简体   繁体   English

pytest 不会运行子目录中的测试文件

[英]pytest will not run the test files in subdirectories

I am new to pytest and trying to run a simple test to check if pytest works.我是 pytest 的新手,并试图运行一个简单的测试来检查 pytest 是否有效。 I'm using windows 10, python 3.8.5 and pytest 6.0.1.我使用的是 Windows 10、python 3.8.5 和 pytest 6.0.1。

Here is my project directory:这是我的项目目录:

projects/  
 tests/    
  __init__.py   
  test_sample.py

Here is what I put in test_sample.py:这是我放在 test_sample.py 中的内容:

def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5

if I do the following:如果我执行以下操作:

> pytest 
the test run fine (1 failed in 0.004s)
> pytest tests/test_sample.py 
the test run fine (1 failed in 0.006s) 

However, if I do this:但是,如果我这样做:

> pytest test_sample.py

It will return a message like this:它会返回这样的消息:

no test ran in 0.000s
ERROR: file not found: test_sample.py

I tried deleting __init__.py file but the result was still the same.我尝试删除__init__.py文件,但结果还是一样。 Also, I have tried this on 2 different computers but nothing changed.另外,我在 2 台不同的计算机上尝试过这个,但没有任何改变。 In case the problem can't be solved, can I just ignore it and move on with the solutions I'm having?如果问题无法解决,我可以忽略它并继续我的解决方案吗?

The "best practices" approach to configuring a project with pytest is using a config file .使用 pytest 配置项目的“最佳实践”方法是使用配置文件 The simplest solution is a pytest.ini that looks like this:最简单的解决方案是一个pytest.ini ,它看起来像这样:

# pytest.ini
[pytest]

testpaths = tests

This configures the testpaths relative to your rootdir (pytest will tell you what both paths are whenever you run it).这将配置testpaths相对于你的rootdir (pytest会告诉你这两个路径是什么,只要你运行它)。 This answers the specific problem you raised in your question.这回答了您在问题中提出的具体问题。

C:\YourProject  <<-- Run pytest on this path and it will be considered your rootdir.
│
│ pytest.ini
│ your_module.py
│
├───tests       <<-- This is the directory you configured as testpaths in pytest.ini
│     __init__.py
│     test_sample.py

Your example was about running specific tests from the command line.您的示例是关于从命令行运行特定测试。 The complete set of rules for finding the rootdir from args is somewhat contrived. args查找rootdir的完整规则集有些人为。

You should notice that pytest currently supports two possible layouts for your tests and modules.您应该注意到 pytest 目前支持您的测试和模块的两种可能的布局 It's currently strongly suggested by pytest documentation to use a src layout . pytest 文档目前强烈建议使用src layout Answering about the importance of using __init__.py depends on the former to an extent, however choosing a configuration file and layout still takes precedence over how you choose to use __init__.py to define your packages.回答使用__init__.py的重要性在一定程度上取决于前者,但是选择配置文件和布局仍然优先于您选择如何使用__init__.py来定义您的包。

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

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