-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathfactories.py
372 lines (293 loc) · 10.6 KB
/
factories.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import logging
import string
from django.db.utils import IntegrityError
from factory import (
Faker,
Iterator,
LazyAttribute,
RelatedFactory,
SelfAttribute,
SubFactory,
post_generation,
)
from factory.django import DjangoModelFactory, FileField
from factory.fuzzy import FuzzyChoice, FuzzyText
from juriscraper.lib.string_utils import CaseNameTweaker
from cl.lib.factories import RelatedFactoryVariableList
from cl.people_db.factories import PersonFactory
from cl.search.models import (
PRECEDENTIAL_STATUS,
SOURCES,
BankruptcyInformation,
Citation,
Court,
Docket,
DocketEntry,
Opinion,
OpinionCluster,
OpinionsCited,
OpinionsCitedByRECAPDocument,
Parenthetical,
ParentheticalGroup,
RECAPDocument,
)
from cl.tests.providers import LegalProvider
logger = logging.getLogger(__name__)
Faker.add_provider(LegalProvider)
cnt = CaseNameTweaker()
class CourtFactory(DjangoModelFactory):
class Meta:
model = Court
django_get_or_create = ("id",)
id = FuzzyText(length=4, chars=string.ascii_lowercase, suffix="d")
position = Faker("pyfloat", positive=True, right_digits=4, left_digits=3)
short_name = Faker("court_name")
full_name = Faker("court_name")
url = Faker("url")
jurisdiction = FuzzyChoice(Court.JURISDICTIONS, getter=lambda c: c[0])
in_use = True
@classmethod
def _create(cls, model_class, *args, **kwargs):
count = 1
while True:
try:
obj = model_class(*args, **kwargs)
obj.save()
return obj
except IntegrityError as exp:
logger.info(f"Unexpected {exp=}, {type(exp)=}")
kwargs["position"] = Faker(
"pyfloat", positive=True, right_digits=4, left_digits=3
).evaluate(None, None, {"locale": None})
count = count + 1
if count > 3:
raise (exp)
class ParentheticalFactory(DjangoModelFactory):
class Meta:
model = Parenthetical
describing_opinion = SelfAttribute("described_opinion")
text = Faker("sentence")
score = Faker("pyfloat", min_value=0, max_value=1, right_digits=4)
class ParentheticalGroupFactory(DjangoModelFactory):
class Meta:
model = ParentheticalGroup
score = Faker("pyfloat", min_value=0, max_value=1, right_digits=4)
size = Faker("random_int", min=1, max=100)
class ParentheticalWithParentsFactory(ParentheticalFactory):
describing_opinion = SubFactory(
"cl.search.factories.OpinionWithParentsFactory",
)
described_opinion = SelfAttribute("describing_opinion")
class OpinionFactory(DjangoModelFactory):
class Meta:
model = Opinion
author = SubFactory(PersonFactory)
author_str = LazyAttribute(
lambda self: self.author.name_full if self.author else ""
)
type = FuzzyChoice(Opinion.OPINION_TYPES, getter=lambda c: c[0])
sha1 = Faker("sha1")
plain_text = Faker("text", max_nb_chars=2000)
class OpinionWithChildrenFactory(OpinionFactory):
parentheticals = RelatedFactory(
ParentheticalFactory,
factory_related_name="described_opinion",
)
class CitationWithParentsFactory(DjangoModelFactory):
class Meta:
model = Citation
volume = Faker("random_int", min=1, max=100)
reporter = "U.S."
page = Faker("random_int", min=1, max=100)
type = 1
cluster = SubFactory(
"cl.search.factories.OpinionClusterFactoryWithChildrenAndParents",
)
class OpinionWithParentsFactory(OpinionFactory):
cluster = SubFactory(
"cl.search.factories.OpinionClusterWithParentsFactory",
)
class OpinionClusterFactory(DjangoModelFactory):
class Meta:
model = OpinionCluster
case_name_short = LazyAttribute(
lambda self: cnt.make_case_name_short(self.case_name)
)
case_name = Faker("case_name")
case_name_full = Faker("case_name", full=True)
date_filed = Faker("date")
slug = Faker("slug")
source = FuzzyChoice(SOURCES.NAMES, getter=lambda c: c[0])
precedential_status = FuzzyChoice(
PRECEDENTIAL_STATUS.NAMES, getter=lambda c: c[0]
)
class OpinionClusterFactoryWithChildren(OpinionClusterFactory):
sub_opinions = RelatedFactory(
OpinionWithChildrenFactory,
factory_related_name="cluster",
)
class DocketParentMixin(DjangoModelFactory):
docket = SubFactory(
"cl.search.factories.DocketFactory",
# Set the case names on the docket to the ones on this object
# if it has them. Else generate the case name values.
case_name=LazyAttribute(
lambda self: getattr(
self.factory_parent,
"case_name",
Faker("case_name").evaluate(None, None, {"locale": None}),
)
),
case_name_short=LazyAttribute(
lambda self: getattr(
self.factory_parent,
"case_name_short",
cnt.make_case_name_short(self.case_name),
)
),
case_name_full=LazyAttribute(
lambda self: getattr(
self.factory_parent,
"case_name_full",
Faker("case_name", full=True).evaluate(
None, None, {"locale": None}
),
)
),
)
class OpinionClusterFactoryWithChildrenAndParents(
OpinionClusterFactory, DocketParentMixin
):
sub_opinions = RelatedFactory(
OpinionWithChildrenFactory,
factory_related_name="cluster",
)
precedential_status = PRECEDENTIAL_STATUS.PUBLISHED # Always precedential
class OpinionClusterWithParentsFactory(
OpinionClusterFactory,
DocketParentMixin,
):
"""Make an OpinionCluster with Docket parents"""
pass
class DocketEntryFactory(DjangoModelFactory):
class Meta:
model = DocketEntry
description = Faker("text", max_nb_chars=750)
docket = SubFactory("cl.search.factories.DocketFactory")
class RECAPDocumentFactory(DjangoModelFactory):
class Meta:
model = RECAPDocument
description = Faker("text", max_nb_chars=750)
docket_entry = SubFactory(DocketEntryFactory)
document_type = RECAPDocument.PACER_DOCUMENT
pacer_doc_id = Faker("pyint", min_value=100_000, max_value=400_000)
class DocketReuseParentMixin(DjangoModelFactory):
docket = Iterator(Docket.objects.all())
class DocketEntryForDocketFactory(DjangoModelFactory):
class Meta:
model = DocketEntry
@classmethod
def _create(cls, model_class, *args, **kwargs):
"""Override default docket"""
docket_id = kwargs.pop("parent_id", None)
if not docket_id:
return None
kwargs["docket_id"] = docket_id
manager = cls._get_manager(model_class)
return manager.create(*args, **kwargs)
description = Faker("text", max_nb_chars=750)
class DocketEntryWithParentsFactory(
DocketEntryFactory,
DocketParentMixin,
):
"""Make a DocketEntry with Docket parents"""
pass
class DocketEntryReuseParentsFactory(
DocketEntryFactory,
DocketReuseParentMixin,
):
"""Make a DocketEntry using existing Dockets as parents"""
pass
class DocketFactory(DjangoModelFactory):
class Meta:
model = Docket
skip_postgeneration_save = True
source = FuzzyChoice(Docket.SOURCE_CHOICES, getter=lambda c: c[0])
court = SubFactory(CourtFactory)
appeal_from = SubFactory(CourtFactory)
case_name_short = LazyAttribute(
lambda self: cnt.make_case_name_short(self.case_name)
)
case_name = Faker("case_name")
case_name_full = Faker("case_name", full=True)
pacer_case_id = Faker("pyint", min_value=100_000, max_value=400_000)
docket_number = Faker("federal_district_docket_number")
slug = Faker("slug")
date_argued = Faker("date_object")
view_count = 0
"""
This hook is necessary to make this factory compatible with the
`make_dev_command` by delegating the file creation to the hook, we prevent
the model from trying to use our storage settings when the field is not
explicitly requested
"""
@post_generation
def filepath_local(self, create, extracted, **kwargs):
"""Attaches a stub file to an instance of this factory."""
if extracted:
self.filepath_local = extracted
elif kwargs:
# Factory Boy uses the `evaluate` method of each field to calculate
# values for object creation. The FileField class only requires the
# extra dictionary to create the stub django file.
#
# Learn more about FactoryBoy's `FileField` class:
# https://github.com/FactoryBoy/factory_boy/blob/ac49fb40ec424276c3cd3ca0925ba99a626f05f7/factory/django.py#L249
self.filepath_local = FileField().evaluate(None, None, kwargs)
if create:
# Use a Docket queryset to persist filepath_local instead of calling
# save(), which can trigger duplicate post_save signals, potentially
# causing issues in certain testing scenarios.
Docket.objects.filter(pk=self.pk).update(
filepath_local=self.filepath_local
)
class DocketWithChildrenFactory(DocketFactory):
clusters = RelatedFactory(
OpinionClusterFactoryWithChildren,
factory_related_name="docket",
)
class OpinionClusterFactoryMultipleOpinions(
OpinionClusterFactory, DocketParentMixin
):
"""Make an OpinionCluster with Docket parent and multiple opinions"""
sub_opinions = RelatedFactoryVariableList(
factory=OpinionWithChildrenFactory,
factory_related_name="cluster",
size=3, # by default create 3 opinions
)
precedential_status = ("Published", "Precedential")
class OpinionsCitedWithParentsFactory(DjangoModelFactory):
"""Make a OpinionCited with Opinion parents"""
class Meta:
model = OpinionsCited
citing_opinion = SubFactory(
"cl.search.factories.OpinionFactory",
)
cited_opinion = SubFactory(
"cl.search.factories.OpinionFactory",
)
class BankruptcyInformationFactory(DjangoModelFactory):
class Meta:
model = BankruptcyInformation
chapter = Faker("random_id_string")
trustee_str = Faker("name_female")
class OpinionsCitedByRECAPDocumentFactory(DjangoModelFactory):
"""Make a OpinionsCitedByRECAPDocument with parents"""
class Meta:
model = OpinionsCitedByRECAPDocument
citing_document = SubFactory(
"cl.search.factories.RECAPDocumentFactory",
)
cited_opinion = SubFactory(
"cl.search.factories.OpinionFactory",
)