I am testing my serializer in Django Rest Framework with pytest.
Here are my modules versions:
python 3.8.8
django==3.2.5
djangorestframework==3.12.4
pytest==6.2.4
Here is my test_serializers.py file:
from my_app.serializers import my_serializer
class TestMySerializer:
def setup(self):
self.serializer = my_serializer
@pytest.mark.parametrize(
"input",
[
{
"a": ["test"],
"b": ["test"],
"c": ["test"],
},
],
)
def test_valid_serializer(self, input):
ser = self.serializer(data=input)
assert ser.is_valid()
@pytest.mark.parametrize(
"input",
[
{"a": ["test"]},
],
)
def test_invalid_formats(self, input):
ser = self.serializer(data=input)
assert not ser.is_valid()
And of course my serializers.py file is:
class my_serializer(Serializer):
a = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True))
b = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True))
c = ListField(child=CharField(max_length=255, allow_null=True, allow_blank=True))
The test_valid_serializer test passes without any problem because the input is valid for the serializer. OK ✅
The test_invalid_formats should pass as well because the input is not valid for the serializer. But unfortunately this test doesn't pass and this error occurs:
django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Following this stackoverflow post, I added a DJANGO_SETTINGS_MODULE variable pointing to my settings.py file. When I try again my test, the following error occurs:
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.
So my questions are:
- Why does my first test test_valid_serializer run without any problems but my second test test_invalid_formats raises Django errors while the assertion seems to be correct?
- Is there a problem with the .is_valid() function?
- How can I solve my problem?
Thank you for your help