Skip to content

Commit ddb763a

Browse files
martin056RadoRado
authored andcommitted
Make factories more explicit
1 parent c3daf91 commit ddb763a

File tree

1 file changed

+15
-23
lines changed

1 file changed

+15
-23
lines changed

styleguide_example/test_examples/tests/factories.py

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,10 @@ class SchoolWithStudentsFactory(SchoolFactory):
3434
@factory.post_generation
3535
def students(obj, create, extracted, **kwargs):
3636
if create:
37-
students = extracted or StudentFactory.create_batch(kwargs.get('count', 5))
37+
students = extracted or StudentFactory.create_batch(
38+
kwargs.pop('count', 5),
39+
**kwargs
40+
)
3841
obj.students.set(students)
3942
return students
4043

@@ -58,31 +61,19 @@ class Meta:
5861
model = Roster
5962

6063
student = factory.SubFactory(StudentFactory)
61-
# Make sure the student and the school_course are from the same school
64+
65+
# NOTE: You can use `factory.SelfAttribute` for the below attributes.
66+
# We prefer using `factory.LazyAttribute` as we find the definition more explicit.
6267
school_course = factory.SubFactory(
6368
SchoolCourseFactory,
64-
school=factory.SelfAttribute('..student.school')
65-
)
66-
# The `SelfAttribute` is just an interface that uses LazyAttribute under the hood:
67-
# school_course = factory.SubFactory(
68-
# SchoolCourseFactory,
69-
# school=factory.LazyAttribute(lambda course: course.factory_parent.student.school)
70-
# )
71-
72-
start_date = factory.SelfAttribute('school_course.start_date')
73-
end_date = factory.SelfAttribute('school_course.end_date')
74-
75-
active = True
76-
# We'd recommend you using LazyAttribute instead of Maybe as it's more explicit
77-
deactivated_at = factory.Maybe(
78-
'active',
79-
no_declaration=factory.LazyAttribute(lambda self: faker.date_between_dates(
80-
date_start=self.start_date,
81-
date_end=self.end_date
82-
)),
83-
yes_declaration=None
69+
school=factory.LazyAttribute(
70+
lambda course: course.factory_parent.student.school
71+
)
8472
)
8573

74+
start_date = factory.LazyAttribute(lambda _self: _self.school_course.start_date)
75+
end_date = factory.LazyAttribute(lambda _self: _self.school_course.end_date)
76+
8677

8778
def get_future_roster_start_date(roster_obj):
8879
if not roster_obj.start_after:
@@ -109,7 +100,8 @@ class SchoolCourseWithRostersFactory(SchoolCourseFactory):
109100
def rosters(obj, create, extracted, **kwargs):
110101
if create:
111102
rosters = extracted or RosterFactory.create_batch(
112-
kwargs.get('count', 5),
103+
kwargs.pop('count', 5),
104+
**kwargs,
113105
student__school=obj.school # NOTE!
114106
)
115107

0 commit comments

Comments
 (0)