1

I have lets say two dataclasses where one is used inside the other like this :

@dataclass(frozen=True)
class SensorModel:
    sensor_id: int
    type: str 
    health_status: bool 

@dataclass
class SamplingModel:
    trigger: str
    priority: str = field(init=False)
    time: datetime
    sensors: List[SensorModel]

how can I use hypothesis to generate sample for my testing from this?

I have found in the docs that hypothesis strategies support dataclasses natively hypothesis but no examples ANYWHERE about how to do it in a simple case like the one described.

KZiovas
  • 3,491
  • 3
  • 26
  • 47

1 Answers1

2

Ok so I found an answer, its turns out it is really simple you can use the from_type generator from_type documentation

In the simple example I described above one could do something like

@dataclass(frozen=True)
class SensorModel:
    sensor_id: int
    type: str 
    health_status: bool 

@dataclass
class SamplingModel:
    trigger: str
    priority: str = field(init=False)
    time: datetime
    sensors: List[SensorModel]

@given(sample=gen.from_type(SamplingModel))
def test_samples(sample):
    assert sample.trigger == sample.trigger #point-less test replace with your logic
KZiovas
  • 3,491
  • 3
  • 26
  • 47
  • 2
    Yep, that's it! I'd also suggest checking out the `builds()` strategy, which allows you to pass an explicit strategy for some arguments, if e.g. `time` must be after the unix epoch. – Zac Hatfield-Dodds Dec 23 '21 at 01:19
  • @ZacHatfield-Dodds ok I see you are a developer of hypothesis and this is a unique chance to ask you. The above works but could we use more specific generator with the data-classes without having to manually replicate the whole nested structure of the data-classes? For example lets say we have 3 nested data-classes AND also we want more specific string generators or list generators, not just the default ones. How could we do it? Or could we add something to the data-classes themselves to tell hypothesis to use more specific generators? – KZiovas Dec 23 '21 at 16:17
  • 2
    You can register a strategy for your custom types, wgich will then be picked up by later uses of builds() and from_type() - see https://hypothesis.readthedocs.io/en/latest/data.html#hypothesis.strategies.register_type_strategy – Zac Hatfield-Dodds Dec 24 '21 at 14:11
  • ok ok,so maybe like I could make a module with all the strategies for our custom types and import them wherever we need them and register them there. That way we could have different strategies for the same dataclasess in different cases as well, if needed. Thanks! – KZiovas Dec 24 '21 at 19:05