Как передать аргумент строки cmd в метод в test_file (pytest)? - PullRequest
0 голосов
/ 23 октября 2018

Я использую 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")])

Ответы [ 2 ]

0 голосов
/ 23 октября 2018

Вы можете использовать pytest_addoption :

def pytest_addoption(parser):
    parser.addoption("--dummy", action="store", default="dummy")

, который добавляет новый параметр командной строки с именем dummy, к которому затем можно получить доступ в приборе с помощью:

request.config.getoption("--dummy")

например,

@pytest.fixture
def dummy(request):
    dummy_val = request.config.getoption("--dummy")

Обратите внимание, что, сделав таким образом манекен приспособлением, вы сможете автоматически запускаться перед всеми тестами обычным способом pytest.

0 голосов
/ 23 октября 2018

Используйте это как ссылку:

import sys


def dummy():
    print(sys.argv[0])
    print(str(sys.argv))


dummy()
...