[Fixed]-How to test a Django model with pytest?

6👍

You can use this plugin that integrates pytest with Django:
https://pytest-django.readthedocs.org/en/latest/tutorial.html

The setup and changes to pytest.ini are described here:
http://www.johnmcostaiii.net/2013/django-projects-to-django-apps-converting-the-unit-tests/

You will find your example here starting from slide 57.
This deck will be useful in testing views as well as models and the settings specific to testing models: https://speakerdeck.com/pelme/testing-django-applications-with-py-dot-test-europython-2013

Specifically look at @pytest.mark.django_db helper documented here: http://pytest-django.readthedocs.org/en/latest/helpers.html

An example for allowing db access in a test also mentioned in the deck above is copied here. Without mark.django_db the test would fail.

import pytest
@pytest.mark.django_db
def test_user_count():
    assert User.objects.count() == 0
👤Sid

Leave a comment