A
A
Alexander Leyba2020-08-27 16:18:53
Django
Alexander Leyba, 2020-08-27 16:18:53

How to test model.serialazer ImageField in pytest-django?

test :

def get_image(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
    file_obj = BytesIO()
    image = Image.new("RGBA", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)

@pytest.mark.django_db
def test_valid_poster_serializer():
    """тест PosterSerializer с верными данными"""
    valid_serializer_data = {
        "title": "new poster",
        "description": "poster description",
        "image": get_image(),
        "address": "foo",
        "phones": "89991234586",
        "price": 100,
        "site": "https://foo-bar.com/",
        "latitude": 123456.0,
        "longitude": 123456.0,
        "categories": {
            "title": "new"
        },
    }
    serializer = PosterSerializer(data=valid_serializer_data)
    assert serializer.is_valid()
    assert serializer.validated_data == valid_serializer_data
    assert serializer.data == valid_serializer_data
    assert serializer.errors == {}

Issues:
E         Common items:
E         {'address': 'foo',
E          'categories': OrderedDict([('title', 'new')]),
E          'description': 'poster description',
E          'latitude': 123456.0,
E          'longitude': 123456.0,
E          'phones': '89991234586',
E          'price': 100,
E          'site': 'https://foo-bar.com/',
E          'title': 'new poster'}
E         Differing items:
E         {'image': None} != {'image': <File: test.png>}
E         Full diff:
E           {
E            'address': 'foo',
E         -  'categories': {'title': 'new'},
E         +  'categories': OrderedDict([('title', 'new')]),
E            'description': 'poster description',
E         -  'image': <File: test.png>,
E         +  'image': None,
E            'latitude': 123456.0,
E            'longitude': 123456.0,
E            'phones': '89991234586',
E            'price': 100,
E            'site': 'https://foo-bar.com/',
E            'title': 'new poster',
E           }
tests/tests_poster/test_serializers.py:50: AssertionError

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-09-01
@tumbler

Generally speaking, FileField / ImageField in DRF are usually presented as a download link, but you generally have None, which means the field in the model is not filled. Comparing with a file is useless.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question