我有以下内容作为conftest.py -->
def pytest_addoption(parser):
parser.addoption("--browser")
parser.addoption("--osType", help="Type of operating system")
parser.addoption("--hostURL", action="store", help="prod, stage, or dev")
@pytest.fixture(scope="session")
def browser(request):
return request.config.getoption("--browser")
@pytest.fixture(scope="session")
def osType(request):
return request.config.getoption("--osType")
@pytest.fixture(autouse=True)
def hostURL(request):
return request.config.getoption("--hostURL")
我想使用 --hostURL 标志来传递值,例如 prod、stage 或 dev。
这是我的 test_TheMainTest.py 的样子 -->
import unitest
import pytest
class CheckStatusCodeTest(unittest.TestCase, LoginPage, CustomSeleniumDriver):
def test_CheckStatusCodeOfPages(self, hostURL):
self.login(hostURL)
当我使用 pytest -q -s --hostURL prod 运行上述测试时,出现以下错误 -->
TypeError: test_CheckStatusCodeOfCRPages() missing 1 required positional argument: 'hostURL'
最佳答案
引用docs :
Note
unittest.TestCase
methods cannot directly receive fixture arguments as implementing that is likely to inflict on the ability to run generalunittest.TestCase
test suites.
但是,您仍然可以使用自动使用装置将常规装置值传递给 unittest
式测试:
class CheckStatusCodeTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def _pass_fixture_value(self, hostURL):
self._hostURL = hostURL
def test_CheckStatusCodeOfPages(self):
assert self._hostURL
您还可以查看this answer of mine解决相同的问题以获取更多示例。
另一种可能性是实现一个显式修改测试类的自动使用装置。如果您有很多应该具有相同设置的测试类,这非常有用:
@pytest.fixture(scope="class")
def set_fixture_value_to_class(request, hostURL):
request.cls._hostURL = hostURL
@pytest.mark.usefixtures('set_fixture_value_to_class')
class CheckStatusCodeTest(unittest.TestCase):
def test_CheckStatusCodeOfPages(self):
assert self._hostURL
@pytest.mark.usefixtures('set_fixture_value_to_class')
class AnotherTest(unittest.TestCase):
def test_spam(self):
assert self._hostURL
在这种情况下,无需将相同的装置复制到每个测试类。只需标记所有相关的测试类(class)即可开始。
关于python - 如何使用 pytest 使用命令行参数在测试中传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030132/