[Python] How to tell hypothesis.strategies to choose not-None for optional fields

Discussão em 'Python' iniciado por Stack, Janeiro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am a consumer of a class that I don't own:

    from dataclasses import dataclass
    @dataclass
    class Child:
    f1: int
    f2: int | None
    @dataclass
    class Parent:
    child: Child


    The actual class is much much deeper and wider.

    To run manual tests (not pytest, not CI), I want to create an instance of Parent with random values.

    from typing import TypeVar
    import hypothesis
    import hypothesis.strategies
    T = TypeVar("T")
    def generate(cls: type[T], seed: int) -> T:
    objects = []

    @hypothesis.seed(seed)
    @hypothesis.given(hypothesis.strategies.from_type(cls))
    @hypothesis.settings(max_examples=10)
    def f(o):
    objects.append(o)

    f()

    # Firts example tends to be a trivial one so return the last one instead
    return objects[-1]

    print(generate(Parent))
    print(generate(Parent))


    output:

    Parent(child=Child(f1=1234, f2=None))
    Parent(child=Child(f1=-10, f2=4567))


    I don't care about the values in the instance, except I do not want Nones for optional fields (I want Child.f2 to be a random int, always). I don't want to maintain code to instantiate one because the class often changes.

    How can I update the snippet to tell hypothesis to never choose None?

    Continue reading...

Compartilhe esta Página