为什么 PyCharm 无法通过 运行 单元测试?

Why does PyCharm fail to run unit tests?

在我的 PyCharm (2016.3.3) 项目中,我有一个名为 'tests' 的包文件夹,其中包含一些测试模块(使用 unittest),例如'test_A.py,' 'test_B.py.'

当我尝试 运行 这些模块之一中的测试,或整个 'tests' 包中的所有测试时,由于 AttributeError: 'module' object has no attribute 'test_A',我得到了 nose_helper.failure.Failure (其他测试模块也一样)。

当我 运行 PyCharm 之外的模块时,它们可以正常工作。

有谁知道原因,如何解决?

这里有很多类似的问题,例如1, 2, 3,等等,但其中 none 解决了我的问题。

不知道确切原因,但在我的 PyCharm (2016.3.3) 中,我能够通过编辑 运行 配置解决问题:

从菜单栏 select 运行->编辑配置,然后 select 您的配置,并在 "Unittests" 下的 "Configuration" 选项卡中检查 "Inspect only subclasses of unittest.TestCase."

要设为默认值:运行 -> 编辑配置,然后 select 默认值 -> Python 测试 -> 单元测试,然后再次选中相同的框。

此答案基于 ancient PyCharm support post

--编辑--

如果测试模块试图导入不存在的 class,这也会发生(在 PyCharm 2018.3),例如(使用 django)from myapp.models import MyModelA, MyModelB 其中 MyModelB 不存在。在这种情况下,修复导入应该可以解决问题。