【问题标题】:Flask Api multiple environments on testingFlask Api 多环境测试
【发布时间】:2017-01-05 20:01:32
【问题描述】:

试试这个example,想知道在使用 unitest 进行 API 测试时什么是正确的方法,如何在 API 测试中加载不同的配置(例如:另一个数据库)?

config.py

​​>
     class BaseConfig(object):
         DEBUG = True
         TESTING = False
         # DATABASE
         SQLALCHEMY_DATABASE_URI = 'postgresql://test:test@localhost:5432/api'   

     class DevelopmentConfig(BaseConfig):
        pass

     class TestingConfig(BaseConfig):
         TESTING = True
         # DATABASE
         SQLALCHEMY_DATABASE_URI = 'postgresql://test:test@localhost:5432/api_testing'

         config = {
             "development": "api.config.DevelopmentConfig",
             "testing": "api.config.TestingConfig",
             "default": "api.config.DevelopmentConfig",
             "production": "api.config.ProductionConfig",
         }

         def configure_app(app):
             config_name = os.getenv('FLAKS_CONFIGURATION', 'default')
             app.config.from_object(config[config_name])

tests.py

​​>
    class DataTestCase(unittest.TestCase):
        def setUp(self):
            self.app = app.test_client()

        def tearDown(self):
            pass

        def test_get_data(self):
            uri = '/data/test'
            resp = self.app.get(uri)
            assert resp.status_code == status.HTTP_200_OK

【问题讨论】:

  • 您的具体问题是什么?正如我所看到的,您已经在 config.py 中处理了不同的配置

标签: python-3.x flask flask-sqlalchemy python-unittest


【解决方案1】:

是的,你可以做到。在运行测试之前,您只需要让应用程序知道您要使用哪种配置。

您的 config.py 文件:

# config.py
class BaseConfig(object):
    pass

class DevelopmentConfig(BaseConfig):
    pass

class TestingConfig(BaseConfig):
    pass

class ProductionConfig(BaseConfig):
    pass

config = {
    'development': DevelopmentConfig,
    'testing': TestingConfig,
    'production': ProductionConfig,

    'default': DevelopmentConfig
}

您创建应用程序的位置:

from .config import config

app = Flask(_name__)
app.config.from_object(config['testing']) # or development, production...

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多