Prevent duplicate items #569
Answered
by
guacs
Chris-May-WS
asked this question in
Q&A
-
Our system has a flaky test because occasionally polyfactory creates two identical class Contact(BaseModel, frozen=True, extra=Extra.forbid):
email: NonEmptyStr
first_name: NonEmptyStr
last_name: NonEmptyStr
phones: List[Phone] = Field(min_items=1)
@validator('phones')
@classmethod
def no_duplicate_phones(cls, value):
counter = Counter(p.type for p in value)
for _, count in counter.items():
if count > 1:
raise ValueError('phone of same type cannot be entered twice')
return value What would you suggest I do to prevent this from happening? |
Beta Was this translation helpful? Give feedback.
Answered by
guacs
Jul 29, 2024
Replies: 1 comment 4 replies
-
You'll probably want to override the generation of a field in Phone using a classmethod to make sure it satisfies your constraint. Could you show the |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looking at your validator, it seems you need to ensure that the
type
is unique for eachPhone
instance right? If so, then I would consider doing something like the following:Now unless you're creating a really large list of phones for a single contact, then this should ensure that you get a list of unique
Phone
instances for a singleContact
.Also, if you use the
Faker
inst…