[pytest] pytest of Hook method_ Addoption: register command line parameters

Pytest of Hook method_ addoption :

pytest_addoption allows users to register a user-defined command line parameter to facilitate users to pass data to pytest;
This Hook method is generally used with the built-in fixture pytestconfig, pytest_addoption registers the command line parameter, and pytestconfig reads the parameter value through the configuration object;

  pytest_addoption register and pytestconfig obtain command line parameters:

# conftest.py
 
import pytest
 
# Register the custom parameter cmdopt to the configuration object
def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store",
                     default="None",
                     help="The command line parameters will be customized '--cmdopt' Add to pytest In configuration")
 
# Gets the value of cmdopt from the configuration object
@pytest.fixture(scope='session')
def cmdopt(pytestconfig):
    return pytestconfig.getoption('--cmdopt')
 
# Then any fixture or test case can call cmdopt to obtain device information

parser.addoption()   Parameter Description:

  1. Name: the name of the user-defined command line parameter, which can be: "foo", "foo" or "-" foo ";
  2. Action: the basic action type to take when this parameter is encountered on the command line;
  3. nargs: the number of command line parameters that should be used;
  4. const: constant value required for some operations and nargs selection;
  5. Default: the default value generated if the parameter is not on the command line.
  6. Type: the type to which the command line parameter should be converted;
  7. choices: container of allowable values of parameters;
  8. required: whether the command line option can be omitted (optional only);
  9. help: brief description of parameter function;
  10. metavar: name of parameter in usage message;
  11. dest: to add to parse_ The name of the property in the object returned by args();

Select several commonly used to demonstrate:
1. name: Needless to say, the name of the user-defined parameter;

2. action, default, const, help:

action="store": by default, only parameter values can be stored, and any type of value can be stored. At this time, default can also be any type of value, and only one command-line parameter can take effect after being used multiple times. The last value overwrites the previous value;

# Register the custom parameter cmdopt to the configuration object
def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store",
                     default="This is the default...",
                     help="Set command line parameters '--cmdopt' Add to pytest In configuration")
 
# Read the value of the custom parameter from the configuration object
@pytest.fixture(scope="session")
def cmdopt(request):
    return request.config.getoption("--cmdopt")
 
# Print the value of the custom parameter
@pytest.fixture(autouse=True)
def fix_1(cmdopt):
    print('\n --cmdopt Value of:',cmdopt)
 
if __name__ == '__main__':
    # Use parameters
    pytest.main(['-s', '--cmdopt=98k'])
# Console print parameter values:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001 
 --cmdopt Value of: 98 k
PASS
============================== 1 passed in 0.02s ==============================

action="append": store a list and use   append   pattern   You can use custom parameters multiple times at the same time, and   default    The default value must be a list, pytest   Will put   default    The values of default parameters and multiple custom parameters are placed in one list:

# Register the custom parameter cmdopt to the configuration object
def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="append",
                     default=['This is the default parameter'],
                     help="Set command line parameters '--cmdopt' Add to pytest In configuration")
 
if __name__ == '__main__':
    # Use parameters
    pytest.main(['-s', '--cmdopt=98k', '--cmdopt=Mauser pistol'])
# Console print parameter values:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001 
 --cmdopt Value of: ['This is the default parameter', '98k', 'Mauser pistol']
PASS
============================== 1 passed in 0.02s ==============================

action="store_const": use   const   Specify a constant value for the command line parameter, which must be and   const   Parameters are used at the same time. After using this mode, the command line parameters cannot be assigned:

def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store_const",
                     default='This is the default parameter',
                     const='This is the constant value specified for the command line parameter...',
                     help="Set command line parameters '--cmdopt' Add to pytest In configuration")
 
if __name__ == '__main__':
    pytest.main(['-s','--cmdopt'])
# Console print parameter values:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001 
 --cmdopt Value of: This is the constant value specified for the command line parameter...
PASS
============================== 1 passed in 0.02s ==============================

action="append_const": store a list and use   const   Specify a constant value for the command line parameter and   default   Default values and   const    Constant values are added to the list. In this mode, user-defined parameters can be used multiple times at the same time, but values cannot be assigned. Only constants can be used;

def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="append_const",
                     default=['This is the default parameter'],
                     const='This is the constant value specified for the command line parameter...',
                     help="Set command line parameters '--cmdopt' Add to pytest In configuration")
 
if __name__ == '__main__':
    pytest.main(['-s','--cmdopt', '--cmdopt'])
# Console print parameter values:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001 
 --cmdopt Value of: ['This is the default parameter', 'This is the constant value specified for the command line parameter...', 'This is the constant value specified for the command line parameter...']
PASS
============================== 1 passed in 0.02s ==============================

three   type: type   The type of can be the basic type of python, such as int, STR, float, list   If the type is not specified, pytest will default the accepted parameter values to   str   Type, so we sometimes need to specify the type of the parameter:

Note: in use   type   When specifying the type, you also need to   default   Change the type of to the same type!

def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store",
                     default=100,
                     type=int,
                     help="Set command line parameters '--cmdopt' Add to pytest In configuration")
 
if __name__ == '__main__':
    pytest.main(['-s', f'--cmdopt=888'])
# Console print parameter values:
============================= test session starts =============================
--cmdopt Value of: 888
--cmdopt Type of: <class 'int'>
PASS
============================== 1 passed in 0.02s ==============================

four   choices: choices   You can specify several values. You must select one of these values for user-defined parameters, or an error will be reported:

def pytest_addoption(parser):
    parser.addoption("--cmdopt", action="store",
                     default='100',
                     choices= ['python', 'java', 'c++'],
                     help="Set command line parameters '--cmdopt' Add to pytest In configuration")
 
if __name__ == '__main__':
    pytest.main(['-s', f'--cmdopt=888'])
# Console print results:
 
ERROR: usage: conftest.py [options] [file_or_dir] [file_or_dir] [...]
conftest.py: error: argument --cmdopt: invalid choice: '888' (choose from 'python', 'java', 'c++')

Keywords: unit testing pytest

Added by cleibesouza on Thu, 23 Sep 2021 11:05:22 +0300