Go on to explore the fixtures flexibility in rhythm.
A test function /fixture requests multiple fixtures at a time
In both the test and fixture functions, you are not limited to requesting one fixture at a time. They can have as many as they want. Here’s another simple example:
import pytest # Arrange @pytest.fixture def first_entry(): return "a" # Arrange @pytest.fixture def second_entry(): return 2 # Arrange @pytest.fixture def order(first_entry, second_entry): Return [first_entry, second_entry] # Arrange @pytest.fixture def expected_list(): Return [" A ", 2, 3.0] def test string(order, Expected_list): This is a test function that requests two different fixture functions # Act Order.append (3.0) # Assert Assert order == Expected_listCopy the code
As you can see, in the fixture function ORDER, two other fixture functions are requested: first_entry and second_entry. In the test function test_string, two different fixture functions are requested: order and expected_list.
Fixtures are required multiple times for each test function.
Fixtures can also be requested more than once in the same test function. However, in this test function, PyTest does not execute the fixture functions after they have been executed for the first time. If the fixture function returns a value the first time you execute it, the return value is cached.
import pytest # Arrange @pytest.fixture def first_entry(): return "a" # Arrange @pytest.fixture def order(): return [] # Act @pytest.fixture def append_first(order, first_entry): The first time order is requested, it returns a list [] # Then the empty list of order increases the return value of first_entry, and the order becomes [" A "]. Return order.append(first_entry) def test_string_only(append_first, order, first_entry): Order == [first_entry] order == ["a"] order == ["a"] Test by # Assert Assert order == [first_entry]Copy the code
As you can see from the example:
- The fixture function
append_first
,order
The first time it is requested, returns a list[]
Is cached. - And then,
order.append(first_entry)
in[]
The return value of first_entry was added to the “first_entry” command, so the order is changed["a"]
. - Finally, in the test function
test_string_only
,order
The second time it is requested, it does not get an empty list[]
And got the cached one["a"]
.
In this case, the final assertionassert order == [first_entry]
You will succeed.
On the other hand, if the same fixture requests a test function once every time, that test function will fail. Append_first returns [“a”], but test_string_only returns an empty list [], so the assertion fails.