In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I would like to share with you the relevant knowledge points of Python's pytest parameterized instance analysis, which is detailed in content and clear in logic. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article.
Source code analysis def parametrize (self,argnames, argvalues, indirect=False, ids=None, scope=None): "Add new invocations to the underlying test function using the list of argvalues for the given argnames. Parametrization is performed during the collection phase. If you need to setup expensive resources see about setting indirect to do it rather at test setup time. # adds a new call to the underlying test function using the argValue list of a given argnames, performing parameterization during the collection phase. : arg argnames: a comma-separated string denoting one or more argument names, or a list/tuple of argument strings. # Parameter name: a comma-separated string, list, or meta-ancestor, indicating one or more parameter names: arg argvalues: The list of argvalues determines how often a test is invoked with different argument values. If only one argname was specified argvalues is a list of values. If N argnames were specified, argvalues must be a list of N-tuples, where each tuple-element specifies a value for its respective argname. # Parameter values: only one argnames,argvalues is a value list. When there are N argnames, each meta-ancestor corresponds to a set of argnames, and all meta-ancestors are combined into a list: arg indirect: The list of argnames or boolean. A list of arguments' names (self,subset of argnames). If True the list contains all names from the argnames. Each argvalue corresponding to an argname in this list will be passed as request.param to its respective argname fixture function so that it can perform more expensive setups during the setup phase of a test rather than at collection time. : arg ids: list of string ids, or a callable. If strings, each is corresponding to the argvalues so that they are part of the test id. If None is given as id of specific test, the automatically generated id for that argument will be used. If callable, it should take one argument (self,a single argvalue) and return a string or return None. If None, the automatically generated id for that argument will be used. If no ids are provided they will be generated automatically from the argvalues. # ids: a list of strings, which can be understood as a title, consistent with the number of use cases: arg scope: if specified it denotes the scope of the parameters. The scope is used for grouping tests by parameter instances. It will also override any fixture-function defined scope, allowing to set a dynamic scope using test context or configuration. # if specified, represents the range of parameters. Scope is used to group tests by parameter instance. It will also cover the scope defined by any fixture function, allowing dynamic ranges to be set using test context or configuration. "
Argnames
Interpretation: parameter name
Format: string "arg1,arg2,arg3"
Aegvalues
Interpretation: list of parameter valu
Format: must be a list, such as [val1,val2,val3]
A single parameter with a list of values, such as @ pytest.mark.parametrize ("name", ["Jack", "Locus", "Bill"])
Multiple parameters need to be stored with meta-ancestors. A meta-ancestor corresponds to the values of a set of parameters, such as @ pytest.mark.parametrize ("user,age", [("user1", 15), ("user2", 24), ("user3", 25)]).
Ids
Interpretation: id that can be understood as a use case
Format: list of strings, such as ["case1", "case2", "case3"]
Indirect
Interpretation: when indirect=True, if the argnames passed in is the fixture function name, the fixture function name will become an executable function
Argvalues, as an argument to fixture, executes the fixture function, and the final result is stored in request.param;. When indirect=False, fixture
The function is called only as a parameter name to the test collection phase.
Note: the setup phase (test setup phase) can be understood as configuring conftest.py phase, and the collection phase (
The test collection phase is understood as the use case execution phase.
Adornment test class import pytestdata = [(2meme 2jue 4), (3pje 4je 12)] def add (arecy b): return a * b@pytest.mark.parametrize ('a * b@pytest.mark.parametrize) class TestParametrize (object): def test_parametrize_1 (self,a,b,expect): print ('\ nTest function 1 test data is\ n {}-{} '.format (acog b)) assert add (a) B) = = expect def test_parametrize_2 (self,a,b,expect): print ('\ nTest function 2 test data is\ n {}-{} '.format (aforme b)) assert add (aforme b) = = expectif _ _ name__ = = "_ _ main__": pytest.main (["- s", "test_07.py"]) = = test session starts = = platform win32-- Python 3.8.0, pytest-6.2.5 Py-1.11.0, pluggy-1.0.0rootdir: d:\ AutoCodeplugins: html-3.1.1, metadata-1.11.0collecting. Collected 4 itemstest_07.py::TestParametrize::test_parametrize_1 [2-2-4] Test function 1 Test data is 2-2PASSEDtest_07.py::TestParametrize::test_parametrize_1 [3-4-12] Test function 1 Test data is 3-4PASSEDtest_07.py::TestParametrize::test_parametrize_2 [2-2-4] Test function 2 Test data is 2-2PASSEDtest_07.py::TestParametrize::test_parametrize _ 2 [3-4-12] Test function 2 Test data is 3-4 PASSED data = 4 passed in 0.12s = = Process finished with exit code 0
As you can see from the above code, when the decorator decorates the test class, the defined data set is passed to all methods of the class.
Decorate the test function single data import pytestdata = ["Rose", "white"] @ pytest.mark.parametrize ("name", data) def test_parametrize (name): print (\ n {} '.format (name)) if _ _ name__ = = "_ _ main__": pytest.main (["- s", "test_07.py"]) = = test session starts = = platform win32-- Python 3.8.0, pytest-6.2.5 Py-1.11.0, pluggy-1.0.0rootdir: d:\ AutoCodeplugins: html-3.1.1, the name in the metadata-1.11.0collected 2 itemstest_07.py list is Rose. The name in the list is white.== 2 passed in 0.09s = = Process finished with exit code 0
When the test case requires only one parameter, the list in which we store the data is an unordered nested sequence, @ pytest.mark.parametrize ("name", data)
The first parameter of the decorator also requires only one variable to receive each element in the list, and the second parameter passes the list of stored data, so the test uses
The example needs to use a string of the same name to receive test data (name in the instance) and how many test cases are generated and executed as many elements in the list.
A set of data import pytestdata = [[1,2,3], [4,5,9]] # list nested list # data_tuple = [# (1,2,3), # (4,5,9) #] # list nested tuple @ pytest.mark.parametrize ('a, b, expect', data) def test_parametrize_1 (a, b Expect): # A parameter receives a data print ('\ nTest data is\ n {}) {} {} '.format (a, b, expect) actual = a + b assert actual = = expect@pytest.mark.parametrize (' value') Data) def test_parametrize_2 (value): # A parameter receives a set of data print ('\ nTest data is\ n {} '.format (value)) actual = value [0] + value [1] assert actual = = value [2] if _ name__ = = "_ main__": pytest.main (["- s", "test_07.py"]) = = test session starts = = platform win32-- Python 3.8.0, pytest-6.2.5 Py-1.11.0, pluggy-1.0.0rootdir: d:\ AutoCodeplugins: html-3.1.1, metadata-1.11.0collected 4 itemstest_07.py test data is 1 2,3. The test data are 4, 5, 5, 9. The test data are [1,2,3]. The test data is [4,5,9]. = 4 passed in 0.09s = = Process finished with exit code 0
When a test case requires multiple data, we can use a list of nested sequences (nested tuples & nested lists) to store the test data.
The decorator @ pytest.mark.parametrize () can receive data using either a single variable or multiple variables. Similarly, test
The trial example function also needs to be consistent with it.
When receiving using a single variable, the test data is passed to the inside of the test function for each element or small list in the list.
You want to get each data using an index.
When multiple variables are used to receive data, each variable receives more than one nested list of elements in a small list or tuple
Group small list or tuple to measure how many test cases are generated.
Combinatorial data import pytestdata_1 = [1Personality 2Power3] data_2 = ['axiajukai] @ pytest.mark.parametrize (' axiaojia) @ pytest.mark.parametrize ('brecaked2) def test_parametrize_1 (' def test_parametrize_1 b): print (f 'Cartesian product test result: {a}, {b}') if _ _ name__ = ='_ main__': pytest.main (["- vs", "test_06.py"])
Through the test results, it is not difficult to analyze that a test function can be decorated by multiple parameterized decorators at the same time, so many
The data in the decorator is passed to the test function by cross-combination, and then n * n test cases are generated.
Markup use cases import pytest@pytest.mark.parametrize ("test_input,expected", [("3 * 5", 8), ("2 # 4", 6), pytest.param ("6 * 9", 42 # markspurpytest.mark.xfail), pytest.param ("6 * 6", 42 Markespowered pytest.mark.skip)]) def test_mark (test_input Expected): assert eval (test_input) = = expectedif _ _ name__ = ='_ _ main__': pytest.main (["- vs", "test_06.py"])
The output shows that four use cases are collected, two pass, one is skipped, and one tag fails when we don't want to run a set of tests.
When data, we can mark skip or skipif;. When we expect a set of data to fail, we can mark it as xfail and so on.
Nested dictionary import pytestdata = ({'user': "name1",' pwd': 123}, {'user': "name2",' pwd': 456}) @ pytest.mark.parametrize ('dic' Data) def test_parametrize (dic): print ('\ nTest data is\ n {} '.format (dic)) if _ _ name__ =' _ _ main__': pytest.main (["- vs", "test_06.py"])
Increase the readability of test results
The parametric decorator has an additional parameter, ids, that identifies each test case and customizes the display of test data results.
To increase readability, we can mark what test data is used by each test case and add some instructions as appropriate.
Before you use it, you need to know that the ids parameter should be a list of strings, which must be consistent with the length of the list of data objects.
Import pytestdata_1 = [(1,2,3), (4,5,9)] ids= ["a: {} + b: {} = expect: {}" .format (a, b, expect) for a, b, expect in data_1] def add (a, b): return a + b@pytest.mark.parametrize ('a, b, expect', data_1, ids=ids) class TestParametrize (object): def test_parametrize_1 (self, a, b) Expect): print ('\ nTest function 1 test data is\ n {}-{} '.format (a, b)) assert add (a, b) = = expect def test_parametrize_2 (self, a, b, expect): print ('\ nTest function 2 data is\ n {}-{} '.format (a, b)) assert add (a) B) = = expectif _ name__ = ='_ main__': pytest.main (["- v", "test_06.py"])
The returned result without ids parameter
Add the returned result of the ids parameter
We can see that the use cases in the return result with the ids parameter are explicitly marked by a list, and through this tag
It is more intuitive to see the data name and test content used by each test case.
These are all the contents of the article "pytest Parametric example Analysis of Python". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.