0

I'm trying to use hypothesis to generate a text strategy with a complex format. I'm not sure how to build up this kind of data structure.

I've tried to build the various elements as composites to then use those as strategies for other composites. However the elements argument in the lists strategy requires a SearchStrategy instead of a composite like I had hoped. Looking through the docs I couldn't work out if the builds, mapping or flatmap would help in this case.

My (simplified) attempt is below.

@st.composite
def composite_coords(draw):
    lat = draw(st.decimals(min_value=-10, max_value=-1, allow_nan=False, places=16))
    long = draw(st.decimals(min_value=50, max_value=90, allow_nan=False, places=16))
    return [float(long), float(lat)]


@st.composite
def composite_polygon_coords(draw):
    polygon_coords = draw(st.lists(
        elements=composite_coords, min_size=3
    ))
    return polygon_coords.append(polygon_coords[0])


@st.composite
def composite_polygons(draw):
    polygons = draw(st.lists(
        elements=composite_polygon_coords, min_size=1
    ))
    polygon = {
        'type': 'Polygon',
        'coordinates': polygons
    }
    return poly.dumps(polygon)


@given(composite_polygons())
def test_valid_polygon(polygon):
    result = validate(polygon)
    assert result == polygon
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
Mr-Love
  • 50
  • 1
  • 4

1 Answers1

1

The @st.composite decorator gives you a function which returns a strategy - you just need to call them and you'll be good to go.

Zac Hatfield-Dodds
  • 2,455
  • 6
  • 19
  • ah, I did try that before, there was just another issue that was causing composite_polygon_coords() to return a list of None which led me to believe it wasn't working. – Mr-Love Oct 27 '19 at 23:21