Beispiel #1
0
    def test_direct_answers_take_request_from_query(self, mock_request):

        geocoding_result = Geocodes(
            level_kind=LevelKind.city,
            queries=[
                RegionQuery(request='fooo'),
                RegionQuery(request='barr'),
                RegionQuery(request='bazz'),
            ],
            answers=[
                Answer([self.foo.set_query('').build_geocoded()]),
                Answer([self.bar.set_query('').build_geocoded()]),
                Answer([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_row(df, names=['fooo', 'barr', 'bazz'])
Beispiel #2
0
    def test_to_dataframe(self):
        df = Geocodes(
            level_kind=LevelKind.city,
            queries=[RegionQuery(request='FOO'),
                     RegionQuery(request='BAR')],
            answers=features_to_answers(
                [self.foo.build_geocoded(),
                 self.bar.build_geocoded()])).to_data_frame()

        assert_row(df, names=['FOO', 'BAR'])
Beispiel #3
0
def make_geocode_region(request: str,
                        name: str,
                        geo_object_id: str,
                        highlights: List[str],
                        level_kind: LevelKind = LevelKind.city) -> Geocodes:
    return Geocodes(level_kind=level_kind,
                    queries=[RegionQuery(request=request)],
                    answers=[make_answer(name, geo_object_id, highlights)])
Beispiel #4
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)
Beispiel #5
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)
Beispiel #6
0
    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 = Geocodes(level_kind=LevelKind.city,
                                    queries=[
                                        RegionQuery('foo'),
                                        RegionQuery('bar'),
                                        RegionQuery('foo')
                                    ],
                                    answers=[
                                        Answer([self.foo.build_geocoded()]),
                                        Answer([self.bar.build_geocoded()]),
                                        Answer([self.foo.build_geocoded()])
                                    ])

        mock_request.return_value = make_success_response() \
            .set_answers(
            [
                Answer([self.foo.set_query(foo_id).set_centroid(GeoPoint(0, 1)).build_geocoded()]),
                Answer([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_row(df, names=['foo', 'bar', 'foo'])
Beispiel #7
0
def query(request: Optional[str] = None,
          scope: Optional[Union[str, MapRegion]] = None,
          ignoring_strategy: Optional[IgnoringStrategyKind] = None,
          near: Optional[Union[str, GeoPoint]] = None,
          box: Optional[GeoRect] = None) -> RegionQuery:
    if isinstance(scope, MapRegion):
        pass
    elif isinstance(scope, str):
        scope = MapRegion.with_name(scope)
    else:
        scope = None

    return RegionQuery(request, scope,
                       AmbiguityResolver(ignoring_strategy, near, box))
Beispiel #8
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
    )
Beispiel #9
0
def make_simple_region(requests: Union[str, List[str]],
                       geo_object_ids: Union[str, List[str]] = None,
                       level_kind: LevelKind = LevelKind.county) -> Geocodes:
    requests = requests if isinstance(requests, (list, tuple)) else [requests]
    geo_object_ids = geo_object_ids if geo_object_ids is not None else [
        request + '_id' for request in requests
    ]
    geo_object_ids = geo_object_ids if isinstance(
        geo_object_ids, (list, tuple)) else [geo_object_ids]

    queries = []
    answers = []
    for request, id in zip(requests, geo_object_ids):
        queries.append(RegionQuery(request=request))
        answers.append(make_answer(request, id, []))

    return Geocodes(level_kind, answers, queries)
Beispiel #10
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)
def _query(request: Optional[str],
           scope: Optional[MapRegion] = None,
           ambiguity_resolver: AmbiguityResolver = AmbiguityResolver.empty()):
    return RegionQuery(request, scope, ambiguity_resolver)
Beispiel #12
0
def features_to_queries(features: List[GeocodedFeature]) -> List[RegionQuery]:
    return [RegionQuery(feature.name) for feature in features]
Beispiel #13
0
from lets_plot.geo_data.gis.request import MapRegion, RegionQuery, MISSING_LEVEL_AND_SCOPE_OR_REQUEST_EXCEPTION_TEXT, \
    MISSING_LEVEL_OR_REQUEST_EXCEPTION_TEXT, GeocodingRequest, \
    AmbiguityResolver
from lets_plot.geo_data.gis.response import LevelKind

REACTION_KIND_ALERT: AmbiguityResolver = AmbiguityResolver.empty()

NAME = 'NY'
LEVEL: LevelKind = LevelKind.city
REGION_STR = 'ignored'
PARENT = MapRegion.with_name(REGION_STR)


@pytest.mark.parametrize('region_queries,level,message', [
    ([], None, MISSING_LEVEL_AND_SCOPE_OR_REQUEST_EXCEPTION_TEXT),
    ([RegionQuery(None, None, REACTION_KIND_ALERT)], None, MISSING_LEVEL_AND_SCOPE_OR_REQUEST_EXCEPTION_TEXT),
    ([RegionQuery(None, PARENT, REACTION_KIND_ALERT)], None, MISSING_LEVEL_OR_REQUEST_EXCEPTION_TEXT),
])
def test_args_that_fail(region_queries: List[RegionQuery],
                        level: Optional[LevelKind],
                        message: str):
    with pytest.raises(ValueError) as exception:
        GeocodingRequest._check_required_parameters(region_queries, level)

    assert message == exception.value.args[0]


@pytest.mark.parametrize('region_queries,level', [
    ([RegionQuery(None, None, REACTION_KIND_ALERT)], LevelKind.country),
    ([RegionQuery('ignored_value', None, REACTION_KIND_ALERT)], None),
    ([RegionQuery(None, PARENT, REACTION_KIND_ALERT)], LevelKind.state),
Beispiel #14
0
RECT_DATA_FRAME = DataFrame({DATAFRAME_COLUMN_NAME: DATAFRAME_NAME_LIST, 'lonmin': [1, 2], 'latmin': [3, 4], 'lonmax': [5, 6], 'latmax': [7, 8]})

LEVEL_KIND: LevelKind = LevelKind.county
LEVEL: str = LEVEL_KIND.value
FILTER = 'Texas'
FILTER_LIST = ['LA', 'NY']
REGION_NAME = 'USA'
REGION_ID = '8898'
REGION_LIST = [REGION_ID]
RESOLUTION = 12
REQUEST = 'united states'
REGION_HIGHLIGHTS = ['united states', 'united states of america']

PARENT_WITH_NAME = MapRegion.with_name(REGION_NAME)

REGION_QUERY_LA = RegionQuery('LA', None, AmbiguityResolver())
REGION_QUERY_NY = RegionQuery('NY', None, AmbiguityResolver())

NAMESAKES_EXAMPLE_LIMIT = 10


def feature_id(answer: Answer) -> str:
    assert len(answer.features) == 1
    return answer.features[0].id


def make_expected_map_region(region_kind: RegionKind, values):
    return {
        'type': region_kind.value,
        'data': values
    }
Beispiel #15
0
})

LEVEL_KIND: LevelKind = LevelKind.county
LEVEL: str = LEVEL_KIND.value
FILTER = 'Texas'
FILTER_LIST = ['LA', 'NY']
REGION_NAME = 'USA'
REGION_ID = '8898'
REGION_LIST = [REGION_ID]
RESOLUTION = 12
REQUEST = 'united states'
REGION_HIGHLIGHTS = ['united states', 'united states of america']

PARENT_WITH_NAME = MapRegion.with_name(REGION_NAME)

REGION_QUERY_LA = RegionQuery('LA', PARENT_WITH_NAME, AmbiguityResolver())
REGION_QUERY_NY = RegionQuery('NY', PARENT_WITH_NAME, AmbiguityResolver())

NAMESAKES_EXAMPLE_LIMIT = 10


def make_expected_map_region(region_kind: RegionKind, values):
    return {'type': region_kind.value, 'data': values}


@mock.patch.object(GeocodingService, 'do_request')
def test_regions(mock_geocoding):
    try:
        regions(level=LEVEL, request=FILTER_LIST,
                within=REGION_NAME).to_data_frame()
    except Exception:
Beispiel #16
0
from lets_plot.geo_data.gis.request import MapRegion, RegionQuery, MISSING_LEVEL_AND_WITHIN_OR_REQUEST_EXCEPTION_TEXT, \
    MISSING_LEVEL_OR_REQUEST_EXCEPTION_TEXT, MISSING_WITHIN_OR_REQUEST_EXCEPTION_TEXT, GeocodingRequest, \
    AmbiguityResolver
from lets_plot.geo_data.gis.response import LevelKind

REACTION_KIND_ALERT: AmbiguityResolver = AmbiguityResolver.empty()

NAME = 'NY'
LEVEL: LevelKind = LevelKind.city
REGION_STR = 'ignored'
PARENT = MapRegion.with_name(REGION_STR)


@pytest.mark.parametrize('region_queries,level,message', [
    ([], None, MISSING_LEVEL_AND_WITHIN_OR_REQUEST_EXCEPTION_TEXT),
    ([RegionQuery(None, None, REACTION_KIND_ALERT)
      ], None, MISSING_LEVEL_AND_WITHIN_OR_REQUEST_EXCEPTION_TEXT),
    ([RegionQuery(None, PARENT, REACTION_KIND_ALERT)
      ], None, MISSING_LEVEL_OR_REQUEST_EXCEPTION_TEXT),
    ([RegionQuery(None, None, REACTION_KIND_ALERT)
      ], LevelKind.state, MISSING_WITHIN_OR_REQUEST_EXCEPTION_TEXT),
])
def test_args_that_fail(region_queries: List[RegionQuery],
                        level: Optional[LevelKind], message: str):
    with pytest.raises(ValueError) as exception:
        GeocodingRequest._check_required_parameters(region_queries, level)

    assert message == exception.value.args[0]


@pytest.mark.parametrize('region_queries,level', [