【发布时间】:2018-10-23 04:26:32
【问题描述】:
我正在使用 pytest。有两个文件,conftest.py 和 Test1.py。在执行测试之前需要执行特定的方法。现在将其命名为dummy(如果有任何建议将其更改为test_dummy 也可以)。它现在完全可以正常工作。如何将cmd-line 参数传递给这个被显式调用的dummy 方法?
Test1.py
import time
tmp1 = ""
tmp2 = ""
class Test1:
def dummy(self):
global tmp1
global tmp2
tmp1 = "Sometext"
ts = int(time.time())
tmp2 = tmp1 + str(ts)
# Need this `ts` value to be passed from command-line and should be accessed in this `dummy`
# And this dummy to be called before the execution of any tests.
# Could have added this conftest.py , but my requirement is to create a folder by getting method names here. So making a separate `dummy`
def testA(self, set_up):
val = set_up[0]
logging.info(val)
# Do - Something, call some function by passing the `val`
def testB(self, set_up):
val = set_up[0]
logging.info(val)
# Do - Something, call some function by passing the `val`
def testC(self, set_up):
val = set_up[0]
logging.info(val)
# Do - Something, call some function by passing the `val`
class Test2:
def testA(self,set_up):
val = set_up[0]
logging.info(val)
#Do - Something, call some function by passing the `val`
def testB(self,set_up):
val = set_up[0]
logging.info(val)
# Do - Something, call some function by passing the `val`
def testC(self,set_up):
val = set_up[0]
logging.info(val)
# Do - Something, call some function by passing the `val`
obj1 = Test1()
obj1.dummy() #Explicitly calling it.
pytest -s -v test1.py::Test2
conftest.py
import pytest
def tear_down():
print "\nTEARDOWN after all tests"
def pytest_addoption(parser):
parser.addoption(
"--a", action="store", default=None, help="value A")
parser.addoption(
"--b", action="store", default=None, help="value B")
parser.addoption(
"--c", action="store", default=None, help="value C")
parser.addoption(
"--d", action="store", default=None, help="value D") # Need this value to be available in `dummy`
@pytest.fixture(autouse=True)
def set_up(request):
print "\nSETUP before all tests"
if request.function.__name__ == "testA":
return([request.config.getoption("--a"),request.config.getoption("--b"),request.config.getoption("--c")])
elif request.function.__name__ == "testB":
return ([request.config.getoption("--a"), request.config.getoption("--b"), request.config.getoption("--c")])
elif request.function.__name__ == "testC":
return ([request.config.getoption("--a"), request.config.getoption("--b"), request.config.getoption("--c")])
【问题讨论】:
标签: python pytest optional-parameters