pytest-django
pytest-django copied to clipboard
Not able to reset django form field initial value
I have a django form with a field defined like this:
myField = forms.CharField(
widget=forms.HiddenInput(),
initial=f"2023-{settings.FIELD_BASE}",
)
I'm writing a test where I'd like to use @pytest.mark.parametrize
to test different values of FIELD_BASE
. Something like:
@pytest.mark.parametrize("test_base", ["aa", "bb", "cc"])
def test_bases(self, client, settings, test_base):
settings.FIELD_BASE = test_base
response = client.get(reverse(someview))
assert f'name="myField" value="2023-{test_base}" in response.content
This does not work. My hunch is that it's because initial
is set when the module is loaded at the beginning of the test run. So I tried reloading, adding the two lines after the settings update:
settings.FIELD_BASE = test_base
import importlib
importlib.reload('myapp.forms')
Still no luck.
Any thoughts on how to handle this?
My hunch is that it's because initial is set when the module is loaded at the beginning of the test run.
Right.
Any thoughts on how to handle this?
Try using a callable:
myField = forms.CharField(
widget=forms.HiddenInput(),
initial=lambda: f"2023-{settings.FIELD_BASE}",
)
If this doesn't work, I think mocking myField.initial
directly would work.