【问题标题】:Why are my App tests not being recognized by Django tests? [duplicate]为什么我的 App 测试没有被 Django 测试识别? [复制]
【发布时间】:2013-09-04 05:55:51
【问题描述】:

背景:

我有以下 django 项目设置:

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

这是 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)

现在,当我跑步时:

> python manage.py test app1

我得到以下输出:

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

但是,如果我改为使用以下项目结构:

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

其中tests.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)

现在,当我跑步时:

> python manage.py test app1

我明白了:

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

问题:

为什么 Django 无法识别我的 Tests 目录 && 为什么在 Tests/ 中列出的任何测试都不会被 Django 的 unittest 结构拾取运行?

【问题讨论】:

    标签: python django django-testing python-unittest django-tests


    【解决方案1】:

    睡个好觉,甚至不用考虑测试发现的一个选择是使用nose。它有很多功能,其中之一是automatic tests discovery

    有一个名为 django_nose 的包可以帮助您将 django 项目与鼻子集成:

    特点

    在你的 Django 测试中,鼻子的所有优点,比如......

    • ...
    • 无需将所有测试导入tests/__init__.py。这不仅可以节省繁忙的工作,还可以消除意外影响测试课程的可能性。
    • ...

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      您需要将Tests 更改为tests 并将每个测试导入tests/__init__.py,直到django 1.5 AFAIK。还有一个test runner 将按照unittest2 发现的工作方式工作。此功能已集成到 django1.6 中。

      【讨论】:

        【解决方案3】:

        看看:running tests in Django

        测试发现基于 unittest 模块的内置测试发现。默认情况下,这将发现当前工作目录下任何名为“test*.py”的文件中的测试。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-18
          • 2021-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-16
          • 1970-01-01
          相关资源
          最近更新 更多