python - 如何使用 pytest 使用命令行参数在测试中传递值?

标签 python selenium pytest

我有以下内容作为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 general unittest.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/

相关文章:

python - 聚类问题

python - 如何根据第一个数组的元素从另一个数组中减去一个 NumPy 数组

python - 我正在写一个函数来查找数字是否是回文。它在第2行给了我一个运行时错误,这是函数定义的行[closed]

python - Pytest cov 不生成任何报告

python - 如何在 py.test 运行中多次重复每个测试?

python - 在 Pytest 中,根级别的 conftest.py 是否会被树中更深处的 conftest 覆盖?

python - 如何使用 PySerial 从 COM 端口读取和写入?

java - 未应用last()

java - 使用 JMeter 和 Selenium 并行进行负载测试

c# - NUnit - 默认重试异常