예제 #1
0
    def test_df_request_when_query_is_empty_should_be_taken_from_found_name_column(
            self, mock_request):
        foo_id = '123'
        foo_name = 'foo'
        geocoding_result = Regions([
            FeatureBuilder().set_id(foo_id).set_query('').set_name(
                foo_name).build_geocoded()
        ])

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                FeatureBuilder().set_id(foo_id).set_query(foo_id).set_name(foo_name).set_centroid(GeoPoint(0, 1)).build_geocoded()
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit)
                .set_ids([foo_id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert foo_name == df[DF_REQUEST][0]
예제 #2
0
def test_valid_success_response():
    foo = FeatureBuilder() \
        .set_query('foo') \
        .set_id('bar') \
        .set_name('baz') \
        .set_boundary(Polygon([Ring([GeoPoint(1, 2), GeoPoint(3, 4), GeoPoint(5, 6), GeoPoint(7, 8)])])) \
        .set_centroid(GeoPoint(9, 10)) \
        .set_limit(GeoRect(11, 12, 13, 14)) \
        .set_position(GeoRect(15, 16, 17, 18)) \
        .build_geocoded()

    foofoo = FeatureBuilder() \
        .set_query('foofoo') \
        .set_id('barbar') \
        .set_name('bazbaz') \
        .build_geocoded()

    response_dict = ResponseFormatter.format(
        ResponseBuilder() \
            .set_status(Status.success) \
            .set_message('OK') \
            .set_level(LevelKind.city) \
            .set_geocoded_features([foo, foofoo])
            .build()
    )

    response = ResponseParser.parse(response_dict)

    assert isinstance(response, SuccessResponse)
    assert 'OK' == response.message
    assert 2 == len(response.answers)
    assert_geocoded(foo, response.answers[0].features[0])
    assert_geocoded(foofoo, response.answers[1].features[0])
예제 #3
0
    def test_plot_should_have_geometries_when_regions_in_map_parameter(self, mock_request):

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                FeatureBuilder() \
                    .set_query(USA_REQUEST) \
                    .set_id(USA_ID) \
                    .set_name(USA_NAME) \
                    .set_boundary(GeoPoint(0, 1))
                    .build_geocoded(),
                FeatureBuilder() \
                    .set_query(RUSSIA_REQUEST) \
                    .set_id(RUSSIA_ID) \
                    .set_name(RUSSIA_NAME) \
                    .set_boundary(GeoPoint(0, 1))
                    .build_geocoded()

            ]
        ).build()

        plotSpec = ggplot() + geom_polygon(map=self.make_regions())

        # previous behaviour
        # expected_map_data_meta = {
        #    'georeference': {}
        # }

        expected_map_data_meta = {
            'geodataframe': {'geometry': 'geometry'}
        }

        assert expected_map_data_meta == get_map_data_meta(plotSpec, 0)
예제 #4
0
def test_reorder_for_centroids_should_happen(mock_request):
    new_york = FeatureBuilder().set_id('2').set_query('New York').set_name('New York').set_centroid(GeoPoint(0, 0)).build_geocoded()
    las_vegas = FeatureBuilder().set_id('3').set_query('Las Vegas').set_name('Las Vegas').set_centroid(GeoPoint(0, 0)).build_geocoded()

    los_angeles = FeatureBuilder().set_id('1').set_query('Los Angeles').set_name('Los Angeles').set_centroid(
        GeoPoint(0, 0)).build_geocoded()
    mock_request.return_value = make_success_response().set_geocoded_features([new_york, las_vegas, los_angeles]).build()

    df = Geocodes(
        level_kind=LevelKind.city,
        queries=features_to_queries([los_angeles, new_york, las_vegas, los_angeles]),
        answers=features_to_answers([los_angeles, new_york, las_vegas, los_angeles])
    ).centroids()

    assert ['Los Angeles', 'New York', 'Las Vegas', 'Los Angeles'] == df[DF_COLUMN_FOUND_NAME].tolist()
