Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running django unit tests from shell with ipython notebook has strange behavior

I'm using an ipyhton notebook connected to Django shell to run some tests. I am on django 1.4.

First, if I run as configured below sometimes it works perfectly and other times, it just hangs with no output and no errors. I have to completely kill the ipyhton kernel and close all notebooks and try again (when the hang event occurs, all open notebooks stop working)

If i inherit from unittest.TestCase instead of django.test.TestCase it works perfect every time. However, I need the latter so i can use the django's TestCase.client in my actual tests.

NOTE: In both cases I am skipping the test database because I'm getting a failure on a missing celery database. I will cross that bridge at another time.

The notebook:

from django.utils import unittest
from django.test import TestCase
from django.test.utils import setup_test_environment
from django.test.simple import DjangoTestSuiteRunner


class MyTestCase(TestCase):
    def test_001(self):
        print "ok"
    def test_002(self):
        self.assertEqual(True , True)

if __name__ == '__main__':
    setup_test_environment()
    runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True)
    suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
    #old_config = runner.setup_databases()
    result = runner.run_suite(suite)
    #runner.teardown_databases(old_config)
    runner.suite_result(suite, result)
like image 440
Arctelix Avatar asked Oct 26 '25 03:10

Arctelix


1 Answers

In my case, I just created a test_runner function that accepts a test_class parameter, like this:

def test_runner(test_class):
    from django.utils import unittest
    from django.test.utils import setup_test_environment
    from django.test.simple import DjangoTestSuiteRunner
    setup_test_environment()
    runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=True)
    suite = unittest.TestLoader().loadTestsFromTestCase(test_class)
    result = runner.run_suite(suite)
    runner.suite_result(suite, result)

After that, you could just run:

test_runner(MyTestCase)

in ipython notebook.

Make sure to use the one that's provided by django-extensions, by running:

manage.py shell_plus --notebook

Hope that helps.

like image 97
Emanuel Calso Avatar answered Oct 28 '25 17:10

Emanuel Calso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!