Flask可以使用unittest或者pytest进行测试。

使用unittest进行测试:

  1. 创建测试文件,例如test.py。

  2. 导入Flask和unittest模块。

from flask import Flask
import unittest
  1. 创建测试类,继承unittest.TestCase。
class TestFlask(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['TESTING'] = True
        self.client = self.app.test_client()
    
    def tearDown(self):
        pass
  1. 编写测试方法。
def test_index(self):
    response = self.client.get('/')
    self.assertEqual(response.status_code, 200)
    self.assertIn(b'Hello, World!', response.data)
  1. 在测试文件中加入main方法,运行测试。
if __name__ == '__main__':
    unittest.main()

使用pytest进行测试:

  1. 安装pytest模块。
pip install pytest
  1. 创建测试文件,例如test.py。

  2. 编写测试方法。

def test_index():
    app = Flask(__name__)
    app.config['TESTING'] = True
    client = app.test_client()
    response = client.get('/')
    assert response.status_code == 200
    assert b'Hello, World!' in response.data
  1. 在命令行中进入测试文件所在目录,运行pytest。
pytest test.py
flask怎么测试

原文地址: https://www.cveoy.top/t/topic/b5OG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录