I have a file that is saved in a specific format, and a class that will create an object based on the data in the file.
I want all the values ββin the file / line to be correctly extracted by testing each attribute in the object.
Here is a simplified version of what I'm doing:
classlist.py
import re class ClassList: def __init__(self, data): values = re.findall('name=(.*?)\$age=(.*?)\$', data) self.students = [Student(name, int(age)) for name, age in values] class Student: def __init__(self, name, age): self.name = name self.age = age
test_classlist.py
import pytest from classlist import ClassList def single_data(): text = 'name=alex$age=20$' return ClassList(text) def double_data(): text = 'name=taylor$age=23$' \ 'name=morgan$age=25$' return ClassList(text) @pytest.mark.parametrize('classinfo, expected', [ (single_data(), ['alex']), (double_data(), ['taylor', 'morgan']) ]) def test_name(classinfo, expected): result = [student.name for student in classinfo.students] assert result == expected @pytest.mark.parametrize('classinfo, expected', [ (single_data(), [20]), (double_data(), [23, 25]) ]) def test_age(classinfo, expected): result = [student.age for student in classinfo.students] assert result == expected
I want to create objects based on different data and use them as a parameterized value.
My current setup works, although there is an unnecessary ability to create an object for each test. I would like them to be created once.
If I try to do the following:
... @pytest.fixture(scope='module') # fixture added def double_data(): text = 'name=taylor$age=23$' \ 'name=morgan$age=25$' return ClassList(text) @pytest.mark.parametrize('classinfo, expected', [ (single_data, ['alex']), (double_data, ['taylor', 'morgan']) # () removed ]) def test_name(classinfo, expected): result = [student.name for student in classinfo.students] assert result == expected ...
AttributeError: 'function' object has no attribute 'students'
... it does not work, because it refers to a function, not a device.
In addition, the code in test_name and test_age almost identical. In my actual code, I do this for about 12 attributes. Should / be combined into one function? How?
How can I clear my test code?
Thanks!
Edit:
I believe that this is relevant, but I'm not sure how it works for my situation: Can the passed parameters be passed to pytest fixture as a variable?