Access to Django Test Server from Django Test

I want to write a unit test that directly executes HTTP requests (instead of using django.test.client.Client).

If you're interested, because I want to check the Thrift-over-HTTP API that I expose from my Django application - and I want to use the Thrift client in the unit test.

The problem is that during the tests the server does not actually start. When using django.test.client.Client, it simply calls the view functions instead of actually creating the HTTP request. (Please correct me if I am wrong.)

So, what would be the best way to get the test environment to start an HTTP server?

I tried writing a bash script that does something like this:

./manage.py testserver --addrport 7000 & PID=$! sleep 5 ./manage.py test --no-input kill $PID 

But this is dirty (and actually does not work), because 1) I need a dream (otherwise the test will start before the database is initialized by the test server), and 2) the test will try to initialize the database again (after the test server has already initialized it).

Any other solutions?

Thanks.

+4
source share
1 answer

Yup, you are right - this is a problem, and there is an error for it: http://code.djangoproject.com/ticket/2879

It’s just that you may run into multi-threaded problems deliberately predicted: http://code.djangoproject.com/ticket/10117 http://code.djangoproject.com/ticket/4513 http://code.djangoproject.com/ticket/3357

I'm upset, so I wrote a library that includes starting a live server in a separate thread and cleaning it up later: http://devel.almad.net/trac/django-sane-testing/ . It also starts a Django server multithreaded with runkey monkeypatching, and you can use cherry http (which is better) instead.

Only problem is that you need to use the nose as a test environment (100% backward compatibility with standard unittest, but if you are already using something else ...). Then you can simply use --with-django and --with-djangoliveserver / - with-cherrypyliveserver. I don’t know how it will work with frugality.

Just beware:

  • Please do not bypass Django devs with bugreports, you yourself
  • A windmill provides the same solution, so if you use a windmill, you are likely to have port conflicts.
+7
source

Source: https://habr.com/ru/post/1286399/


All Articles