Ivan Z. Horvat
Ivan Z. Horvat

Reputation: 395

Flask Api multiple environments on testing

Trying this example, wonder what is a right way when doing API tests with unitest, how to load different config(ex: another db) on API tests?

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

Upvotes: 0

Views: 705

Answers (1)

DonerKebab
DonerKebab

Reputation: 520

Yes, you can do it. Before run the test, you just need to let application know which configuration you want to use.

Your config.py file:

# 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
}

Where you create application:

from .config import config

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

Upvotes: 1

Related Questions