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/03 Report--
This article mainly explains "how to understand fixtureAPI in Python automated testing pytest". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand fixtureAPI in Python automated testing pytest".
What is fixture?
According to the official documentation of pytest, fixture can be simply summarized as a function with the following functions:
Configure the initial state of the system before testing
Define the dataset in the incoming test
Provide data sources for batch testing, etc.
Comparison with setup and teardown in xUnit style
The functions of fixture are similar to setup and teardown, and can implement the functions of setup and teardown, but these functions have been significantly improved, mainly in the following aspects:
Flexible invocation. You can declare the name of fixture in a test function, module, class, or entire project to make a call.
Flexible to use. Fixture is suitable for both simple unit testing and complex functional testing. Fixture can be parameterized according to the requirements of the test, and fixture can be reused.
Fixture is implemented in a modular manner, thus allowing fixture to call other fixture functions
The implementation logic of teardown is clearer and easier to manage.
The processing method of pytest after the error report of fixture
From the above description, we can see that the fixture function itself allows you to call other fixture functions. In this case, what will pytest do when one of the fixture functions reports an error while the test is running?
Through the description of the official pytest documentation, we can know:
Pytest executes the fixture functions called by the test case sequentially in a linear manner
When the earlier fixture function executes an error, pytest stops executing the other fixture called by the test and marks the test with an error
The test mark error does not mean that the test failed, it only means that the test cannot be tried to execute, so we need to reduce the necessary dependencies for the test function as much as possible.
Example 1:
1. In the following demo code, there is a problem with the return type of order (). A list should be returned correctly, and we will return a None to it:
Import pytest@pytest.fixturedef order (): return None # should return [] if correct. We return a None@pytest.fixturedef append_first (order): order.append (1) @ pytest.fixturedef append_second (order, append_first): order.extend ([2]) @ pytest.fixture (autouse=True) def append_third (order, append_second): order + = [3] def test_order (order): assert order = [1,2jue 3]
The results are as follows:
Test_order is marked Error, and the message prompts: test setup failed, which indicates that there is a problem with the called fixture function and explains the cause of the error.
two。 If the test_order fails to run, how will the running information be reminded? We modify the test code and the assertion statement of test_order according to the following demo:
Import pytest@pytest.fixturedef order (): return [] # returns a list@pytest.fixturedef append_first (order): order.append (1) @ pytest.fixturedef append_second (order, append_first): order.extend ([2]) @ pytest.fixture (autouse=True) def append_third (order, append_second): order + = [3] def test_order (order): assert order== [1J 2] # assertion failed and correct should be order== [1J 2J 3]
The running results are as follows:
Test_order is marked failed, and the reminder is AssertionError, assertion error. This indicates that the test_order itself failed to run.
2.fixture API @ pytest.fixture () description
Pytest uses @ pytest.fixture () to declare the fixture method. I will explain in detail how to use it later in the article. Here, let's briefly explain fixture ().
Def fixture (fixture_function: Optional [_ FixtureFunction] = None, *, scope: "Union [_ Scope, Callable [[str, Config], _ Scope]]" = "function", params: optionally [Iterable] = None, autouse: bool = False, ids: Optional [Union [Iterable [Union [None, str, float, int, bool]], Callable [[Any], Optional [object]] ] = None, name: Optional [str] = None,)-> Union [FixtureFunctionMarker, _ FixtureFunction]:
Parameter description:
2.1 scope
The scope of the fixture function. The scope from small to large is: function (default), class, module, package, session.
You can also pass in a callable object to dynamically modify the scope of the fixture.
Later, I will write a separate article to introduce fixture's scope in detail.
2.2 params
Pass in the test data set, generate test cases dynamically, and each piece of data generates a separate test case. Through request.param, you can get the incoming data.
Later, I will write a separate article to introduce the parameterization of fixture in detail.
2.3 autouse
Fixture automatically applies the identity.
If it is True, the test function in the same scope will automatically call the fixture;. If it is False, the test function needs to take the initiative to call the fixture.
I will explain it in detail later in the article that introduces the method of calling fixture.
2.4 ids
The ID identification of the test case corresponds to the parameters passed in by parmas. Id is automatically generated when it is not defined.
Example 2:
1. Pass in the ids parameter and run the following demo:
Import pytest@pytest.fixture (params= [1 data 2), ids= ['Achievement Magnum Bai Ji Meng C']) def ids (request): data=request.param print (f' get test data {data}') return datadef test_ids (ids): print (ids)
Running result:
In the execution information, we can find that the three parameters of ids and the three parameters of params correspond to each other, and the parameters of ids are presented as part of the test case id.
two。 Modify the code in the above demo without passing in the ids parameter, and run:
Import pytest@pytest.fixture (params= [1 request 2]) # not introduced idsdef ids (request): data=request.param print (f 'get test data {data}') return datadef test_ids (ids): print (ids)
Running result:
Looking at the running results, we can see that although there is no ids passed in, the ids is generated automatically.
After the test, we often report the test results in the form of a test report, such as presenting the test results with allure. The parameters passed in through ids can describe the test case, which makes it easier for us to view the test results.
2.5 name
An alias for fixture. Fixture's name defaults to the name of the function decorated by @ pytest.fixture. Using the alias of fixture can improve the readability of the code.
Example 3:
Take the following demo as an example:
Import pytest@pytest.fixture () def login (): print ('login') class SubClass: def sub_login (self): print (' subcalss_login') class TestCase: def test_case1 (self,login): # call fixture--login login=SubClass () # define a login and instantiate SubClass login.sub_login () # call sub_login () print in SubClass ('this is testcase1')
We define a fixture function, login (), instantiate a Subclass class in test_case1, name it login, and then call sub_login () in the SubClass class. If the code is complex, it is easy to confuse the login of the fixture function with the login of the SubClass instance, increasing the complexity of reading the code.
When we use the fixture alias, it's easy to tell the difference when reading the code.
@ pytest.fixture (name='module_login') def login (): print ('login') class TestCase: def test_case1 (self,module_login): # define a login using the fixture alias: module_login login=SubClass () # and instantiate SubClass login.sub_login () # call sub_login () print in SubClass (' this is testcase1')
Note:
When the name parameter is used, it can no longer be called through the function name decorated by @ pytest.fixture, but must be called using the fixture alias specified by name.
Thank you for your reading, the above is the content of "how to understand fixtureAPI in Python automated testing pytest". After the study of this article, I believe you have a deeper understanding of how to understand fixtureAPI in Python automated testing pytest, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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: 234
*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.