Flask Api测试多个环境

时间:2017-01-05 20:01:32

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

尝试这个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

1 个答案:

答案 0 :(得分: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...