python - Flask app:根据环境实例化一个模拟服务
问题描述
我正在尝试解决一个有趣的问题。我的 Flask 应用程序包含几个服务:
# app.py
...
email_service = EmailService()
notification_service = NotificationService()
third_party_integration = ThirdPartyService()
...
我的问题是,在启动烧瓶应用程序时,您将如何覆盖这些服务并使用该类的模拟版本进行测试?
# There must be a better way!
if app.testing:
email_service = EmailServiceMock() # Should be mocked during server tests (Pytest), but not during E2E tests (CI)
notification_service = NotificationServiceMock()
amazon_s3_client = AmazonS3ClientMock()
third_party_integration = ThirdPartyServiceMock()
else:
email_service = EmailService()
notification_service = NotificationService()
amazon_s3_client = AmazonS3Client()
third_party_integration = ThirdPartyService()
这些 Mock 类继承自原始类并添加额外的功能来支持测试。
我见过一些人将这些服务添加到 Flask 应用程序实例中——对此有什么想法吗?这允许从测试内部访问服务:
def test_endpoint_x(app):
...
assert app.email_service._sent_emails_test_stack > 0
提前致谢!
解决方案
推荐阅读
- cmake - 无法将 TensorFlow C 语言绑定下载为 ExternalProject
- reactjs - 从 WordPress 获取 HTML、CSS、JS 并从 React 应用程序提供它
- php - PHP 错误:解析错误:语法错误,第 82 行的意外标记“<”
- graphql - 涉及分层数据的 GraphQL 中的 Upsert
- unity3d - 如何将布尔值从 true 更改为 false,并在按下按钮后永久保持为 true?
- javascript - 用文本区域中更漂亮的 Unicode 替代品替换数学符号
- flutter - 创建动态下拉列表 - Flutter 问题项读取为零
- laravel - Laravel vue js以模态onClick打开视频不起作用
- python - 我想添加列百分比变化,它给出两行之间平均价格的百分比变化
- python - 数组相当小的 Numpy 内存错误:无法为 Win 10 上的数组分配 359.MiB