简体   繁体   English

Python unittest 测试套件中的实用程序放在哪里?

[英]Where to place utilities in Python unittest test suites?

I am writing unit tests for a largish piece of software written in Python, and there are some tools I wrote to facilitate tests.我正在为 Python 中编写的一个较大的软件编写单元测试,并且我编写了一些工具来促进测试。 I would like to continue using these utilities in another test file.我想在另一个测试文件中继续使用这些实用程序。

The obvious solution is to put these utilities in a separate file next to the tests and load it, eg显而易见的解决方案是将这些实用程序放在测试旁边的单独文件中并加载它,例如

import .utilities as tu

but that fails, because但那失败了,因为

ImportError: attempted relative import with no known parent package

which is fair enough.这很公平。

So my question is: what is the recommended place to put utilities that are solely used for testing?所以我的问题是:建议放置仅用于测试的实用程序的位置是什么?

Let's say your project's name is coolproj .假设您的项目名称是coolproj Assuming that you have the usual structure假设你有通常的结构

coolproj -> coolproj -> __init__.py
                     -> file1.py
                     -> file2.py
                     -> ...
         -> tests -> __init__.py # You need to make `tests` a package!
                  -> utilities.py
                  -> test_file1.py
                  -> test_file2.py
                  -> ...  

Then you can just import your utilities module in, say, test_file1.py via然后你可以通过导入你的utilities模块,比如test_file1.py

from tests import utilities

and in the root directory coolproj (where you should be running your testsuite!) you can run all tests using the test discovery feature在根目录coolproj (你应该在其中运行你的测试套件!)你可以使用测试发现功能运行所有测试

python3 -m unittest

This should cover your question.这应该涵盖您的问题。 By the way, in case your utilities module is not in tests but in coolproj , then the import should be顺便说一下,如果您的utilities模块不在tests中而是在coolproj中,那么导入应该是

from coolproj import utilities

If for some reason you get the message 0 tests run , then you may want to check how exactly you are naming your tests classes and members.如果出于某种原因您收到消息0 tests run ,那么您可能想要检查您命名测试类和成员的准确程度。 In particular, the test discovery feature expects your test modules to be named test_*.py , as exemplified above.特别是,测试发现功能期望您的测试模块被命名为test_*.py ,如上例所示。 Follow the examples in the documentation to name your tests appropriately.按照文档中的示例适当地命名您的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM