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

How to exclude property? for hypothesis.errors.ResolutionFailed: Could not infer a strategy for <django.db.models.fields.AutoField: id> #3883

Closed
PorcoRosso85 opened this issue Feb 14, 2024 · 1 comment

Comments

@PorcoRosso85
Copy link

PorcoRosso85 commented Feb 14, 2024

error

_________________________________ TestSpaceSerializerHypothesis.test_space_no_content _________________________________

self = <app.serializer.TestSpaceSerializerHypothesis testMethod=test_space_no_content>

    @pytest.mark.django_db
>   @given(
        from_model(
            Space,
            exclude_fields=["id"],
            content=st.lists(from_model(Content, exclude_fields=["id"])),
        )
    )

app/serializer.py:356: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
.venv/lib/python3.12/site-packages/hypothesis/core.py:670: in process_arguments_to_given
    s.validate()
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/strategies.py:417: in validate
    self.do_validate()
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:136: in do_validate
    w = self.wrapped_strategy
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:108: in wrapped_strategy
    k: unwrap_strategies(v) for k, v in self.__kwargs.items()
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:43: in unwrap_strategies
    result = unwrap_strategies(s.wrapped_strategy)
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:106: in wrapped_strategy
    unwrapped_args = tuple(unwrap_strategies(s) for s in self.__args)
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:106: in <genexpr>
    unwrapped_args = tuple(unwrap_strategies(s) for s in self.__args)
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:43: in unwrap_strategies
    result = unwrap_strategies(s.wrapped_strategy)
.venv/lib/python3.12/site-packages/hypothesis/strategies/_internal/lazy.py:111: in wrapped_strategy
    base = self.function(*self.__args, **self.__kwargs)
.venv/lib/python3.12/site-packages/hypothesis/extra/django/_impl.py:109: in from_model
    field_strategies[name] = from_field(field)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

field = <django.db.models.fields.AutoField: id>

    def from_field(field: F) -> st.SearchStrategy[Union[F, None]]:
        """Return a strategy for values that fit the given field.
    
        This function is used by :func:`~hypothesis.extra.django.from_form` and
        :func:`~hypothesis.extra.django.from_model` for any fields that require
        a value, or for which you passed ``...`` (:obj:`python:Ellipsis`) to infer
        a strategy from an annotation.
    
        It's pretty similar to the core :func:`~hypothesis.strategies.from_type`
        function, with a subtle but important difference: ``from_field`` takes a
        Field *instance*, rather than a Field *subtype*, so that it has access to
        instance attributes such as string length and validators.
        """
        check_type((dm.Field, df.Field), field, "field")
        if getattr(field, "choices", False):
            choices: list = []
            for value, name_or_optgroup in field.choices:
                if isinstance(name_or_optgroup, (list, tuple)):
                    choices.extend(key for key, _ in name_or_optgroup)
                else:
                    choices.append(value)
            # form fields automatically include an empty choice, strip it out
            if "" in choices:
                choices.remove("")
            min_size = 1
            if isinstance(field, (dm.CharField, dm.TextField)) and field.blank:
                choices.insert(0, "")
            elif isinstance(field, (df.Field)) and not field.required:
                choices.insert(0, "")
                min_size = 0
            strategy = st.sampled_from(choices)
            if isinstance(field, (df.MultipleChoiceField, df.TypedMultipleChoiceField)):
                strategy = st.lists(st.sampled_from(choices), min_size=min_size)
        else:
            if type(field) not in _global_field_lookup:
                if getattr(field, "null", False):
                    return st.none()
>               raise ResolutionFailed(f"Could not infer a strategy for {field!r}")
E               hypothesis.errors.ResolutionFailed: Could not infer a strategy for <django.db.models.fields.AutoField: id>

.venv/lib/python3.12/site-packages/hypothesis/extra/django/_fields.py:325: ResolutionFailed
=================================================== inline snapshot ===================================================
=============================================== short test summary info ===============================================
FAILED app/serializer.py::TestSpaceSerializerHypothesis::test_space_no_content - hypothesis.errors.ResolutionFailed: Could not infer a strategy for <django.db.models.fields.AutoField: id>

reference code

this code is powered by chatgpt, maybe exclude_fields is not allowed.
but this is a way to explain what I want.

from hypothesis import given
from hypothesis import strategies as st
from hypothesis.extra.django import TestCase as HypothesisTestCase
from hypothesis.extra.django import from_model


class TestSpaceSerializerHypothesis(HypothesisTestCase):
    @pytest.mark.django_db
    def test_no_space(self):
        serializer = SpaceSerializer(data={})
        assert not serializer.is_valid()

    @pytest.mark.django_db
    @given(from_model(Space, exclude_fields=['id'], content=st.lists(from_model(Content, exclude_fields=['id']))))
    def test_space_no_content(self, space):
        print(f"space: {space}")
        data = {"content": []}
        serializer = SpaceSerializer(data=data)
        assert serializer.is_valid()
        assert serializer.errors == {"content": ["This field is required"]}
@Zac-HD
Copy link
Member

Zac-HD commented Feb 14, 2024

@Zac-HD Zac-HD closed this as completed Feb 14, 2024
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

2 participants