Should Python unittests be in a separate module?

后端 未结 7 2006
攒了一身酷
攒了一身酷 2021-02-12 16:44

Is there a consensus about the best place to put Python unittests?

Should the unittests be included within the same module as the functionality being tested (executed wh

相关标签:
7条回答
  • 2021-02-12 17:08

    YES, do use a separate module.

    It does not really make sense to use the __main__ trick. Just assume that you have several files in your module, and it does not work anymore, because you don't want to run each source file separately when testing your module.

    Also, when installing a module, most of the time you don't want to install the tests. Your end-user does not care about tests, only the developers should care.

    No, really. Put your tests in tests/, your doc in doc, and have a Makefile ready around for a make test. Any other approaches are just intermediate solutions, only valid for specific tiny modules.

    0 讨论(0)
  • 2021-02-12 17:14

    Personally, I create a tests/ folder in my source directory and try to, more or less, mirror my main source code hierarchy with unit test equivalents (having 1 module = 1 unit test module as a rule of thumb).

    Note that I'm using nose and its philosophy is a bit different than unittest's.

    0 讨论(0)
  • 2021-02-12 17:19
    1. Where you have to if using a library specifying where unittests should live,
    2. in the modules themselves for small projects, or
    3. in a tests/ subdirectory in your package for larger projects.

    It's a matter of what works best for the project you're creating.

    Sometimes the libraries you're using determine where tests should go, as is the case with Django (where you put your tests in models.py, tests.py or a tests/ subdirectory in your apps).

    If there are no existing constraints, it's a matter of personal preference. For a small set of modules, it may be more convenient to put the unittests in the files you're creating.

    For anything more than a few modules I create the tests separately in a tests/ directory in the package. Having testing code mixed with the implementation adds unnecessary noise for anyone reading the code.

    0 讨论(0)
  • 2021-02-12 17:27

    I usually have them in a separate folder called most often test/. Personally I am not using the if __name__ == '__main__' check, because I use nosetests and it handles the test detection by itself.

    0 讨论(0)
  • 2021-02-12 17:31

    if __name__ == '__main__', etc. is great for small tests.

    0 讨论(0)
  • 2021-02-12 17:33

    I generally keep test code in a separate module, and ship the module/package and tests in a single distribution. If the user installs using setup.py they can run the tests from the test directory to ensure that everything works in their environment, but only the module's code ends up under Lib/site-packages.

    0 讨论(0)
提交回复
热议问题