python如何测试仪器_如何测试pytest设备本身?
pytest有一個^{}插件,它是為了測試pytest本身和插件而設計的;它在一個獨立的運行中執行不影響當前測試運行的測試。示例:# conftest.py
import pytest
pytest_plugins = ['pytester']
@pytest.fixture
def spam(request):
yield request.param
fixture spam有一個問題,它只能與參數化測試一起工作;一旦在非參數化測試中請求它,它將引發一個AttributeError。這意味著我們不能通過這樣的常規測試進行測試:
^{pr2}$
相反,我們使用testdir插件提供的testdirfixture在獨立的測試運行中執行測試:import pathlib
import pytest
# an example on how to load the code from the actual test suite
@pytest.fixture
def read_conftest(request):
return pathlib.Path(request.config.rootdir, 'conftest.py').read_text()
def test_spam_fixture(testdir, read_conftest):
# you can create a test suite by providing file contents in different ways, e.g.
testdir.makeconftest(read_conftest)
testdir.makepyfile(
"""
import pytest
@pytest.mark.parametrize('spam', ('eggs', 'bacon'), indirect=True)
def test_spam_parametrized(spam):
assert spam in ['eggs', 'bacon']
def test_spam_no_params(spam):
assert True
""")
result = testdir.runpytest()
# we should have two passed tests and one failed (unarametrized one)
result.assert_outcomes(passed=3, error=1)
# if we have to, we can analyze the output made by pytest
assert "AttributeError: 'SubRequest' object has no attribute 'param'" in ' '.join(result.outlines)
為測試加載測試代碼的另一個方便的方法是testdir.copy_example方法。在pytest.ini中設置根路徑,例如:[pytest]
pytester_example_dir = samples_for_fixture_tests
norecursedirs = samples_for_fixture_tests
現在創建包含以下內容的文件samples_for_fixture_tests/test_spam_fixture/test_x.py:import pytest
@pytest.mark.parametrize('spam', ('eggs', 'bacon'), indirect=True)
def test_spam_parametrized(spam):
assert spam in ['eggs', 'bacon']
def test_spam_no_params(spam):
assert True
(這與之前作為字符串傳遞給testdir.makepyfile的代碼相同)。上述試驗變更為:def test_spam_fixture(testdir, read_conftest):
testdir.makeconftest(read_conftest)
# pytest will now copy everything from samples_for_fixture_tests/test_spam_fixture
testdir.copy_example()
testdir.runpytest().assert_outcomes(passed=3, error=1)
這樣,您就不必在測試中將Python代碼維護為字符串,還可以通過使用pytester來重用現有的測試模塊。也可以通過pytester_example_path標記配置測試數據根:@pytest.mark.pytester_example_path('fizz')
def test_fizz(testdir):
testdir.copy_example('buzz.txt')
將查找與項目根目錄相關的文件fizz/buzz.txt。在
對于更多的例子,一定要查看pytest文檔中的Testing plugins部分;而且,您可能會發現my other answer對問題How can I test if a pytest fixture raises an exception?很有幫助,因為它包含了該主題的另一個工作示例。我還發現直接研究^{} code非常有幫助,因為遺憾的是,pytest沒有為它提供大量的文檔,但是代碼幾乎是自文檔化的。在
總結
以上是生活随笔為你收集整理的python如何测试仪器_如何测试pytest设备本身?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在页面插入一个跟随页面移动的盒子_w
- 下一篇: python分布式框架有哪些_Pytho