Flask Api 多环境测试
Flask Api multiple environments on testing
尝试这个 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 文件:
# 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...
尝试这个 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 文件:
# 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...