예제 #5
0
def make_region(request: str, name: str, geo_object_id: str, highlights: List[str]) -> GeocodedFeature:
    return FeatureBuilder() \
        .set_query(request) \
        .set_name(name) \
        .set_id(geo_object_id) \
        .set_highlights(highlights) \
        .build_geocoded()
예제 #6
0
def test_requestless_centroids():
    gdf = CentroidsGeoDataFrame().to_data_frame([
        FeatureBuilder()
            .set_id(ID)
            .set_name(FOUND_NAME)
            .set_centroid(make_centroid_point())
    ])
    assert_names(gdf, 0, FOUND_NAME, FOUND_NAME)
예제 #7
0
def test_requestless_limits():
    gdf = LimitsGeoDataFrame().to_data_frame([
        FeatureBuilder()
            .set_id(ID)
            .set_name(FOUND_NAME)
            .set_limit(make_limit_rect())
    ])
    assert_names(gdf, 0, FOUND_NAME, FOUND_NAME)
예제 #8
0
def test_requestless_boundaries():
    gdf = BoundariesGeoDataFrame().to_data_frame([
        FeatureBuilder()
            .set_id(ID)
            .set_name(FOUND_NAME)
            .set_boundary(make_single_point_boundary()) # dummy geometry to not fail on None property
    ])
    assert_names(gdf, 0, FOUND_NAME, FOUND_NAME)
예제 #9
0
def make_answer(name: str, geo_object_id: str,
                highlights: List[str]) -> Answer:
    return Answer([FeatureBuilder() \
                  .set_name(name) \
                  .set_id(geo_object_id) \
                  .set_highlights(highlights) \
                  .build_geocoded()
                   ]
                  )
예제 #10
0
    def setup(self):
        self.foo_id = 'foo_id'
        self.foo_query = 'foo'
        self.foo_name = 'Foo'
        self.foo: FeatureBuilder = FeatureBuilder().set_query(
            self.foo_query).set_id(self.foo_id).set_name(self.foo_name)

        self.bar_id = 'bar_id'
        self.bar_query = 'bar'
        self.bar_name = 'Bar'
        self.bar: FeatureBuilder = FeatureBuilder().set_query(
            self.bar_query).set_id(self.bar_id).set_name(self.bar_name)

        self.baz_id = 'baz_id'
        self.baz_query = 'baz'
        self.baz_name = 'Baz'
        self.baz: FeatureBuilder = FeatureBuilder().set_query(
            self.baz_query).set_id(self.baz_id).set_name(self.baz_name)
예제 #11
0
def test_reorder_for_centroids_should_happen(mock_request):
    mock_request.return_value = make_success_response() \
        .set_geocoded_features(
        [
            FeatureBuilder().set_id('2').set_query('New York').set_name('New York').set_centroid(GeoPoint(0, 0)).build_geocoded(),
            FeatureBuilder().set_id('3').set_query('Las Vegas').set_name('Las Vegas').set_centroid(GeoPoint(0, 0)).build_geocoded(),
            FeatureBuilder().set_id('1').set_query('Los Angeles').set_name('Los Angeles').set_centroid(GeoPoint(0, 0)).build_geocoded()
        ]
    ).build()

    df = Regions([
        make_region('Los Angeles', 'Los Angeles', '1', []),
        make_region('New York', 'New York', '2', []),
        make_region('Las Vegas', 'Las Vegas', '3', []),
        make_region('Los Angeles', 'Los Angeles', '1', []),
    ]).centroids()

    assert ['Los Angeles', 'New York', 'Las Vegas',
            'Los Angeles'] == df[DF_FOUND_NAME].tolist()
예제 #12
0
def test_requestless_limits():
    gdf = LimitsGeoDataFrame().to_data_frame(
        answers=[
            feature_to_answer(
                FeatureBuilder().set_id(ID).set_name(FOUND_NAME).set_limit(
                    make_limit_rect()).build_geocoded())
        ],
        queries=[RegionQuery(request=FOUND_NAME)],
        level_kind=LevelKind.city)
    assert_row(gdf, names=FOUND_NAME, found_name=FOUND_NAME)
