首页 > 解决方案 > 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

提前致谢!

标签: pythonflask

解决方案


推荐阅读