Can we print the command line arguments in setup_module() or setup_class in pytest?

六眼飞鱼酱① 提交于 2020-01-05 07:17:18

问题


I got to know how to pass command line parameters in pytest. I want to print or do some basic validation in my setup_class() or setup_module() against the variables passed as command line arguments.

I am able to access these variables in test methods but not in setup_class or setup_module. Is this even possible?

I want to do something like this...

conftest.py

def pytest_addoption(parser):
    parser.addoption('--user',action='store', help='email id Ex: abc@infoblox.com')

test_1.py

import pytest

def setup_module():
    print 'Setup Module'
def teardown_module():
    print "Teardown Module"

class Test_ABC:

    def setup_class(cls,request):
        user = request.config.option.user
        print user
        print 'Setup Class'

    def teardown_class(cls,request):
        print 'Teardown Class'

    def test_12(self,request):
        print "Test_12"
        assert 1==1

回答1:


In conftest.py:

def pytest_addoption(parser):
    """Add the --user option"""
    parser.addoption(
        '-U', '--user',
        action="store", default=None,
        help="The user")

option = None

def pytest_configure(config):
    """Make cmdline arguments available to dbtest"""
    global option
    option = config.option

Now you can just import option from conftest:

from conftest import option

class Test_ABC:

    def setup_class(cls):
        user = option.user
        print user
        print 'Setup Class'



回答2:


I had a similar use case and I ended up implementing it as follows:

In conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption("--testarg", action="store", dest="testarg", default="test", help="testarg help")

def pytest_configure(config):
    pytest.testarg = config.getoption('testarg')

In test_sample.py

import pytest
print pytest.testarg

Resources:

  1. https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_addoption



回答3:


1.Add conftest.py at first and add 2 method in it.

def pytest_addoption(parser):
    parser.addoption(
        "--devicename", action="store", default="test1", help="test1"
    )

def pytest_configure(config):
    pytest.devicename = config.getoption('devicename')

2.Then call pytest. in your setupclass or setupmethod. like print(pytest.devicename)



来源:https://stackoverflow.com/questions/45120266/can-we-print-the-command-line-arguments-in-setup-module-or-setup-class-in-pyte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!