使用Flask-testing客戶端,實現mock server自啟動
1.建立mock_server
#mock_server.py from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/user',methods = ['GET']) def mock_user(): return jsonify({'id':1,'name':'Jane','age':18}) if __name__ == '__main__': app.run(port=5000)
2.建立啟動mockserver基類:
#base.py import unittest import mock_server class MockServerUnittest(unittest.TestCase): """use for set up an http server which can use in test""" @classmethod def setUpClass(cls) -> None: cls.app = mock_server.app.test_client()
#此處使用client,無需關閉
3.測試程式應用mockserver基類:
from mock_server import app from flask import Flask from flask_testing import TestCase import unittest class TestUser(TestCase): def create_app(self): return app def test_user(self): response = self.client.get('/api/user') print(response.get_json()) if __name__ == '__main__': unittest.main()