[英]pytest will not run the test files in subdirectories
我是 pytest 的新手,並試圖運行一個簡單的測試來檢查 pytest 是否有效。 我使用的是 Windows 10、python 3.8.5 和 pytest 6.0.1。
這是我的項目目錄:
projects/
tests/
__init__.py
test_sample.py
這是我放在 test_sample.py 中的內容:
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
如果我執行以下操作:
> pytest
the test run fine (1 failed in 0.004s)
> pytest tests/test_sample.py
the test run fine (1 failed in 0.006s)
但是,如果我這樣做:
> pytest test_sample.py
它會返回這樣的消息:
no test ran in 0.000s
ERROR: file not found: test_sample.py
我嘗試刪除__init__.py
文件,但結果還是一樣。 另外,我在 2 台不同的計算機上嘗試過這個,但沒有任何改變。 如果問題無法解決,我可以忽略它並繼續我的解決方案嗎?
使用 pytest 配置項目的“最佳實踐”方法是使用配置文件。 最簡單的解決方案是一個pytest.ini
,它看起來像這樣:
# pytest.ini
[pytest]
testpaths = tests
這將配置testpaths
相對於你的rootdir
(pytest會告訴你這兩個路徑是什么,只要你運行它)。 這回答了您在問題中提出的具體問題。
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
您的示例是關於從命令行運行特定測試。 從args
查找rootdir
的完整規則集有些人為。
您應該注意到 pytest 目前支持您的測試和模塊的兩種可能的布局。 pytest 文檔目前強烈建議使用src
layout 。 回答使用__init__.py
的重要性在一定程度上取決於前者,但是選擇配置文件和布局仍然優先於您選擇如何使用__init__.py
來定義您的包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.