예제 #13
0
def data_frame(r: GeoRect):
    return LimitsGeoDataFrame().to_data_frame(
        [
            FeatureBuilder() \
                .set_id(ID) \
                .set_query(NAME) \
                .set_name(FOUND_NAME) \
                .set_limit(r) \
                .build_geocoded()
        ]
    )
예제 #14
0
def test_requestless_boundaries():
    gdf = BoundariesGeoDataFrame().to_data_frame(
        answers=[
            feature_to_answer(
                FeatureBuilder().set_id(ID).set_name(FOUND_NAME).set_boundary(
                    make_single_point_boundary()
                )  # dummy geometry to not fail on None property
                .build_geocoded())
        ],
        queries=[RegionQuery(request=FOUND_NAME)],
        level_kind=LevelKind.city)
    assert_row(gdf, names=FOUND_NAME, found_name=FOUND_NAME)
예제 #15
0
    def test_exploding_answers_to_data_frame_take_request_from_feature_name(
            self, mock_request):
        foo_id = '123'
        foo_name = 'foo'

        bar_id = '456'
        bar_name = 'bar'
        geocoding_result = Geocodes(
            level_kind=LevelKind.city,
            queries=[RegionQuery(request=None)],
            answers=[
                Answer([
                    FeatureBuilder().set_id(foo_id).set_name(
                        foo_name).build_geocoded(),
                    FeatureBuilder().set_id(bar_id).set_name(
                        bar_name).build_geocoded()
                ])
            ])

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                FeatureBuilder().set_id(foo_id).set_query(foo_id).set_name(foo_name).set_centroid(
                    GeoPoint(0, 1)).build_geocoded(),
                FeatureBuilder().set_id(bar_id).set_query(bar_id).set_name(bar_name).set_centroid(
                    GeoPoint(2, 3)).build_geocoded(),
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit)
                .set_ids([foo_id, bar_id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert_request_and_found_name_are_equal(df)
예제 #16
0
    def make_geocoder(self) -> Geocoder:
        usa = FeatureBuilder() \
            .set_name(USA_NAME) \
            .set_id(USA_ID) \
            .set_highlights(USA_HIGHLIGHTS) \
            .build_geocoded()

        russia = FeatureBuilder() \
            .set_name(RUSSIA_NAME) \
            .set_id(RUSSIA_ID) \
            .set_highlights(RUSSIA_HIGHLIGHTS) \
            .build_geocoded()

        geocodes = Geocodes(level_kind=LevelKind.country,
                            queries=features_to_queries([usa, russia]),
                            answers=features_to_answers([usa, russia]))

        class StubGeocoder(Geocoder):
            def _geocode(self) -> Geocodes:
                return geocodes

        return StubGeocoder()
예제 #17
0
def test_ambiguous_response():
    foo = FeatureBuilder() \
        .set_query('foo') \
        .set_total_namesake_count(150) \
        .set_namesake_examples(FluentList() \
                               .add(Namesake('foo-namesake', FluentList() \
                                             .add(NamesakeParent('foo-ns-parent', LevelKind.city))
                                             .list()))
                               .add(Namesake('foo-namenamesake', FluentList() \
                                             .add(NamesakeParent('foo-nns-parent', LevelKind.state))
                                             .add(NamesakeParent('foo--nns-parent', LevelKind.county))
                                             .list()))
                               .list()) \
        .build_ambiguous()

    foofoo = FeatureBuilder() \
        .set_query("foofoo") \
        .set_total_namesake_count(13) \
        .set_namesake_examples([]) \
        .build_ambiguous()

    response_dict = ResponseFormatter.format(
        ResponseBuilder() \
            .set_status(Status.ambiguous) \
            .set_message('amb') \
            .set_level(LevelKind.city) \
            .set_ambiguous_features([foo, foofoo])
            .build()
    )

    response = ResponseParser.parse(response_dict)

    assert isinstance(response, AmbiguousResponse)
    assert 'amb' == response.message
    assert 2 == len(response.features)
    assert_ambiguous(foo, response.features[0])
    assert_ambiguous(foofoo, response.features[1])
예제 #18
0
def data_frame(r: GeoRect):
    return LimitsGeoDataFrame().to_data_frame(
        answers=[
            Answer([
                FeatureBuilder() \
                   .set_id(ID) \
                   .set_name(FOUND_NAME) \
                   .set_limit(r) \
                   .build_geocoded()
            ]
            )
        ],
        queries=[RegionQuery(request=NAME)],
        level_kind=LevelKind.city
    )
예제 #19
0
def feature(q: Query) -> FeatureBuilder:
    return FeatureBuilder().set_id(q.region_id).set_query(q.name).set_name(
        q.name)
예제 #20
0
def make_query(name: str, region_id: str) -> Query:
    region_feataure = FeatureBuilder().set_query(name).set_name(name).set_id(
        region_id).build_geocoded()
    return Query(name, region_id, MapRegion.with_ids([region_id]),
                 region_feataure)
예제 #21
0
class TestMapRegions:
    def setup(self):
        self.foo_id = 'foo_id'
        self.foo_query = 'foo'
        self.foo_name = 'Foo'
        self.foo = FeatureBuilder().set_query(self.foo_query).set_id(
            self.foo_id).set_name(self.foo_name)

        self.bar_id = 'bar_id'
        self.bar_query = 'bar'
        self.bar_name = 'Bar'
        self.bar = FeatureBuilder().set_query(self.bar_query).set_id(
            self.bar_id).set_name(self.bar_name)

        self.baz_id = 'baz_id'
        self.baz_query = 'baz'
        self.baz_name = 'Baz'
        self.baz = FeatureBuilder().set_query(self.baz_query).set_id(
            self.baz_id).set_name(self.baz_name)

    @mock.patch.object(GeocodingService, 'do_request')
    def test_boundaries(self, mock_request):
        try:
            self.make_regions().boundaries(resolution=RESOLUTION)
        except ValueError:
            pass  # response doesn't contain proper feature with ids - ignore

        mock_request.assert_called_with(
            ExplicitRequest(requested_payload=[PayloadKind.boundaries],
                            ids=[USA_ID, RUSSIA_ID],
                            resolution=_to_resolution(RESOLUTION)))

    @mock.patch.object(GeocodingService, 'do_request')
    def test_limits(self, mock_request):
        try:
            self.make_regions().limits()
        except ValueError:
            pass  # response doesn't contain proper feature with ids - ignore

        mock_request.assert_called_with(
            ExplicitRequest(requested_payload=[PayloadKind.limits],
                            ids=[USA_ID, RUSSIA_ID]))

    @mock.patch.object(GeocodingService, 'do_request')
    def test_centroids(self, mock_request):
        try:
            self.make_regions().centroids()
        except ValueError:
            pass  # response doesn't contain proper feature with ids - ignore

        mock_request.assert_called_with(
            ExplicitRequest(requested_payload=[PayloadKind.centroids],
                            ids=[USA_ID, RUSSIA_ID]))

    def test_to_dataframe(self):
        df = Regions([
            self.foo.set_query('').set_id('123').build_geocoded(),
            self.bar.set_query('').set_id('456').build_geocoded(),
        ]).to_data_frame()

        assert [self.foo.name, self.bar.name] == df[DF_REQUEST].tolist()

    def test_as_list(self):
        regions = Regions(
            [self.foo.build_geocoded(),
             self.bar.build_geocoded()]).as_list()

        assert 2 == len(regions)

        assert_region_df(self.foo, regions[0].to_data_frame())
        assert_region_df(self.bar, regions[1].to_data_frame())

    @mock.patch.object(GeocodingService, 'do_request')
    def test_df_request_when_query_is_empty_should_be_taken_from_found_name_column(
            self, mock_request):
        foo_id = '123'
        foo_name = 'foo'
        geocoding_result = Regions([
            FeatureBuilder().set_id(foo_id).set_query('').set_name(
                foo_name).build_geocoded()
        ])

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                FeatureBuilder().set_id(foo_id).set_query(foo_id).set_name(foo_name).set_centroid(GeoPoint(0, 1)).build_geocoded()
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit)
                .set_ids([foo_id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert foo_name == df[DF_REQUEST][0]

    @mock.patch.object(GeocodingService, 'do_request')
    def test_df_rows_order(self, mock_request):

        geocoding_result = Regions([
            self.foo.set_query('').build_geocoded(),
            self.bar.set_query('').build_geocoded(),
            self.baz.set_query('').build_geocoded(),
        ])

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                self.foo.set_query(self.bar_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
                self.bar.set_query(self.foo_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
                self.baz.set_query(self.baz_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit) \
                .set_ids([self.foo.id, self.bar.id, self.baz.id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert [self.foo.name, self.bar.name,
                self.baz.name] == df[DF_REQUEST].tolist()

    @mock.patch.object(GeocodingService, 'do_request')
    def test_df_rows_duplication_should_be_processed_correctly(
            self, mock_request):
        foo_id = '123'
        foo_name = 'foo'

        bar_id = '234'
        bar_name = 'bar'

        geocoding_result = Regions([
            self.foo.set_query('').build_geocoded(),
            self.bar.set_query('').build_geocoded(),
            self.foo.set_query('').build_geocoded()
        ])

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                self.foo.set_query(foo_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
                self.bar.set_query(bar_id).set_centroid(GeoPoint(0, 1)).build_geocoded()
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit) \
                .set_ids([self.foo.id, self.bar.id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert [self.foo.name, self.bar.name,
                self.foo.name] == df[DF_REQUEST].tolist()

    def test_plot_should_has_meta_map_for_georeference(self):
        plotSpec = ggplot() + geom_polygon(map=self.make_regions())

        expected_map_data_meta = {'georeference': {}}

        assert expected_map_data_meta == get_map_data_meta(plotSpec, 0)

    def make_regions(self) -> Regions:
        regions = Regions([
            make_region(USA_REQUEST, USA_NAME, USA_ID, USA_HIGHLIGHTS),
            make_region(RUSSIA_REQUEST, RUSSIA_NAME, RUSSIA_ID,
                        RUSSIA_HIGHLIGHTS)
        ])
        return regions
예제 #22
0
def ambiguous(feature: AmbiguousFeature) -> AmbiguousResponse:
    response: AmbiguousResponse = make_ambiguous_response().set_ambiguous_features([feature]).build()
    return response


def error(message: str) -> ErrorResponse:
    response: ErrorResponse = make_error_response().set_message(message).build()
    return response


@pytest.mark.parametrize('response, expected_message', [
    (ambiguous(
        FeatureBuilder()
            .set_query('NY')
            .set_total_namesake_count(2)
            .set_namesake_examples([Namesake('NY', [NamesakeParent('England', LevelKind.country)])])
            .build_ambiguous()),
     'Multiple objects (2) were found for NY:\n- NY (England)\n'
    ),

    (ambiguous(
        FeatureBuilder()
            .set_query('NY')
            .set_total_namesake_count(0)
            .set_namesake_examples([])
            .build_ambiguous()),
     'No objects were found for NY.\n'
    ),

    (error(
예제 #23
0
        regions_builder(level=LEVEL,
                        request=FILTER_LIST,
                        within=REGION_NAME,
                        highlights=True).build()
    except Exception:
        pass  # response doesn't contain proper feature with ids - ignore

    mock_geocoding.assert_called_with(
        GeocodingRequest(requested_payload=[PayloadKind.highlights],
                         resolution=None,
                         region_queries=[REGION_QUERY_LA, REGION_QUERY_NY],
                         level=LEVEL_KIND,
                         namesake_example_limit=NAMESAKES_EXAMPLE_LIMIT))


FOO = FeatureBuilder().set_query('foo').set_name('fooname').set_id(
    'fooid').build_geocoded()
BAR = FeatureBuilder().set_query('foo').set_name('barname').set_id(
    'barid').build_geocoded()


@pytest.mark.parametrize(
    'location,expected',
    [
        # none
        (None, None),

        # single string
        ('name', MapRegion.with_name('name')),

        # single region
        (Regions([FOO, BAR]), MapRegion.with_ids([FOO.id, BAR.id])),
예제 #24
0
class TestMapRegions:

    def setup(self):
        self.foo_id = 'foo_id'
        self.foo_query = 'foo'
        self.foo_name = 'Foo'
        self.foo = FeatureBuilder().set_query(self.foo_query).set_id(self.foo_id).set_name(self.foo_name)

        self.bar_id = 'bar_id'
        self.bar_query = 'bar'
        self.bar_name = 'Bar'
        self.bar = FeatureBuilder().set_query(self.bar_query).set_id(self.bar_id).set_name(self.bar_name)

        self.baz_id = 'baz_id'
        self.baz_query = 'baz'
        self.baz_name = 'Baz'
        self.baz = FeatureBuilder().set_query(self.baz_query).set_id(self.baz_id).set_name(self.baz_name)

    @mock.patch.object(GeocodingService, 'do_request')
    def test_boundaries(self, mock_request):
        try:
            self.make_regions().boundaries(resolution=RESOLUTION)
        except ValueError:
            pass  # response doesn't contain proper feature with ids - ignore

        mock_request.assert_called_with(
            ExplicitRequest(
                requested_payload=[PayloadKind.boundaries],
                ids=[USA_ID, RUSSIA_ID],
                resolution=_coerce_resolution(RESOLUTION)
            )
        )

    @pytest.mark.parametrize('str,expected', [
        pytest.param('city', Resolution.city_medium),
        pytest.param('county', Resolution.county_medium),
        pytest.param('state', Resolution.state_medium),
        pytest.param('country', Resolution.country_medium),
        pytest.param('world', Resolution.world_medium),
        pytest.param('city_high', Resolution.city_high)
    ])
    def test_parse_resolution(self, str, expected):
        assert expected == _parse_resolution(str)

    @mock.patch.object(GeocodingService, 'do_request')
    def test_limits(self, mock_request):
        try:
            self.make_regions().limits()
        except ValueError:
            pass  # response doesn't contain proper feature with ids - ignore

        mock_request.assert_called_with(
            ExplicitRequest(
                requested_payload=[PayloadKind.limits],
                ids=[USA_ID, RUSSIA_ID]
            )
        )

    @mock.patch.object(GeocodingService, 'do_request')
    def test_centroids(self, mock_request):
        try:
            self.make_regions().centroids()
        except ValueError:
            pass  # response doesn't contain proper feature with ids - ignore

        mock_request.assert_called_with(
            ExplicitRequest(
                requested_payload=[PayloadKind.centroids],
                ids=[USA_ID, RUSSIA_ID]
            )
        )

    def test_to_dataframe(self):
        df = Regions(
            LevelKind.city,
            [
                self.foo.set_query('').set_id('123').build_geocoded(),
                self.bar.set_query('').set_id('456').build_geocoded(),
            ]
        ).to_data_frame()

        assert [self.foo.name, self.bar.name] == df[DF_REQUEST].tolist()

    def test_as_list(self):
        regions = Regions(
            LevelKind.city,
            [
                self.foo.build_geocoded(),
                self.bar.build_geocoded()
            ]
        ).as_list()

        assert 2 == len(regions)

        assert_region_df(self.foo, regions[0].to_data_frame())
        assert_region_df(self.bar, regions[1].to_data_frame())

    @mock.patch.object(GeocodingService, 'do_request')
    def test_df_request_when_query_is_empty_should_be_taken_from_found_name_column(self, mock_request):
        foo_id = '123'
        foo_name = 'foo'
        geocoding_result = Regions(
            LevelKind.city,
            [
                FeatureBuilder().set_id(foo_id).set_query('').set_name(foo_name).build_geocoded()
            ]
        )

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                FeatureBuilder().set_id(foo_id).set_query(foo_id).set_name(foo_name).set_centroid(
                    GeoPoint(0, 1)).build_geocoded()
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit)
                .set_ids([foo_id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert foo_name == df[DF_REQUEST][0]

    @mock.patch.object(GeocodingService, 'do_request')
    def test_df_rows_order(self, mock_request):

        geocoding_result = Regions(
            LevelKind.city,
            [
                self.foo.set_query('').build_geocoded(),
                self.bar.set_query('').build_geocoded(),
                self.baz.set_query('').build_geocoded(),
            ]
        )

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                self.foo.set_query(self.bar_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
                self.bar.set_query(self.foo_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
                self.baz.set_query(self.baz_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit) \
                .set_ids([self.foo.id, self.bar.id, self.baz.id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert [self.foo.name, self.bar.name, self.baz.name] == df[DF_REQUEST].tolist()

    @mock.patch.object(GeocodingService, 'do_request')
    def test_df_rows_duplication_should_be_processed_correctly(self, mock_request):
        foo_id = '123'
        foo_name = 'foo'

        bar_id = '234'
        bar_name = 'bar'

        geocoding_result = Regions(
            LevelKind.city,
            [
                self.foo.set_query('').build_geocoded(),
                self.bar.set_query('').build_geocoded(),
                self.foo.set_query('').build_geocoded()
            ]
        )

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                self.foo.set_query(foo_id).set_centroid(GeoPoint(0, 1)).build_geocoded(),
                self.bar.set_query(bar_id).set_centroid(GeoPoint(0, 1)).build_geocoded()
            ]
        ).build()

        df = geocoding_result.centroids()

        mock_request.assert_called_with(
            RequestBuilder() \
                .set_request_kind(RequestKind.explicit) \
                .set_ids([self.foo.id, self.bar.id]) \
                .set_requested_payload([PayloadKind.centroids]) \
                .build()
        )

        assert [self.foo.name, self.bar.name, self.foo.name] == df[DF_REQUEST].tolist()

    # python invokes geocoding functions when Regions objects detected in map
    # changed from previous version, where client invoked these functions
    @mock.patch.object(GeocodingService, 'do_request')
    def test_plot_should_have_geometries_when_regions_in_map_parameter(self, mock_request):

        mock_request.return_value = make_success_response() \
            .set_geocoded_features(
            [
                FeatureBuilder() \
                    .set_query(USA_REQUEST) \
                    .set_id(USA_ID) \
                    .set_name(USA_NAME) \
                    .set_boundary(GeoPoint(0, 1))
                    .build_geocoded(),
                FeatureBuilder() \
                    .set_query(RUSSIA_REQUEST) \
                    .set_id(RUSSIA_ID) \
                    .set_name(RUSSIA_NAME) \
                    .set_boundary(GeoPoint(0, 1))
                    .build_geocoded()

            ]
        ).build()

        plotSpec = ggplot() + geom_polygon(map=self.make_regions())

        # previous behaviour
        # expected_map_data_meta = {
        #    'georeference': {}
        # }

        expected_map_data_meta = {
            'geodataframe': {'geometry': 'geometry'}
        }

        assert expected_map_data_meta == get_map_data_meta(plotSpec, 0)

    def make_regions(self) -> Regions:
        regions = Regions(
            LevelKind.country,
            [
                make_region(USA_REQUEST, USA_NAME, USA_ID, USA_HIGHLIGHTS),
                make_region(RUSSIA_REQUEST, RUSSIA_NAME, RUSSIA_ID, RUSSIA_HIGHLIGHTS)
            ]
        )
        return regions
예제 #25
0
    GEO_RECT_MIN_LAT, GEO_RECT_MAX_LAT
from pandas import DataFrame

from lets_plot.geo_data.gis.request import RegionQuery, LevelKind
from lets_plot.geo_data.gis.response import SuccessResponse, FeatureBuilder
from lets_plot.geo_data.to_geo_data_frame import LimitsGeoDataFrame, CentroidsGeoDataFrame, BoundariesGeoDataFrame
from .geo_data import CENTROID_LON, CENTROID_LAT, GEO_RECT_MIN_LON, GEO_RECT_MIN_LAT, GEO_RECT_MAX_LON, GEO_RECT_MAX_LAT
from .geo_data import GJMultipolygon, GJPolygon
from .geo_data import ID, NAME, FOUND_NAME
from .geo_data import assert_success_response, assert_row, make_success_response
from .geo_data import feature_to_answer, features_to_answers, features_to_queries
from .geo_data import make_limit_rect, make_centroid_point, polygon, ring, point, make_polygon_boundary, multipolygon, \
    make_multipolygon_boundary, make_single_point_boundary

NAMED_FEATURE_BUILDER = FeatureBuilder() \
    .set_query(NAME) \
    .set_id(ID) \
    .set_name(FOUND_NAME)


def test_requestless_boundaries():
    gdf = BoundariesGeoDataFrame().to_data_frame(
        answers=[
            feature_to_answer(
                FeatureBuilder().set_id(ID).set_name(FOUND_NAME).set_boundary(
                    make_single_point_boundary()
                )  # dummy geometry to not fail on None property
                .build_geocoded())
        ],
        queries=[RegionQuery(request=FOUND_NAME)],
        level_kind=LevelKind.city)
    assert_row(gdf, names=FOUND_NAME, found_name=FOUND_NAME)
예제 #26
0
def ambiguous(feature: AmbiguousFeature) -> AmbiguousResponse:
    response: AmbiguousResponse = make_ambiguous_response(
    ).set_ambiguous_features([feature]).build()
    return response


def error(message: str) -> ErrorResponse:
    response: ErrorResponse = make_error_response().set_message(
        message).build()
    return response


@pytest.mark.parametrize('response, expected_message', [
    (ambiguous(FeatureBuilder().set_query('NY').set_total_namesake_count(
        2).set_namesake_examples([
            Namesake('NY', [NamesakeParent('England', LevelKind.country)])
        ]).build_ambiguous()),
     'Multiple objects (2) were found for NY:\n- NY (England)\n'),
    (ambiguous(FeatureBuilder().set_query('NY').set_total_namesake_count(
        0).set_namesake_examples(
            []).build_ambiguous()), 'No objects were found for NY.\n'),
    (error(ERROR_MESSAGE), 'Error: error msg'),
])
def test_args_that_fail(response, expected_message):
    assert expected_message == _format_error_message(response)


def test_create_multiple_error_message():
    query = 'York'
    namesakes: List[Namesake] = \
        [
예제 #27
0
        geocode(level=LEVEL, names=FILTER_LIST).scope(REGION_NAME).highlights(True).get_geocodes()
    except Exception:
        pass  # response doesn't contain proper feature with ids - ignore

    mock_geocoding.assert_called_with(
        GeocodingRequest(requested_payload=[PayloadKind.highlights],
                         resolution=None,
                         region_queries=[REGION_QUERY_LA, REGION_QUERY_NY],
                         scope=MapRegion.with_name(REGION_NAME),
                         level=LEVEL_KIND,
                         namesake_example_limit=NAMESAKES_EXAMPLE_LIMIT,
                         allow_ambiguous=False
                         )
    )

FOO_FEATURE = FeatureBuilder().set_name('fooname').set_id('fooid').build_geocoded()
BAR_FEATURE = FeatureBuilder().set_name('barname').set_id('barid').build_geocoded()

FOO = Answer([FeatureBuilder().set_name('fooname').set_id('fooid').build_geocoded()])
BAR = Answer([FeatureBuilder().set_name('barname').set_id('barid').build_geocoded()])

@pytest.mark.parametrize('location,expected', [
    # none
    (None,
     None
     ),

    # single string
    ('name',
     MapRegion.with_name('name')
     ),