-
Notifications
You must be signed in to change notification settings - Fork 588
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
Document how to make a Strategy for enums #2693
Comments
As the docs note, I actually don't think we should change the semantics of However, I'd be happy to detect this particular problem and raise an error with a helpful message explaining what to do instead. |
Ok! The confusion mainly stems from the fact that I can build dataclasses using |
Ah - the distinction is actually " Knowing that's the distinction you had in mind will help me write the new error message though - thanks! |
Thanks a lot @Zac-HD , I appreciate it a lot! |
But how do we generate enums, though? I've tried @st.composite
def generate_enum(draw):
return draw(
st.builds(
Enum,
st.from_regex(r"(?a)[_a-zA-Z][_a-zA-Z0-9]*"),
st.from_regex(r"(?a)[_a-zA-Z][_a-zA-Z0-9]*( [_a-zA-Z][_a-zA-Z0-9]*)*"),
)
) But got TypeError: Attempted to reuse key: 'A' and ValueError: type name must not contain null characters I also saw #2923 . Maybe I'm just dumb. Because what I'm trying is not working |
This issue is about generating instances of a particular Enum subclass. To generate arbitrary Enum types, you could from enum import Enum
from hypothesis import strategies as st
def enums():
names = st.text().filter(str.isidentifier) # or st.from_regex(), etc.
values = st.lists(names, min_size=1, unique=True).map(" ".join)
return st.builds(Enum, names, values) though a more efficient strategy for Python identifiers can be found here. You could also be more general about the values with |
Funny, because I also tried a little harder with making the enum strategy and I got (where @st.composite
def generate_enum(draw):
return draw(
st.builds(
Enum,
variable_names(),
st.dictionaries(variable_names(), st.text()),
),
) I think you guys should really add two new strategies: Enums and/or identifiers |
What is insufficient about the strategy that you and @Zac-HD both posted? It makes standard use of |
Hmm, true. Though it did take me a while to figure. I guess we shouldn't add too much extra strategies |
I get hypothesis.errors.InvalidArgument: Cannot sample from generate_enum(), not an ordered collection. |
Because |
If one tries
builds(Enum)
, it fails horribly:It would be nice if the right way was documented, or if
builds
detected that it was being called on an enum. It is a standard library class.sampled_from(list(Enum))
does work, but it may not be obvious to everybody.This was tested with version 5.41.5 on Python 3.9.0rc2.
The text was updated successfully, but these errors were encountered: