I
I
IvanOne2019-06-18 07:29:05
Django
IvanOne, 2019-06-18 07:29:05

How to organize tests in django at the app level?

I am doing a project on django and rest framework, I want to make tests at the application level, I use pytest. That is, I have a tests directory in each app and there are already modules with tests, the question is how to test view classes at the app level, without registering paths in the root urls.py. Is it possible, for example, to create a request object yourself and throw it into the view class? The goal is to make django app's as reusable as possible

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alternativshik, 2019-06-18
@IvanOne

Something like this

def test_product_list_view(user: UserFactory, api_request_factory: APIRequestFactory):
    view = ProductListView.as_view()
    # Make an authenticated request to the view...
    # Урл можно писать любой
    request = api_request_factory.get('/api/v1/products/')
    force_authenticate(request, user=user)
    response = view(request)
    assert response.status_code == 200

M
marazmiki, 2019-06-18
@marazmiki

Purely subjective, it is better to choose one of one: either place tests at the application level, or use pytest.
Keeping tests inside applications is useful when using a standard jung test runner: it knows and knows how to find and run them. Pytest is not a native django tool, so it uses its own test discovery mechanism.
If you're specifically targeting reusable apps (I guess that means separating them into separate packages and placing them in indexes like PyPI or your own private ones?), I would recommend doing the following:

  • Write tests using pytest. It is much more powerful and more convenient than the native jung runner.
  • Place tests outside the python package directory, i.e. of your django app, and don't put them in the package archive at all. In the end, tests are about development, not about production, they are not needed on a combat vehicle
  • Create a minimalistic django project inside the tests directory and do not add a link to your application's URLConf in its urls
  • And as a result, don't be afraid to test views as if they were already part of the project (and indeed they are). Of course, no one will forbid constructing a request object and calling views like ordinary functions, passing this request as the first argument, but we are not testing for coverage, but for it to work, right?
  • Didn't find what you were looking for?

    Ask your question

    Ask a Question

    731 491 924 answers to any question