How to spread django unit tests over multiple files?

后端 未结 10 1917
后悔当初
后悔当初 2020-12-07 11:46
  • I have a python-django application
  • I\'m using the unit testing framework
  • The tests are arranged in the file \"tests.py\" in the module directory
相关标签:
10条回答
  • 2020-12-07 12:16

    I think ./manage.py test simply does running all the tests trick (in django >= 1.7).

    If your organizing tests is about grouping and cherrypicking and you are fan of nose use django nose:

    python manage.py test another.test:TestCase.test_method
    

    If you know nose, then you know how to "wildcard" much nicer over all your files.

    PS

    It is just a better practice. Hope that helps. The answer was borrowed from here: Running a specific test case in Django when your app has a tests directory

    0 讨论(0)
  • 2020-12-07 12:18

    If you have a more complicated setup, or don't want to use from ... import *-type statements, you can define a function called suite in your tests.py (or tests/__init__.py), which returns an instance of unittest.TestSuite.

    0 讨论(0)
  • 2020-12-07 12:26

    Note that this approach is no longer valid from Django 1.6, see this post.

    You can create tests folder with ___init___.py inside (so that it becomes a package). Then you add your split test .py files there and import all of them in ___init___.py.

    I.e: Substitute the test.py file with a module that looks and acts like the file:

    Create a tests Directory under the app in question

    app
    app\models.py
    app\views.py
    app\tests
    app\tests\__init__.py
    app\tests\bananas.py
    app\tests\apples.py
    

    Import the submodules into app\tests\__init__.py:

    from bananas import *
    from apples import *
    

    Now you can use ./manage.py as if they were all in a single file:

    ./manage.py test app.some_test_in_bananas
    
    0 讨论(0)
  • 2020-12-07 12:29

    With Django 2.2 a simple and fairly good solution could be to create a test folder inside an app, and you can put your related test_...py files into, just add __init__.py to the test folder.

    0 讨论(0)
  • 2020-12-07 12:32

    http://docs.python.org/library/unittest.html#organizing-tests talks about splitting the files into modules, and the section right above it has an example.

    0 讨论(0)
  • 2020-12-07 12:34

    No need to code anything in init. Just create a subdirectory in your app. Only requirement is not to call it tests* For exemple

    app/
    app/__init_.py
    app/serializers.py
    app/testing/
    app/testing/__init__.py
    app/testing/tests_serializers.py
    
    0 讨论(0)
提交回复
热议问题