Sil*_*ash 8 selenium pytest python-3.x
我正在为网络应用程序构建一个测试套件。我使用的固定装置如下:
import pytest
from selenium import webdriver
from common import Common
@pytest.fixture(scope='module')
def driver(module, headless=True):
opts = webdriver.FirefoxOptions()
opts.add_argument('--headless') if headless else None
driver = webdriver.Firefox(options=opts)
driver.get('http://localhost:8080/request')
yield driver
driver.quit()
def test_title(driver):
assert driver.title == 'abc'
if __name__ == '__main__':
test_title() #what I need to execute to see if everything is fine
Run Code Online (Sandbox Code Playgroud)
假设我需要test_title通过直接在if __name__ == '__main__':. 如何使用test_title()作为参数传入的驱动程序进行调用?
调用test_title如下:
if __name__ == '__main__':
test_title(driver(None, False))
Run Code Online (Sandbox Code Playgroud)
python 产生如下错误:
(virtual) sflash@debian:~/Documents/php/ufj/ufj-test$ ./test_r*
Traceback (most recent call last):
File "./test_request.py", line 30, in <module>
test_empty_all(driver(None, headless=True))
File "/home/sflash/Documents/php/ufj/ufj-test/virtual/lib/python3.7/site-packages/_pytest/fixtures.py", line 1176, in result
fail(message, pytrace=False)
File "/home/sflash/Documents/php/ufj/ufj-test/virtual/lib/python3.7/site-packages/_pytest/outcomes.py", line 153, in fail
raise Failed(msg=msg, pytrace=pytrace)
Failed: Fixture "driver" called directly. Fixtures are not meant to be called directly,
but are created automatically when test functions request them as parameters.
See https://docs.pytest.org/en/stable/fixture.html for more information about fixtures, and
https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly about how to update your code.
Run Code Online (Sandbox Code Playgroud)
MrB*_*men 12
正如评论中所讨论的,装置不能直接调用 - 它们只能与pytest.
要直接从代码调用测试,您可以pytest.main()在您的部分中调用,这与在命令行上__main__调用具有相同的效果。pytest任何命令行选项都可以作为参数添加到调用中(作为列表),例如:
if __name__ == '__main__':
pytest.main(['-vv', 'test.py::test_title'])
Run Code Online (Sandbox Code Playgroud)
要在不涉及 pytest 的情况下使用驱动程序(这是您的意图),您必须提取驱动程序逻辑并从固定装置和主程序中分别调用它:
import pytest
from selenium import webdriver
from common import Common
def get_driver(headless=True):
opts = webdriver.FirefoxOptions()
opts.add_argument('--headless') if headless else None
driver = webdriver.Firefox(options=opts)
driver.get('http://localhost:8080/request')
return driver
):
@pytest.fixture(scope='module')
def driver():
yield get_driver()
driver.quit()
def test_title(driver):
assert driver.title == 'abc'
if __name__ == '__main__':
driver = get_driver()
test_title(driver)
driver.quit()
Run Code Online (Sandbox Code Playgroud)
请注意,只有当测试函数不依赖于任何 pytest 特定的东西(例如自动应用的装置)时,这才有效。
另请注意,您不能像在示例中那样在夹具中使用参数,因为您无法提供该参数。相反,您可以使用参数化夹具。
| 归档时间: |
|
| 查看次数: |
14655 次 |
| 最近记录: |