feat(clients): maps: Places, Address Validation, Solar, Pollen, Air Quality, Area Insights, Routes, web services, Street View, key handling

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-25 10:31:52 +01:00
co-authored by Claude Sonnet 5.5
parent 3db67fcf1f
commit bf7b6fb3c8
30 changed files with 3941 additions and 3 deletions
+77
View File
@@ -0,0 +1,77 @@
// Routes: every POST that would call Google Maps. No credential is 503
// google_not_configured, bad input is 422 before any traffic, GET is 405, and
// with a credential but no confirm the answer is a dry run that shows the
// exact request and sends nothing.
#include <string>
#include <vector>
#include "support/GoogleRig.hpp"
using namespace molo::example::test;
namespace {
struct Case {
std::string path;
std::string good;
std::string bad;
std::string expect_in_request; // proof of the exact request shape
};
} // namespace
int main() {
const std::string json = "application/json";
const std::vector<Case> cases = {
{"/google/maps/places/search", "{\"query\":\"pizza\",\"limit\":\"3\"}", "{\"query\":\"\"}",
"/v1/places:searchText?fields=places.id"},
{"/google/maps/places/nearby", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"radius\":\"300\",\"type\":\"cafe\"}",
"{\"lat\":\"99\",\"lng\":\"4.89\"}", "/v1/places:searchNearby"},
{"/google/maps/places/autocomplete", "{\"input\":\"Dam\"}", "{}", "/v1/places:autocomplete"},
{"/google/maps/places/details", "{\"place_id\":\"ChIJabc\"}", "{\"place_id\":\"a/../b\"}",
"/v1/places/ChIJabc?fields="},
{"/google/maps/address/validate", "{\"region\":\"NL\",\"lines\":\"Dam 1\"}", "{\"region\":\"NL\"}",
"/v1:validateAddress"},
{"/google/maps/solar", "{\"lat\":\"52.37\",\"lng\":\"4.89\"}", "{\"lat\":\"x\",\"lng\":\"4\"}",
"/v1/buildingInsights:findClosest?location.latitude=52.37"},
{"/google/maps/pollen", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"days\":\"2\"}",
"{\"lat\":\"52.37\",\"lng\":\"4.89\",\"days\":\"9\"}", "/v1/forecast:lookup?"},
{"/google/maps/air", "{\"lat\":\"52.37\",\"lng\":\"4.89\"}", "{\"lat\":\"52.37\"}",
"/v1/currentConditions:lookup"},
{"/google/maps/area", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"radius\":\"500\"}",
"{\"lat\":\"52.37\",\"lng\":\"4.89\",\"radius\":\"0\"}", "/v1:computeInsights"},
{"/google/maps/routes", "{\"origin\":\"52.37,4.89\",\"destination\":\"Utrecht Centraal\"}",
"{\"origin\":\"52.37,4.89\"}", "/directions/v2:computeRoutes?fields=routes.duration"},
{"/google/maps/geocode", "{\"address\":\"Dam 1 Amsterdam\"}", "{\"lat\":\"1\"}",
"/maps/api/geocode/json?address=Dam%201%20Amsterdam"},
{"/google/maps/timezone", "{\"lat\":\"52.37\",\"lng\":\"4.89\",\"timestamp\":\"1700000000\"}",
"{\"lat\":\"52.37\",\"lng\":\"4.89\"}", "/maps/api/timezone/json?location=52.3700000"},
{"/google/maps/elevation", "{\"locations\":\"52.37,4.89|52.38,4.90\"}", "{\"locations\":\"nope\"}",
"/maps/api/elevation/json?locations=52.3700000"},
{"/google/maps/streetview/list", "{\"limit\":\"2\"}", "{\"limit\":\"500\"}", "/v1/photos?pageSize=2"},
};
for (const Case& c : cases) {
{
GoogleRig rig(false);
Fixture f(rig.client);
auto res = f.client->post(c.path, c.good, json);
check(res.status == 503, c.path + ": no credential is 503");
check(contains(res.body, "google_not_configured"), c.path + ": error code google_not_configured");
check(contains(res.headers.get("Content-Type"), "application/json"), c.path + ": error body is json");
check(rig.mock->send_count() == 0, c.path + ": nothing sent without a credential");
}
{
GoogleRig rig;
Fixture f(rig.client);
auto bad = f.client->post(c.path, c.bad, json);
check(bad.status == 422, c.path + ": bad input is 422");
check(contains(bad.body, "validation_error"), c.path + ": error code validation_error");
check(f.client->get(c.path).status == 405, c.path + ": get is 405");
auto dry = f.client->post(c.path, c.good, json);
check(dry.status == 200, c.path + ": dry run is 200");
check(contains(dry.body, "\"dry_run\":true"), c.path + ": answer says dry run");
check(contains(dry.body, c.expect_in_request), c.path + ": exact request shown (" + c.expect_in_request + ")");
check(!contains(dry.body, kTestKey), c.path + ": credential never shown");
check(rig.mock->send_count() == 0, c.path + ": side effect: a dry run sends nothing");
}
}
return finish("google/maps/calls");
}
@@ -0,0 +1,48 @@
// Routes: DELETE /google/maps/streetview/photo/{id} (destructive: dry run
// unless ?confirm=true) and POST /google/maps/keys/lint (local, no credential).
#include "support/GoogleRig.hpp"
using namespace molo::example::test;
using molo::example::fw::Method;
int main() {
const std::string json = "application/json";
{
GoogleRig rig(false);
Fixture f(rig.client);
auto res = f.client->request(Method::Delete, "/google/maps/streetview/photo/p1");
check(res.status == 503 && contains(res.body, "google_not_configured"), "delete without credential is 503");
check(rig.mock->send_count() == 0, "side effect: nothing sent");
}
{
GoogleRig rig;
Fixture f(rig.client);
auto res = f.client->request(Method::Delete, "/google/maps/streetview/photo/p1");
check(res.status == 200 && contains(res.body, "\"dry_run\":true"), "delete is a dry run by default");
check(contains(res.body, "\"method\":\"DELETE\"") && contains(res.body, "/v1/photo/p1"),
"dry run shows the DELETE request");
check(rig.mock->send_count() == 0, "side effect: the dry run deleted nothing");
check(f.client->request(Method::Delete, "/google/maps/streetview/photo/a..b%2Fc").status != 200 ||
rig.mock->send_count() == 0,
"odd ids never reach Google");
check(f.client->get("/google/maps/streetview/photo/p1").status == 405, "get is 405");
}
{
GoogleRig rig(false);
Fixture f(rig.client);
auto open = f.client->post("/google/maps/keys/lint", "{}", json);
check(open.status == 200, "lint works without a credential");
check(contains(open.body, "\"scope\":\"local\""), "lint is local");
check(contains(open.body, "no application restriction") && contains(open.body, "no API restriction"),
"an unrestricted key is reported");
auto good = f.client->post("/google/maps/keys/lint",
"{\"referrers\":\"https://*.example.com/*\",\"apis\":\"places.googleapis.com\"}", json);
check(good.status == 200 && contains(good.body, "\"findings\":[]"), "a restricted key has no findings");
check(contains(good.body, "allowedReferrers") && contains(good.body, "apiTargets"), "restrictions rendered");
auto both = f.client->post("/google/maps/keys/lint",
"{\"referrers\":\"https://a.com/*\",\"ips\":\"1.2.3.4\"}", json);
check(both.status == 422, "two application restriction kinds are 422");
check(f.client->get("/google/maps/keys/lint").status == 405, "get is 405");
}
return finish("google/maps/delete_and_keys");
}
+43
View File
@@ -0,0 +1,43 @@
// Route: GET /google/maps, /google/maps/status, /google/maps/calls (never call Google)
#include "support/GoogleRig.hpp"
using namespace molo::example::test;
int main() {
{
GoogleRig rig;
Fixture f(rig.client);
auto page = f.client->get("/google/maps");
check(page.status == 200, "page is 200");
check(contains(page.headers.get("Content-Type"), "text/html"), "page is html");
check(contains(page.body, "viewport") || contains(page.body, "Google Maps Platform"), "page renders");
check(contains(page.body, "/embedded/google_maps.js"), "page loads its script");
auto st = f.client->get("/google/maps/status");
check(st.status == 200, "status is 200");
check(contains(st.headers.get("Content-Type"), "application/json"), "status is json");
check(contains(st.body, "\"configured\":true"), "configured with a key");
check(contains(st.body, "\"max_points\":512"), "caps shown");
check(!contains(st.body, kTestKey), "credential never shown");
auto calls = f.client->get("/google/maps/calls");
check(calls.status == 200, "calls is 200");
check(contains(calls.body, "places.places.searchText"), "places search declared");
check(contains(calls.body, "\"source\":\"reference\""), "reference rows are marked");
check(contains(calls.body, "directions/v2:computeRoutes"), "routes declared");
check(!contains(calls.body, kTestKey), "no credential in the table");
check(f.client->post("/google/maps").status == 405, "page post is 405");
check(f.client->post("/google/maps/status").status == 405, "status post is 405");
check(f.client->post("/google/maps/calls").status == 405, "calls post is 405");
check(rig.mock->send_count() == 0, "side effect: no upstream traffic");
}
{
GoogleRig rig(false);
Fixture f(rig.client);
check(contains(f.client->get("/google/maps/status").body, "\"configured\":false"),
"not configured without a key");
check(f.client->get("/google/maps").status == 200, "page works without a credential");
}
return finish("google/maps/status");
}
+492
View File
@@ -0,0 +1,492 @@
// Maps package: deterministic local tests (call table, path rendering,
// validation, caps, request shapes through the dry run, key handling, no
// credential behavior). No scripted Google replies: shapes are verified
// against Google's Discovery documents by src/google/maps/tools/
// check_discovery.py and live (see src/google/maps/SPEC.md).
#include <memory>
#include <set>
#include "framework.h"
#include "clients/transports/mock_transport.h"
#include "google/errors.h"
#include "google/maps/address_validation.h"
#include "google/maps/calls.h"
#include "google/maps/caps.h"
#include "google/maps/environment.h"
#include "google/maps/maps_key.h"
#include "google/maps/places.h"
#include "google/maps/routes.h"
#include "google/maps/street_view.h"
#include "google/maps/web_services.h"
using namespace molo::google;
using namespace molo::google::maps;
using molo::clients::body::Json;
using molo::clients::transports::MockTransport;
namespace {
struct Rig {
MockTransport* mock;
std::shared_ptr<GoogleClient> client;
Rig() {
auto t = std::make_unique<MockTransport>();
mock = t.get();
client = std::make_shared<GoogleClient>(std::move(t), nullptr); // no credential
}
};
template <typename F>
bool invalid(F&& f) {
try {
f();
} catch (const NotConfiguredError&) {
return false; // passed validation, stopped at the credential check
} catch (const GoogleError& e) {
return e.http_status() == 400 && e.status() == "INVALID_ARGUMENT";
}
return false;
}
template <typename F>
bool not_configured(F&& f) {
try {
f();
} catch (const NotConfiguredError&) {
return true;
} catch (...) {
}
return false;
}
const LatLng kAmsterdam{52.3702157, 4.8951679};
} // namespace
TEST(maps, call_table_is_unique_and_complete) {
std::set<int> calls;
std::set<std::string> rpcs;
for (std::size_t i = 0; i < call_count(); ++i) {
const CallSpec& s = spec_at(i);
ASSERT_TRUE(calls.insert(static_cast<int>(s.call)).second);
ASSERT_TRUE(rpcs.insert(s.rpc_id).second);
ASSERT_TRUE(std::string(s.source) == "discovery" || std::string(s.source) == "reference");
ASSERT_EQ(spec_of(s.call).rpc_id, std::string(s.rpc_id));
}
ASSERT_EQ(call_count(), static_cast<std::size_t>(38));
ASSERT_EQ(static_cast<std::size_t>(Call::kApiKeysGet) + 1, call_count());
}
TEST(maps, path_rendering) {
ASSERT_EQ(render(Call::kPlacesGet, {{"name", "places/ChIJabc-_"}}), "/v1/places/ChIJabc-_");
ASSERT_EQ(render(Call::kPlacesSearchText), "/v1/places:searchText");
ASSERT_EQ(render(Call::kRoutesCompute), "/directions/v2:computeRoutes");
ASSERT_EQ(render(Call::kRoutesMatrix), "/distanceMatrix/v2:computeRouteMatrix");
ASSERT_EQ(render(Call::kGeocode), "/maps/api/geocode/json");
ASSERT_EQ(render(Call::kStreetPhotoGet, {{"photoId", "p1"}}), "/v1/photo/p1");
ASSERT_EQ(render(Call::kPollenHeatmapTile, {{"mapType", "TREE_UPI"}, {"zoom", "2"}, {"x", "1"}, {"y", "3"}}),
"/v1/mapTypes/TREE_UPI/heatmapTiles/2/1/3");
ASSERT_TRUE(invalid([] { render(Call::kPlacesGet, {{"name", "places/../x"}}); }));
ASSERT_TRUE(invalid([] { render(Call::kPlacesGet, {{"name", "places//x"}}); }));
ASSERT_TRUE(invalid([] { render(Call::kPlacesGet, {}); }));
ASSERT_TRUE(invalid([] { render(Call::kPlacesSearchText, {{"extra", "x"}}); }));
ASSERT_TRUE(invalid([] { render(Call::kStreetPhotoGet, {{"photoId", "a/b"}}); }));
ASSERT_TRUE(method_of(Call::kStreetPhotoUpdate) == molo::clients::Method::kPut);
ASSERT_TRUE(method_of(Call::kStreetPhotoDelete) == molo::clients::Method::kDelete);
}
TEST(maps, endpoints_prefer_key_except_oauth_only_apis) {
ASSERT_TRUE(endpoint_of(Api::kPlaces).prefer_key);
ASSERT_TRUE(endpoint_of(Api::kWebServices).prefer_key);
ASSERT_FALSE(endpoint_of(Api::kStreetViewPublish).prefer_key);
ASSERT_FALSE(endpoint_of(Api::kApiKeys).prefer_key);
ASSERT_EQ(endpoint_of(Api::kRoutes).base_url, "https://routes.googleapis.com");
}
TEST(maps, latlng_and_fieldmask_validation) {
ASSERT_TRUE(invalid([] { LatLng{91, 0}.validate(); }));
ASSERT_TRUE(invalid([] { LatLng{0, -181}.validate(); }));
ASSERT_EQ(kAmsterdam.to_string(), "52.3702157,4.8951679");
LatLng p = LatLng::parse("1.5,-2.25");
ASSERT_EQ(p.lat, 1.5);
ASSERT_EQ(p.lng, -2.25);
ASSERT_TRUE(invalid([] { LatLng::parse("abc"); }));
ASSERT_TRUE(invalid([] { FieldMask(""); }));
ASSERT_TRUE(invalid([] { FieldMask("*"); }));
ASSERT_TRUE(invalid([] { FieldMask("places.id,,places.name"); }));
ASSERT_TRUE(invalid([] { FieldMask("places.id;drop"); }));
ASSERT_TRUE(invalid([] { FieldMask(std::string(1025, 'a')); }));
ASSERT_EQ(FieldMask("places.id,places.displayName").str(), "places.id,places.displayName");
ASSERT_TRUE(FieldMask::all().is_all());
}
TEST(maps, query_encoding_and_row_check) {
Query q;
q.add("a b", "x&y=z");
ASSERT_EQ(q.encode(), "?a%20b=x%26y%3Dz");
Rig rig;
Places places(rig.client);
places.set_dry_run(true);
// An undeclared query parameter or body field is rejected before sending.
struct Probe : Places {
using Places::Places;
Json bad_query() const { return invoke(Call::kPlacesGet, {{"name", "places/x"}}, Query().add("nope", "1")); }
Json bad_field() const {
Json b = Json::object();
b.set("nope", Json(1));
return invoke(Call::kPlacesSearchText, {}, Query(), &b);
}
Json wrong_api() const { return invoke(Call::kRoutesCompute, {}, Query()); }
} probe(rig.client);
ASSERT_TRUE(invalid([&] { probe.bad_query(); }));
ASSERT_TRUE(invalid([&] { probe.bad_field(); }));
ASSERT_TRUE(invalid([&] { probe.wrong_api(); }));
ASSERT_TRUE(invalid([&] { Query().add("x", std::string(3000, 'a')); }));
}
TEST(maps, no_credential_is_loud_and_sends_nothing) {
Rig rig;
Places places(rig.client);
SearchTextRequest r;
r.text_query = "pizza";
ASSERT_TRUE(not_configured([&] { places.search_text(r, FieldMask("places.id")); }));
Geocoding geo(rig.client);
ASSERT_TRUE(not_configured([&] { geo.geocode("Dam 1 Amsterdam"); }));
ASSERT_TRUE(not_configured([&] { TimeZone(rig.client).lookup(kAmsterdam, 1700000000); }));
ASSERT_EQ(rig.mock->send_count(), static_cast<std::size_t>(0));
ASSERT_FALSE(Places(rig.client).configured());
}
TEST(maps, places_request_shapes) {
Rig rig;
Places places(rig.client);
places.set_dry_run(true);
SearchTextRequest r;
r.text_query = "pizza amsterdam";
r.page_size = 5;
r.open_now = true;
r.language_code = "nl";
Json d = places.search_text(r, FieldMask("places.id,places.displayName"));
ASSERT_EQ(d.find("method")->as_string(), "POST");
ASSERT_EQ(d.find("path")->as_string(), "/v1/places:searchText?fields=places.id%2Cplaces.displayName");
ASSERT_EQ(d.find("body")->find("textQuery")->as_string(), "pizza amsterdam");
ASSERT_EQ(d.find("body")->find("pageSize")->as_int(), 5);
ASSERT_TRUE(d.find("body")->find("openNow")->as_bool());
SearchNearbyRequest n;
n.restriction.center = kAmsterdam;
n.restriction.radius_meters = 500;
n.included_types = {"restaurant"};
n.max_result_count = 3;
Json nd = places.search_nearby(n, FieldMask("places.id"));
const Json* circle = nd.find("body")->find("locationRestriction")->find("circle");
ASSERT_EQ(circle->find("radius")->as_number(), 500.0);
ASSERT_EQ(circle->find("center")->find("latitude")->as_number(), 52.3702157);
Json g = places.get("ChIJabc", FieldMask("id,displayName"), "nl", "NL");
ASSERT_EQ(g.find("method")->as_string(), "GET");
ASSERT_EQ(g.find("path")->as_string(),
"/v1/places/ChIJabc?fields=id%2CdisplayName&languageCode=nl&regionCode=NL");
ASSERT_EQ(Places::resource_name("places/x"), "places/x");
AutocompleteRequest a;
a.input = "Dam";
a.session_token = "tok";
Json ad = places.autocomplete(a);
ASSERT_EQ(ad.find("path")->as_string(), "/v1/places:autocomplete");
ASSERT_EQ(ad.find("body")->find("sessionToken")->as_string(), "tok");
Json p = places.photo_uri("places/X/photos/Y_-z", 400, 0);
ASSERT_EQ(p.find("path")->as_string(), "/v1/places/X/photos/Y_-z/media?maxWidthPx=400&skipHttpRedirect=true");
}
TEST(maps, places_validation) {
Rig rig;
Places places(rig.client);
SearchTextRequest r;
ASSERT_TRUE(invalid([&] { places.search_text(r, FieldMask("places.id")); })); // empty query
r.text_query = "x";
r.page_size = 21;
ASSERT_TRUE(invalid([&] { places.search_text(r, FieldMask("places.id")); }));
r.page_size = 5;
r.min_rating = 6;
ASSERT_TRUE(invalid([&] { places.search_text(r, FieldMask("places.id")); }));
SearchNearbyRequest n;
ASSERT_TRUE(invalid([&] { places.search_nearby(n, FieldMask("places.id")); })); // no area
n.restriction.center = kAmsterdam;
n.restriction.radius_meters = 50001;
ASSERT_TRUE(invalid([&] { places.search_nearby(n, FieldMask("places.id")); }));
n.restriction.radius_meters = 100;
n.rank_preference = "BEST";
ASSERT_TRUE(invalid([&] { places.search_nearby(n, FieldMask("places.id")); }));
ASSERT_TRUE(invalid([&] { places.get("a/b/../c", FieldMask("id")); }));
ASSERT_TRUE(invalid([&] { places.photo_uri("places/x", 100, 100); }));
ASSERT_TRUE(invalid([&] { places.photo_uri("places/x/photos/y", 0, 0); }));
ASSERT_TRUE(invalid([&] { places.photo_uri("places/x/photos/y", 4801, 0); }));
AutocompleteRequest a;
ASSERT_TRUE(invalid([&] { places.autocomplete(a); }));
a.input = std::string(513, 'x');
ASSERT_TRUE(invalid([&] { places.autocomplete(a); }));
}
TEST(maps, place_parsing_is_tolerant) {
Json doc = Json::parse(
"{\"places\":[{\"id\":\"p1\",\"name\":\"places/p1\",\"displayName\":{\"text\":\"Cafe\"},"
"\"formattedAddress\":\"Dam 1\",\"location\":{\"latitude\":52.1,\"longitude\":4.2},"
"\"types\":[\"cafe\",\"food\"]},{}]}");
auto ps = Places::places_of(doc);
ASSERT_EQ(ps.size(), static_cast<std::size_t>(2));
ASSERT_EQ(ps[0].display_name, "Cafe");
ASSERT_EQ(ps[0].types.size(), static_cast<std::size_t>(2));
ASSERT_TRUE(ps[0].location.has_value());
ASSERT_FALSE(ps[1].location.has_value());
ASSERT_EQ(Places::places_of(Json::parse("{}")).size(), static_cast<std::size_t>(0));
}
TEST(maps, address_validation) {
Rig rig;
AddressValidation av(rig.client);
av.set_dry_run(true);
ValidateAddressRequest r;
ASSERT_TRUE(invalid([&] { av.validate(r); })); // no region, no lines
r.address.region_code = "NL";
r.address.address_lines = {"Dam 1", "1012 JS Amsterdam"};
Json d = av.validate(r);
ASSERT_EQ(d.find("path")->as_string(), "/v1:validateAddress");
ASSERT_EQ(d.find("body")->find("address")->find("regionCode")->as_string(), "NL");
ASSERT_EQ(d.find("body")->find("address")->find("addressLines")->as_array().size(), static_cast<std::size_t>(2));
r.enable_usps_cass = true;
ASSERT_TRUE(invalid([&] { av.validate(r); })); // CASS is US only
r.address.address_lines.assign(31, "x");
r.enable_usps_cass = false;
ASSERT_TRUE(invalid([&] { av.validate(r); }));
ASSERT_TRUE(invalid([&] { av.provide_feedback("MAYBE", "id"); }));
ASSERT_TRUE(invalid([&] { av.provide_feedback("UNUSED", ""); }));
Json f = av.provide_feedback("VALIDATED_VERSION_USED", "resp1");
ASSERT_EQ(f.find("path")->as_string(), "/v1:provideValidationFeedback");
AddressVerdict v = AddressVerdict::from_json(Json::parse(
"{\"responseId\":\"r\",\"result\":{\"verdict\":{\"addressComplete\":true,"
"\"validationGranularity\":\"PREMISE\"},\"address\":{\"formattedAddress\":\"Dam 1\"}}}"));
ASSERT_TRUE(v.address_complete);
ASSERT_EQ(v.formatted_address, "Dam 1");
}
TEST(maps, solar_pollen_air_area_shapes) {
Rig rig;
Solar solar(rig.client);
solar.set_dry_run(true);
Json s = solar.building_insights(kAmsterdam, "MEDIUM");
ASSERT_EQ(s.find("path")->as_string(),
"/v1/buildingInsights:findClosest?location.latitude=52.3702157&location.longitude=4.8951679&requiredQuality=MEDIUM");
ASSERT_TRUE(invalid([&] { solar.building_insights(kAmsterdam, "BEST"); }));
ASSERT_TRUE(invalid([&] { solar.data_layers(kAmsterdam, 1001); }));
ASSERT_TRUE(invalid([&] { solar.data_layers(kAmsterdam, 100, "NOPE"); }));
ASSERT_TRUE(invalid([&] { solar.data_layers(kAmsterdam, 100, "", "", 2.0); }));
ASSERT_EQ(solar.geotiff_path("abc"), "/v1/geoTiff:get?id=abc");
Pollen pollen(rig.client);
pollen.set_dry_run(true);
Json p = pollen.forecast(kAmsterdam, 3, "nl");
ASSERT_TRUE(p.find("path")->as_string().find("days=3") != std::string::npos);
ASSERT_TRUE(invalid([&] { pollen.forecast(kAmsterdam, 6); }));
ASSERT_TRUE(invalid([&] { pollen.forecast(kAmsterdam, 0); }));
ASSERT_EQ(pollen.heatmap_tile_path("GRASS_UPI", 3, 2, 5), "/v1/mapTypes/GRASS_UPI/heatmapTiles/3/2/5");
ASSERT_TRUE(invalid([&] { pollen.heatmap_tile_path("GRASS_UPI", 1, 2, 0); })); // x outside the grid
ASSERT_TRUE(invalid([&] { pollen.heatmap_tile_path("MOSS", 1, 0, 0); }));
ASSERT_TRUE(invalid([&] { pollen.heatmap_tile_path("TREE_UPI", 21, 0, 0); }));
AirQuality air(rig.client);
air.set_dry_run(true);
Json c = air.current(kAmsterdam, {"LOCAL_AQI"}, "nl");
ASSERT_EQ(c.find("path")->as_string(), "/v1/currentConditions:lookup");
ASSERT_EQ(c.find("body")->find("location")->find("latitude")->as_number(), 52.3702157);
ASSERT_EQ(c.find("body")->find("extraComputations")->as_array()[0].as_string(), "LOCAL_AQI");
ASSERT_TRUE(invalid([&] { air.current(kAmsterdam, {"FOO"}); }));
ASSERT_TRUE(invalid([&] { air.history(kAmsterdam, 721); }));
ASSERT_EQ(air.history(kAmsterdam, 24).find("body")->find("hours")->as_int(), 24);
ASSERT_TRUE(invalid([&] { air.forecast(kAmsterdam, ""); }));
ASSERT_EQ(air.forecast(kAmsterdam, "2026-10-26T12:00:00Z").find("path")->as_string(), "/v1/forecast:lookup");
AreaInsights area(rig.client);
area.set_dry_run(true);
InsightsFilter f;
ASSERT_TRUE(invalid([&] { area.compute({"INSIGHT_COUNT"}, f); })); // no area
f.circle_center = kAmsterdam;
f.circle_radius_meters = 1000;
f.included_types = {"restaurant"};
Json a = area.compute({"INSIGHT_COUNT"}, f);
ASSERT_EQ(a.find("path")->as_string(), "/v1:computeInsights");
ASSERT_EQ(a.find("body")->find("filter")->find("locationFilter")->find("circle")->find("radius")->as_int(), 1000);
ASSERT_TRUE(invalid([&] { area.compute({}, f); }));
ASSERT_TRUE(invalid([&] { area.compute({"INSIGHT_ALL"}, f); }));
f.region_place = "places/x";
ASSERT_TRUE(invalid([&] { area.compute({"INSIGHT_COUNT"}, f); })); // circle and region together
}
TEST(maps, routes_shapes_and_caps) {
Rig rig;
Routes routes(rig.client);
routes.set_dry_run(true);
ComputeRoutesRequest r;
ASSERT_TRUE(invalid([&] { routes.compute_routes(r, FieldMask("routes.duration")); })); // no waypoints
r.origin = Waypoint::at(kAmsterdam);
r.destination = Waypoint::of_address("Rotterdam Centraal");
r.travel_mode = "DRIVE";
r.routing_preference = "TRAFFIC_AWARE";
Json d = routes.compute_routes(r, FieldMask("routes.duration,routes.distanceMeters"));
ASSERT_EQ(d.find("path")->as_string(),
"/directions/v2:computeRoutes?fields=routes.duration%2Croutes.distanceMeters");
ASSERT_EQ(d.find("body")->find("origin")->find("location")->find("latLng")->find("latitude")->as_number(),
52.3702157);
ASSERT_EQ(d.find("body")->find("destination")->find("address")->as_string(), "Rotterdam Centraal");
r.travel_mode = "WALK"; // traffic preference is for DRIVE / TWO_WHEELER only
ASSERT_TRUE(invalid([&] { routes.compute_routes(r, FieldMask("routes.duration")); }));
r.routing_preference = "";
r.intermediates.assign(26, Waypoint::at(kAmsterdam));
ASSERT_TRUE(invalid([&] { routes.compute_routes(r, FieldMask("routes.duration")); }));
Waypoint two;
two.address = "a";
two.place_id = "b";
ASSERT_TRUE(invalid([&] { two.validate(); }));
RouteMatrixRequest m;
m.origins.assign(26, Waypoint::at(kAmsterdam));
m.destinations = {Waypoint::of_place("ChIJx")};
ASSERT_TRUE(invalid([&] { routes.compute_route_matrix(m, FieldMask("originIndex")); }));
m.origins.resize(2);
Json md = routes.compute_route_matrix(m, FieldMask("originIndex,destinationIndex,duration"));
ASSERT_EQ(md.find("path")->as_string(),
"/distanceMatrix/v2:computeRouteMatrix?fields=originIndex%2CdestinationIndex%2Cduration");
ASSERT_EQ(md.find("body")->find("origins")->as_array()[0].find("waypoint")->find("location") != nullptr, true);
ASSERT_EQ(md.find("body")->find("destinations")->as_array()[0].find("waypoint")->find("placeId")->as_string(), "ChIJx");
auto s = RouteSummary::first_of(Json::parse(
"{\"routes\":[{\"distanceMeters\":1234,\"duration\":\"456s\",\"polyline\":{\"encodedPolyline\":\"abc\"}}]}"));
ASSERT_TRUE(s.has_value());
ASSERT_EQ(s->distance_meters, 1234L);
ASSERT_EQ(s->duration_seconds, 456L);
ASSERT_FALSE(RouteSummary::first_of(Json::parse("{}")).has_value());
}
TEST(maps, web_services_shapes_and_status_mapping) {
Rig rig;
Geocoding geo(rig.client);
geo.set_dry_run(true);
ASSERT_TRUE(invalid([&] { geo.geocode("", ""); }));
geo.geocode("Dam 1, Amsterdam", "country:NL", "nl", "nl");
ASSERT_EQ(geo.raw(Query().add("address", "a b")).find("path")->as_string(), "/maps/api/geocode/json?address=a%20b");
ASSERT_TRUE(invalid([&] { geo.raw(Query().add("nope", "1")); }));
TimeZone tz(rig.client);
tz.set_dry_run(true);
ASSERT_TRUE(invalid([&] { tz.lookup(kAmsterdam, -1); }));
Elevation el(rig.client);
el.set_dry_run(true);
ASSERT_TRUE(invalid([&] { el.at({}); }));
ASSERT_TRUE(invalid([&] { el.along({kAmsterdam}, 5); }));
ASSERT_TRUE(invalid([&] { el.along({kAmsterdam, kAmsterdam}, 1); }));
ASSERT_TRUE(invalid([&] { el.at(std::vector<LatLng>(513, kAmsterdam)); }));
// Google answers HTTP 200 with a failure status: it must be loud.
struct S : MapsService {
using MapsService::MapsService;
static void check(const Json& d) { check_web_status(d, "maps"); }
};
S::check(Json::parse("{\"status\":\"OK\"}"));
S::check(Json::parse("{\"status\":\"ZERO_RESULTS\"}"));
S::check(Json::parse("{\"status\":\"DATA_NOT_AVAILABLE\"}"));
try {
S::check(Json::parse("{\"status\":\"REQUEST_DENIED\",\"error_message\":\"bad key\"}"));
FAIL("REQUEST_DENIED must throw");
} catch (const GoogleError& e) {
ASSERT_EQ(e.http_status(), 403);
ASSERT_EQ(e.status(), "REQUEST_DENIED");
ASSERT_TRUE(e.message().find("bad key") != std::string::npos);
}
ASSERT_THROW(S::check(Json::parse("{\"status\":\"OVER_QUERY_LIMIT\"}")), GoogleError);
ASSERT_THROW(S::check(Json::parse("{}")), GoogleError);
GeocodeResult g = GeocodeResult::from_json(Json::parse(
"{\"formatted_address\":\"Dam 1\",\"place_id\":\"p\",\"geometry\":{\"location_type\":\"ROOFTOP\","
"\"location\":{\"lat\":52.3,\"lng\":4.9}},\"types\":[\"street_address\"],\"partial_match\":true}"));
ASSERT_EQ(g.location_type, "ROOFTOP");
ASSERT_TRUE(g.partial_match);
ASSERT_EQ(g.location->lat, 52.3);
TimeZoneInfo ti;
ti.raw_offset = 3600;
ti.dst_offset = 3600;
ASSERT_EQ(ti.local_time(1000), 8200L);
}
TEST(maps, street_view_reads_and_explicit_writes) {
Rig rig;
StreetViewPublish sv(rig.client);
sv.set_dry_run(true);
ASSERT_EQ(sv.list_photos("INCLUDE_DOWNLOAD_URL", "placeId=ChIJx", 10).find("path")->as_string(),
"/v1/photos?view=INCLUDE_DOWNLOAD_URL&filter=placeId%3DChIJx&pageSize=10");
ASSERT_TRUE(invalid([&] { sv.list_photos("FULL"); }));
ASSERT_TRUE(invalid([&] { sv.list_photos("", "", 101); }));
Json b = sv.batch_get_photos({"a", "b"});
ASSERT_EQ(b.find("path")->as_string(), "/v1/photos:batchGet?photoIds=a&photoIds=b");
ASSERT_TRUE(invalid([&] { sv.batch_get_photos({}); }));
ASSERT_TRUE(invalid([&] { sv.batch_delete_photos({"a/b"}); }));
ASSERT_TRUE(invalid([&] { sv.batch_delete_photos(std::vector<std::string>(101, "a")); }));
ASSERT_EQ(sv.delete_photo("p1").find("method")->as_string(), "DELETE");
ASSERT_EQ(sv.delete_photo_sequence("s1").find("path")->as_string(), "/v1/photoSequence/s1");
ASSERT_TRUE(invalid([&] { sv.delete_photo(".."); }));
ASSERT_TRUE(invalid([&] { sv.create_photo(Json::object()); })); // uploadReference required
Json ph = Json::object();
Json ref = Json::object();
ref.set("uploadUrl", Json("https://x"));
ph.set("uploadReference", ref);
ASSERT_EQ(sv.create_photo(ph).find("path")->as_string(), "/v1/photo");
ASSERT_TRUE(invalid([&] { sv.update_photo("p1", ph, ""); }));
ASSERT_EQ(sv.update_photo("p1", Json::object(), "pose.heading").find("method")->as_string(), "PUT");
ASSERT_TRUE(invalid([&] { sv.create_photo_sequence(Json::object(), "AUDIO"); }));
// Real (non dry-run) writes stop at the credential check.
StreetViewPublish real(rig.client);
ASSERT_TRUE(not_configured([&] { real.delete_photo("p1"); }));
ASSERT_EQ(rig.mock->send_count(), static_cast<std::size_t>(0));
}
TEST(maps, key_handling) {
MapsKey none;
ASSERT_FALSE(none.present());
ASSERT_EQ(none.redacted(), "");
ASSERT_FALSE(none.make_client()->configured());
MapsKey good("AIzaSyA1234567890abcdefghijklmnopqrstuv");
ASSERT_TRUE(good.present());
ASSERT_TRUE(good.looks_like_maps_key());
ASSERT_EQ(good.redacted(), "AIza...stuv");
ASSERT_TRUE(good.make_client()->configured());
ASSERT_FALSE(MapsKey("AQ.Ab8RN6Ixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").looks_like_maps_key()); // Vertex express key
ASSERT_FALSE(MapsKey("short").looks_like_maps_key());
ASSERT_EQ(MapsKey("short").redacted(), "****");
KeyRestrictions k;
ASSERT_EQ(k.lint().size(), static_cast<std::size_t>(2)); // unrestricted: loud
k.allowed_referrers = {"https://*.example.com/*"};
k.api_services = {"places.googleapis.com", "geocoding-backend.googleapis.com"};
ASSERT_EQ(k.lint().size(), static_cast<std::size_t>(0));
Json j = k.to_json();
ASSERT_EQ(j.find("browserKeyRestrictions")->find("allowedReferrers")->as_array().size(), static_cast<std::size_t>(1));
ASSERT_EQ(j.find("apiTargets")->as_array()[1].find("service")->as_string(), "geocoding-backend.googleapis.com");
KeyRestrictions back = KeyRestrictions::from_json(j);
ASSERT_EQ(back.api_services.size(), static_cast<std::size_t>(2));
ASSERT_EQ(back.allowed_referrers[0], "https://*.example.com/*");
k.allowed_ips = {"1.2.3.4"};
ASSERT_TRUE(invalid([&] { k.validate(); })); // two application restriction kinds
k.allowed_ips.clear();
k.api_services = {"not-a-service"};
ASSERT_TRUE(invalid([&] { k.validate(); }));
KeyRestrictions open;
open.allowed_referrers = {"*"};
open.allowed_ips.clear();
ASSERT_EQ(open.lint().size(), static_cast<std::size_t>(2)); // wildcard referrer + no API restriction
Rig rig;
ApiKeys keys(rig.client);
keys.set_dry_run(true);
ASSERT_EQ(keys.list("my-proj", 10).find("path")->as_string(),
"/v2/projects/my-proj/locations/global/keys?pageSize=10");
ASSERT_TRUE(invalid([&] { keys.list("bad/proj"); }));
ASSERT_TRUE(invalid([&] { keys.get("keys/x"); }));
}
+148
View File
@@ -0,0 +1,148 @@
// Opt-in live checks for the Maps package (MOLO_LIVE_NET=1, GOOGLE_ACCESS_TOKEN,
// GOOGLE_CLOUD_PROJECT). Free and read-only: which Maps services are enabled
// on the project (Service Usage) and the API Keys listing. The per-request
// billed calls run only with MOLO_LIVE_PAID=1, at most ONE tiny request per
// API. A disabled API or a missing Maps key is reported loudly ("API NOT
// ENABLED" / "NO MAPS KEY"), never skipped silently. Nothing is created,
// changed or deleted. Replies are Google's own, never scripted.
#include <cstdlib>
#include <iostream>
#include "framework.h"
#include "clients/transports/http_transport.h"
#include "google/credentials.h"
#include "google/errors.h"
#include "google/maps/address_validation.h"
#include "google/maps/environment.h"
#include "google/maps/maps_key.h"
#include "google/maps/places.h"
#include "google/maps/routes.h"
#include "google/maps/street_view.h"
#include "google/maps/web_services.h"
#include "google/resource.h"
using namespace molo::google;
using namespace molo::google::maps;
using molo::clients::body::Json;
namespace {
bool ready() {
return std::getenv("MOLO_LIVE_NET") && !Credentials::env("GOOGLE_ACCESS_TOKEN").empty() &&
!Credentials::env("GOOGLE_CLOUD_PROJECT").empty();
}
bool paid() { return std::getenv("MOLO_LIVE_PAID") && std::string(std::getenv("MOLO_LIVE_PAID")) == "1"; }
// Maps key (classic AIza... only; a Vertex express key is not a Maps key) plus
// the OAuth credential, so each API gets the credential it accepts.
std::shared_ptr<GoogleClient> maps_client(bool& has_key) {
MapsKey key = MapsKey::from_env();
has_key = key.looks_like_maps_key();
std::shared_ptr<molo::clients::Auth> k = has_key ? Credentials::api_key(Credentials::env("GOOGLE_MAPS_API_KEY").empty()
? Credentials::env("GOOGLE_API_KEY")
: Credentials::env("GOOGLE_MAPS_API_KEY"))
: nullptr;
return std::make_shared<GoogleClient>(std::make_unique<molo::clients::transports::HttpTransport>(), k,
Credentials::oauth_from_env());
}
// One billed request. Success or a Google refusal that names why (API not
// enabled, key problem, quota) is reported; any other failure fails the test.
template <typename F>
void one(const char* what, F&& f) {
try {
f();
std::cout << " " << what << ": 200 OK\n";
} catch (const GoogleError& e) {
bool denied = e.http_status() == 403 || e.http_status() == 400 || e.http_status() == 401 ||
e.http_status() == 429 || e.status() == "REQUEST_DENIED";
std::cout << " " << what << ": " << e.http_status() << " " << e.status() << (denied ? " <-- API NOT ENABLED or credential refused: " : ": ")
<< e.message().substr(0, 200) << "\n";
ASSERT_TRUE(denied);
}
}
} // namespace
TEST(maps_live, enabled_services_and_keys_are_reported) {
if (!ready()) {
std::cout << "SKIP maps_live.enabled_services_and_keys_are_reported (set MOLO_LIVE_NET=1, "
"GOOGLE_ACCESS_TOKEN and GOOGLE_CLOUD_PROJECT)\n";
return;
}
bool has_key = false;
auto client = maps_client(has_key);
std::string project = Credentials::env("GOOGLE_CLOUD_PROJECT");
ServiceEndpoint usage = endpoints::custom("serviceusage", "https://serviceusage.googleapis.com/v1");
int enabled = 0;
for (const char* svc : {"places.googleapis.com", "places-backend.googleapis.com", "addressvalidation.googleapis.com",
"solar.googleapis.com", "pollen.googleapis.com", "airquality.googleapis.com",
"areainsights.googleapis.com", "routes.googleapis.com", "geocoding-backend.googleapis.com",
"timezone-backend.googleapis.com", "elevation-backend.googleapis.com",
"streetviewpublish.googleapis.com"}) {
Json s = client->get_json(usage, "/projects/" + project + "/services/" + svc);
const Json* st = s.find("state");
bool on = st && st->is_string() && st->as_string() == "ENABLED";
enabled += on ? 1 : 0;
std::cout << " " << svc << ": " << (on ? "ENABLED" : "API NOT ENABLED") << "\n";
}
std::cout << " maps services enabled: " << enabled << " of 12; classic Maps key present: "
<< (has_key ? "yes" : "NO MAPS KEY (Vertex express keys are not Maps keys)") << "\n";
ApiKeys keys(client);
try {
Json l = keys.list(project, 10);
auto all = ApiKeys::restrictions_of(l);
std::cout << " api keys listed: " << all.size() << "\n";
for (const auto& [name, r] : all)
for (const auto& f : r.lint()) std::cout << " key lint: " << f << "\n";
} catch (const GoogleError& e) {
std::cout << " apikeys.list: " << e.http_status() << " " << e.status() << " (API NOT ENABLED?) "
<< e.message().substr(0, 160) << "\n";
ASSERT_TRUE(e.http_status() == 403);
}
}
TEST(maps_live, one_billed_request_per_api) {
if (!ready() || !paid()) {
std::cout << "SKIP maps_live.one_billed_request_per_api (set MOLO_LIVE_NET=1 and MOLO_LIVE_PAID=1: "
"each Maps API bills per request)\n";
return;
}
bool has_key = false;
auto client = maps_client(has_key);
if (!has_key) std::cout << " NO MAPS KEY: key-only APIs (Geocoding, Time Zone, Elevation) are expected to be refused\n";
const LatLng here{52.3702157, 4.8951679};
one("places.searchText", [&] {
SearchTextRequest r;
r.text_query = "Dam Square";
r.page_size = 1;
Places(client).search_text(r, FieldMask("places.id"));
});
one("addressvalidation.validateAddress", [&] {
ValidateAddressRequest r;
r.address.region_code = "NL";
r.address.address_lines = {"Dam 1"};
AddressValidation(client).validate(r);
});
one("solar.findClosest", [&] { Solar(client).building_insights(here); });
one("pollen.forecast", [&] { Pollen(client).forecast(here, 1); });
one("airquality.currentConditions", [&] { AirQuality(client).current(here); });
one("areainsights.computeInsights", [&] {
InsightsFilter f;
f.circle_center = here;
f.circle_radius_meters = 200;
f.included_types = {"restaurant"};
AreaInsights(client).compute({"INSIGHT_COUNT"}, f);
});
one("routes.computeRoutes", [&] {
ComputeRoutesRequest r;
r.origin = Waypoint::at(here);
r.destination = Waypoint::at({52.0907374, 5.1214201});
r.travel_mode = "DRIVE";
Routes(client).compute_routes(r, FieldMask("routes.duration,routes.distanceMeters"));
});
one("geocoding", [&] { Geocoding(client).geocode("Dam 1, Amsterdam"); });
one("timezone", [&] { TimeZone(client).lookup(here, 1700000000); });
one("elevation", [&] { Elevation(client).at({here}); });
one("streetviewpublish.photos.list", [&] { StreetViewPublish(client).list_photos("", "", 1); });
}