'pytest assert multiple objects in single line
I am using pytest to assert multiple objects for same condition. Board of writing repetitive code. I wanted to know how these multiple objects can be clubbed together to test at once in a single line.
Below is my current code:
assert response['a'] is not None
assert response['b'] is not None
assert response['c'] is not None
assert response['d'] is not None
Essentially what I am looking for is something like this:assert response['a'], response['b'], response['c'], response['d'] is not None
I did study about parametrixing fixtures but looks like that is not for my current use case.
Solution 1:[1]
assert all(getattr(response, x) for x in ["a", "b", "c", "d"])
Solution 2:[2]
For identical tests, the parametrize decorator of pytest allows you to write a single test changing parameter(s).
The code readability is improved compared to a list comprehension because the test is simpler. More over your Junit or report is split into a single test for each attribute which highlights where the issue is:
Another issue is that testing the key is not None wil raise a KeyError if the key is absent and your test status will be error, not failed. Use the get method on the object to get None if the is absent.
Therefore I would write the test this way (assuming response can be a fixture):
import pytest
@pytest.fixture()
def response():
return {"a": 1, "b": None}
@pytest.mark.parametrize("attribute", ('a', 'b', 'c', 'd'))
def test_attributes(attribute, response):
assert response.get(attribute) is not None
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shod |
| Solution 2 | Christophe Brun |

