【问题标题】:Django 1.8 - How do I test a specific file inside a tests folder?Django 1.8 - 如何测试测试文件夹中的特定文件?
【发布时间】:2016-01-27 12:13:48
【问题描述】:

这是我的目录

CMSApp/tests/test_page.py
CMSApp/tests/test_user.py
CMSApp/models.py
CMSApp/views.py

我只想测试test_page.py。我可以这样做:

python manage.py test CMSApp/tests

但这将同时测试test_page.pytest_user.py。当我尝试时

python manage.py test CMSApp/tests/test_page

上面写着:

No module named CMSApp/tests/test_page

当我尝试时:

python manage.py test CMSApp/tests/test_page.py 上面写着NoneType object is not iterable

【问题讨论】:

标签: python django django-unittest


【解决方案1】:
python manage.py test CMSApp.tests.test_page

您需要在tests 目录中有__init__.py 才能使其成为一个模块。

【讨论】:

    【解决方案2】:
    python manage.py test tests.main.testMainPage.MainPageTests
    

    其中 tests 和 main 是文件夹,需要有 init.py 文件,testMainPage 是 main 中的一个文件,而 MainPageTests 是该文件的一个类。

    树视图:

    tests
    ├── __init__.py
    ├── main
    │   ├── __init__.py
    │   ├── testMainPage.py
    

    MainPageTests 类将保存您的所有测试 示例:

    class MainPageTests(TestCase):
        def test_my_view(self):
        pass
    

    【讨论】:

    • 我的文件结构在tests 中没有main 文件夹。如果没有tests 中的main 文件夹,我该如何完成任务?
    • @user2719875 是的,这是可能的,您将运行 python manage.py test tests.testMainPage.MainPageTests
    • 它对你有用吗?当我执行python manage.py test tests.test_user.UserTests 时,它会出现错误提示AttributeError: 'module' object has no attribute 'test_user'
    【解决方案3】:

    有几种方法可以只运行特定的测试,如文档中的explained

    # Run all the tests in the animals.tests module
    $ ./manage.py test animals.tests
    
    # Run all the tests found within the 'animals' package
    $ ./manage.py test animals
    
    # Run just one test case
    $ ./manage.py test animals.tests.AnimalTestCase
    
    # Run just one test method
    $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak
    
    # You can also provide a path to a directory to discover tests below that directory:
    
    $ ./manage.py test animals/
    
    # You can specify a custom filename pattern match using the -p (or --pattern)
    # option, if your test files are named differently from the test*.py pattern:
    
    $ ./manage.py test --pattern="tests_*.py"
    

    我发现使用--pattern 参数特别方便,您可以只提供测试文件名的唯一部分。例如,在您的情况下,您可以只写:

    python manage.py test --pattern "*test_page*"
    

    这样您甚至不必查找测试文件的整个路径。

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      相关资源
      最近更新 更多