How to stop testserver from within a test case?

45 views
Skip to first unread message

Arun Marathe

unread,
Nov 18, 2014, 10:50:53 AM11/18/14
to django...@googlegroups.com

We have Django 1.6.

For a somewhat obscure reason, I need to stop the testserver from within a test case. Any ideas?
I would like a programmatic solution if possible. Finding a process and killing it (ps -ef., then grep,
then kill) is bit of a hack, and may end up killing unintended processes.

Note that I want the testserver stopped for a small number of test cases. For the rest of them, the
testserver should be running as it always does.

Thanks,
Arun

Erik Cederstrand

unread,
Nov 18, 2014, 12:27:37 PM11/18/14
to Django Users
> Den 18/11/2014 kl. 16.50 skrev Arun Marathe <ap.ma...@gmail.com>:
>
> For a somewhat obscure reason, I need to stop the testserver from within a test case. Any ideas?
> I would like a programmatic solution if possible. Finding a process and killing it (ps -ef., then grep,
> then kill) is bit of a hack, and may end up killing unintended processes.

By "test server" I assume you mean the built-in Django development server.

The development server is running in a completely different process from your test case, so your options are somewhat limited. The development server does a really good job of staying alive, so you can't raise KeyboardInterrupt or sys.exit() because the development server will simply restart.

I would probably create a special view that you van call from your test case, e.g. GET http://localhost:8000/killme, which finds the process ID of itself (the development server) and signals it to stop. Something like this:


class KillMe(View):
def get(request):
import os
import signal
pid = os.getpid()
os.kill(pid, signal.SIGINT)


Depending on your needs, you might need to let your test case wait until the development server process has actually terminated.

Erik
Reply all
Reply to author
Forward
0 new messages