Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A way to ensure that all elements in a sequence match constraint #60

Open
qweeze opened this issue Apr 13, 2023 · 2 comments
Open

A way to ensure that all elements in a sequence match constraint #60

qweeze opened this issue Apr 13, 2023 · 2 comments

Comments

@qweeze
Copy link

qweeze commented Apr 13, 2023

I came across a situation when I need to assert that all of dicts in a list have a certain key/value pair, eg

my_obj = {
    "items": [{"x": 42, "type": 1}, {"x": 123, "type": 1}],
}
assert all(item["type"] == 1 for item in my_obj["items"])

Is there currently any way to achieve this? I could only come up with this

assert my_obj == IsPartialDict({"items": ~Contains(~IsPartialDict({"type": 1}))})

but it seems too dirty 🥲

@FBruzzesi
Copy link
Contributor

FBruzzesi commented Apr 28, 2023

I imagine you need the outer IsPartialDict because you have other keys in the dictionary in the first place.

Not sure this is better, it only doesn't contain double negation:

assert my_obj == IsPartialDict({"items": IsListOrTuple(*[IsPartialDict({"type": 1})]*len(my_obj["items"]))})

@alexmojaki
Copy link
Contributor

Suggestions for syntax:

IsListOrTuple.of(constraint)
IsListOrTuple(of=constraint)
IsListOrTuple(constraint, ...)  # literally `...`, similar to type hints like `Tuple[int, ...]`

e.g.

assert my_obj == IsPartialDict({"items": IsListOrTuple.of(IsPartialDict({"type": 1}))})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants