How to test a Django model with pytest?

后端 未结 2 1787
花落未央
花落未央 2021-02-08 05:12

I am getting started with pytest. I have configured pytest, anyway I couldn\'t found a resource on Django specific testing with pytest. How do I test a model with pytest_d

2条回答
  •  无人及你
    2021-02-08 05:41

    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
    

提交回复
热议问题