簡體   English   中英

為什么 pytest 在僅運行一部分測試時不加載 conftest.py?

[英]Why doesn't pytest load conftest.py when running only a subset of tests?

這是我的 API 測試目錄布局:

api_tests
├── conftest.py
└── query
    └── me_test.py

conftest.py 的內容:

print("CONFTEST LOADED")

me_test.py 的內容:

"""Tests the "me" query"""

def test_me():
    assert True

如果我只是運行pytest ,一切正常:

================================================= test session starts =================================================
platform linux -- Python 3.8.5, pytest-6.1.0, py-1.9.0, pluggy-0.13.1
rootdir: /home/hubro/myproject, configfile: pytest.ini
collecting ... CONFTEST LOADED
collected 3 items                                                                                                     

api_tests/query/me_test.py .                                                                                    [ 33%]
lib/myproject/utils_test.py .                                                                                   [ 66%]
lib/myproject/schema/types/scalars_test.py .                                                                    

注意打印“CONFTEST LOADED”。 偉大的! 但是,此測試運行還包含了我不想要的所有單元測試。 我想將我的測試運行分為單元測試和 API 測試,我不想一次性運行它們。

但是,如果我只是運行pytest api_tests/

================================================= test session starts =================================================
platform linux -- Python 3.8.5, pytest-6.1.0, py-1.9.0, pluggy-0.13.1
rootdir: /home/hubro/myproject, configfile: pytest.ini
collected 1 item                                                                                                      

api_tests/query/me_test.py .                                                                                    [100%]

================================================== 1 passed in 0.00s ==================================================

現在運行了正確的測試,但是沒有加載 conftest.py 文件......怎么會?


我在 Python 3.8 上使用 Pytest 6.1.0。


編輯:好的,我找到了一個可以接受的解決方法。 我可以通過命令行使用-o選項覆蓋 INI 文件選項。 這有效:

poetry run pytest -o "testpaths=api_tests"

但是,我非常想要原始問題的答案,因此我不會將其刪除。

conftest插件將在兩次調用中注冊,唯一的區別是注冊階段。 如果有疑問,請添加--traceconfig參數以按注冊順序列出已注冊的插件:

$ pytest --traceconfig
PLUGIN registered: <_pytest.config.PytestPluginManager object at 0x7f23033ff100>
PLUGIN registered: <_pytest.config.Config object at 0x7f2302d184c0>
...
=================================== test session starts ===================================
...
PLUGIN registered: <module 'conftest' from 'path/to/conftest.py'>
...

在第一次調用中, conftest.py不會立即被找到,因為它位於測試根路徑下,所以它會在pytest發現測試時加載。 在第二次調用中, conftest.py位於測試根目錄中,因此它甚至會在測試會話開始之前加載(在加載通過-p arg 傳遞並通過setuptools入口點注冊的插件之后)。 運行pytest -s (禁用輸出捕獲)應該顯示位於==== test session starts ====行上方的自定義打印。

如果您希望兩次調用之間的打印相同,請將其放在合適的掛鈎中。 例如,要在測試收集完成后始終打印CONFTEST loaded ,請使用:

# api_tests/conftest.py

def pytest_collectreport(report):
    print("CONFTEST loaded")

還有其他選項可用於自定義輸出放置; 最好是查看pytest參考中Hooks下的可用鈎子列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM