pytest 4 @pytest.fixture运用2
test_people.py
from test_case.people import Person, anyone_like_dogs import pytest @pytest.fixture() def person(): return Person(name = "Bob", favorite_animal = "dog") def test_anyone_like_dogs_true(person): people = [person, person] assert anyone_like_dogs(people)
people.py
class Person(object): def __init__(self, name, favorite_animal=None): self.name = name self.favorite_animal = favorite_animal def anyone_like_dogs(people): """Check if 1 person likes dogs""" return any( [p.favorite_animal == "dog" for p in people] )
改进版test_people.py
from test_case.people import Person, anyone_like_dogs import pytest @pytest.fixture() def person(**kwargs): count = 0 def _person(**kwargs): nonlocal count count+=1 name = kwargs.pop("name","Bob{}".format(count)) return Person(name=name, **kwargs) return _person def test_anyone_like_dogs_true(person): people = [ person(favorite_animal = 'cat'), person(favorite_animal = 'dog'), ] assert anyone_like_dogs(people) def test_person(person): assert person().name != person().name assert person(name = "Alice").name =="Alice"