dynaconf icon indicating copy to clipboard operation
dynaconf copied to clipboard

[RFC] Pytest fixture to override settings dynamically

Open maroux opened this issue 5 years ago • 3 comments

Is your feature request related to a problem? Please describe. It would be useful to be able to write tests like this:

def test_foo_bar(settings):
    settings.FOO = "bar"

def test_foo_not(settings):
    settings.FOO = "not"

The existing pytest solution relies on use of environments to switch to testing, and thus doesn't support dynamic values.

Describe the solution you'd like A new utility method on LazySettings that allows temporarily overriding values in tests

class LazySettings:
    ...
    def override():
        ...
        yield
        ...

in app:

@pytest.fixture
def override_settings():
    with settings.override() as wrapped:
        yield wrapped

Describe alternatives you've considered

  • Tried mocking dynaconf.store doesn't seem to work well.
  • Tried using_env but I don't really use environments, so there's no "testing" environment here to get default values from.

Additional context

maroux avatar Oct 01 '20 22:10 maroux

Update: this .. kinda works?

@pytest.fixture(autouse=True)
def settings_reset():
    settings.reload()
    settings.validators.validate()

maroux avatar Oct 01 '20 23:10 maroux

Not sure why validators.validate() isn't called in reload - I added some default values using validation which seem to get blown away on reload.

maroux avatar Oct 01 '20 23:10 maroux

We can implement a fixture like that using from_env method.

https://www.dynaconf.com/advanced/#from_env

this gives us a new copy of the settings instance.

The reload should call validators and also keep the default values, probably a bug.

rochacbruno avatar Oct 02 '20 13:10 rochacbruno