Search code examples
pythondjangodjango-testingpython-unittestdjango-tests

Why are my App tests not being recognized by Django tests?


Background:

I have the following django project setup:

>TopLevel:
>  - App1:
>      * models.py
>      * forms.py
>      * views.py
>      * __init__.py
>      * Tests/
>        * __init__.py
>        * test_simple.py

Here is the code in test_simple.py:

from django.test import TestCase


class SimpleTest(TestCase):
    def test_basic_addition(self):
        """
        Tests that 1 + 1 always equals 2.
        """
        self.assertEqual(1 + 1, 2)

Now, when I run:

> python manage.py test app1

I get the following output:

>Creating test database for alias 'default'...
>
>----------------------------------------------------------------------
>Ran 0 tests in 0.000s
>
>OK
>Destroying test database for alias 'default'...

But, if I instead use the following project structure:

>TopLevel:
>  - App1:
>      * models.py
>      * forms.py
>      * views.py
>      * __init__.py
>      * tests.py

Where tests.py has the following code:

from django.test import TestCase


class SimpleTest(TestCase):
    def test_basic_addition(self):
        """
        Tests that 1 + 1 always equals 2.
        """
        self.assertEqual(1 + 1, 2)

Now, when I run:

> python manage.py test app1

I get:

>Creating test database for alias 'default'...
>.
>----------------------------------------------------------------------
>Ran 1 test in 0.002s
>
>OK
>Destroying test database for alias 'default'...

Question:

Why does Django not recognize my Tests directory && why won't any tests listed inside Tests/ be picked up by Django's unittest structure to run?


Solution

  • One option to have a good sleep and don't even think about test discovery is to use nose. It has a lot features, one of it is automatic tests discovery.

    There is package called django_nose that will help you to integrate your django project with nose:

    Features

    All the goodness of nose in your Django tests, like...

    • ...
    • Obviating the need to import all your tests into tests/__init__.py. This not only saves busy-work but also eliminates the possibility of accidentally shadowing test classes.
    • ...

    Hope that helps.