cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / browser / geolocation / network_location_provider_unittest.cc
blob881ec68c9a90e57bfa52242163c762ff591020cf
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/json/json_reader.h"
6 #include "base/json/json_writer.h"
7 #include "base/memory/scoped_ptr.h"
8 #include "base/strings/string_number_conversions.h"
9 #include "base/strings/string_util.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/values.h"
13 #include "content/browser/geolocation/fake_access_token_store.h"
14 #include "content/browser/geolocation/location_arbitrator_impl.h"
15 #include "content/browser/geolocation/network_location_provider.h"
16 #include "content/browser/geolocation/wifi_data_provider.h"
17 #include "net/url_request/test_url_fetcher_factory.h"
18 #include "net/url_request/url_request_status.h"
19 #include "testing/gtest/include/gtest/gtest.h"
21 namespace content {
23 // Constants used in multiple tests.
24 const char kTestServerUrl[] = "https://www.geolocation.test/service";
25 const char kAccessTokenString[] = "accessToken";
27 // Using #define so we can easily paste this into various other strings.
28 #define REFERENCE_ACCESS_TOKEN "2:k7j3G6LaL6u_lafw:4iXOeOpTh1glSXe"
30 // Stops the specified (nested) message loop when the listener is called back.
31 class MessageLoopQuitListener {
32 public:
33 MessageLoopQuitListener()
34 : client_message_loop_(base::MessageLoop::current()),
35 updated_provider_(NULL) {
36 CHECK(client_message_loop_);
39 void OnLocationUpdate(const LocationProvider* provider,
40 const Geoposition& position) {
41 EXPECT_EQ(client_message_loop_, base::MessageLoop::current());
42 updated_provider_ = provider;
43 client_message_loop_->Quit();
46 base::MessageLoop* client_message_loop_;
47 const LocationProvider* updated_provider_;
50 // A mock implementation of WifiDataProvider for testing. Adapted from
51 // http://gears.googlecode.com/svn/trunk/gears/geolocation/geolocation_test.cc
52 class MockWifiDataProvider : public WifiDataProvider {
53 public:
54 // Factory method for use with WifiDataProvider::SetFactoryForTesting.
55 static WifiDataProvider* GetInstance() {
56 CHECK(instance_);
57 return instance_;
60 static MockWifiDataProvider* CreateInstance() {
61 CHECK(!instance_);
62 instance_ = new MockWifiDataProvider;
63 return instance_;
66 MockWifiDataProvider() : start_calls_(0), stop_calls_(0), got_data_(true) {}
68 // WifiDataProvider implementation.
69 void StartDataProvider() override { ++start_calls_; }
71 void StopDataProvider() override { ++stop_calls_; }
73 bool GetData(WifiData* data_out) override {
74 CHECK(data_out);
75 *data_out = data_;
76 return got_data_;
79 void SetData(const WifiData& new_data) {
80 got_data_ = true;
81 const bool differs = data_.DiffersSignificantly(new_data);
82 data_ = new_data;
83 if (differs)
84 this->RunCallbacks();
87 void set_got_data(bool got_data) { got_data_ = got_data; }
88 int start_calls_;
89 int stop_calls_;
91 private:
92 ~MockWifiDataProvider() override {
93 CHECK(this == instance_);
94 instance_ = NULL;
97 static MockWifiDataProvider* instance_;
99 WifiData data_;
100 bool got_data_;
102 DISALLOW_COPY_AND_ASSIGN(MockWifiDataProvider);
105 MockWifiDataProvider* MockWifiDataProvider::instance_ = NULL;
107 // Main test fixture
108 class GeolocationNetworkProviderTest : public testing::Test {
109 public:
110 virtual void SetUp() {
111 test_server_url_ = GURL(kTestServerUrl);
112 access_token_store_ = new FakeAccessTokenStore;
113 wifi_data_provider_ = MockWifiDataProvider::CreateInstance();
116 virtual void TearDown() { WifiDataProviderManager::ResetFactoryForTesting(); }
118 LocationProvider* CreateProvider(bool set_permission_granted) {
119 LocationProvider* provider = NewNetworkLocationProvider(
120 access_token_store_.get(),
121 NULL, // No URLContextGetter needed, as using test urlfecther factory.
122 test_server_url_,
123 access_token_store_->access_token_set_[test_server_url_]);
124 if (set_permission_granted)
125 provider->OnPermissionGranted();
126 return provider;
129 protected:
130 GeolocationNetworkProviderTest() {
131 // TODO(joth): Really these should be in SetUp, not here, but they take no
132 // effect on Mac OS Release builds if done there. I kid not. Figure out why.
133 WifiDataProviderManager::SetFactoryForTesting(
134 MockWifiDataProvider::GetInstance);
137 // Returns the current url fetcher (if any) and advances the id ready for the
138 // next test step.
139 net::TestURLFetcher* get_url_fetcher_and_advance_id() {
140 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(
141 NetworkLocationRequest::url_fetcher_id_for_tests);
142 if (fetcher)
143 ++NetworkLocationRequest::url_fetcher_id_for_tests;
144 return fetcher;
147 static int IndexToChannel(int index) { return index + 4; }
149 // Creates wifi data containing the specified number of access points, with
150 // some differentiating charactistics in each.
151 static WifiData CreateReferenceWifiScanData(int ap_count) {
152 WifiData data;
153 for (int i = 0; i < ap_count; ++i) {
154 AccessPointData ap;
155 ap.mac_address =
156 base::ASCIIToUTF16(base::StringPrintf("%02d-34-56-78-54-32", i));
157 ap.radio_signal_strength = ap_count - i;
158 ap.channel = IndexToChannel(i);
159 ap.signal_to_noise = i + 42;
160 ap.ssid = base::ASCIIToUTF16("Some nice+network|name\\");
161 data.access_point_data.insert(ap);
163 return data;
166 static void CreateReferenceWifiScanDataJson(
167 int ap_count, int start_index, base::ListValue* wifi_access_point_list) {
168 std::vector<std::string> wifi_data;
169 for (int i = 0; i < ap_count; ++i) {
170 base::DictionaryValue* ap = new base::DictionaryValue();
171 ap->SetString("macAddress", base::StringPrintf("%02d-34-56-78-54-32", i));
172 ap->SetInteger("signalStrength", start_index + ap_count - i);
173 ap->SetInteger("age", 0);
174 ap->SetInteger("channel", IndexToChannel(i));
175 ap->SetInteger("signalToNoiseRatio", i + 42);
176 wifi_access_point_list->Append(ap);
180 static Geoposition CreateReferencePosition(int id) {
181 Geoposition pos;
182 pos.latitude = id;
183 pos.longitude = -(id + 1);
184 pos.altitude = 2 * id;
185 pos.timestamp = base::Time::Now();
186 return pos;
189 static std::string PrettyJson(const base::Value& value) {
190 std::string pretty;
191 base::JSONWriter::WriteWithOptions(
192 &value, base::JSONWriter::OPTIONS_PRETTY_PRINT, &pretty);
193 return pretty;
196 static testing::AssertionResult JsonGetList(
197 const std::string& field,
198 const base::DictionaryValue& dict,
199 const base::ListValue** output_list) {
200 if (!dict.GetList(field, output_list))
201 return testing::AssertionFailure() << "Dictionary " << PrettyJson(dict)
202 << " is missing list field " << field;
203 return testing::AssertionSuccess();
206 static testing::AssertionResult JsonFieldEquals(
207 const std::string& field,
208 const base::DictionaryValue& expected,
209 const base::DictionaryValue& actual) {
210 const base::Value* expected_value;
211 const base::Value* actual_value;
212 if (!expected.Get(field, &expected_value))
213 return testing::AssertionFailure()
214 << "Expected dictionary " << PrettyJson(expected)
215 << " is missing field " << field;
216 if (!expected.Get(field, &actual_value))
217 return testing::AssertionFailure()
218 << "Actual dictionary " << PrettyJson(actual)
219 << " is missing field " << field;
220 if (!expected_value->Equals(actual_value))
221 return testing::AssertionFailure()
222 << "Field " << field << " mismatch: " << PrettyJson(*expected_value)
223 << " != " << PrettyJson(*actual_value);
224 return testing::AssertionSuccess();
227 static GURL UrlWithoutQuery(const GURL& url) {
228 url::Replacements<char> replacements;
229 replacements.ClearQuery();
230 return url.ReplaceComponents(replacements);
233 testing::AssertionResult IsTestServerUrl(const GURL& request_url) {
234 const GURL a(UrlWithoutQuery(test_server_url_));
235 const GURL b(UrlWithoutQuery(request_url));
236 if (a == b)
237 return testing::AssertionSuccess();
238 return testing::AssertionFailure() << a << " != " << b;
241 void CheckRequestIsValid(const net::TestURLFetcher& request,
242 int expected_routers,
243 int expected_wifi_aps,
244 int wifi_start_index,
245 const std::string& expected_access_token) {
246 const GURL& request_url = request.GetOriginalURL();
248 EXPECT_TRUE(IsTestServerUrl(request_url));
250 // Check to see that the api key is being appended for the default
251 // network provider url.
252 bool is_default_url = UrlWithoutQuery(request_url) ==
253 UrlWithoutQuery(LocationArbitratorImpl::DefaultNetworkProviderURL());
254 EXPECT_EQ(is_default_url, !request_url.query().empty());
256 const std::string& upload_data = request.upload_data();
257 ASSERT_FALSE(upload_data.empty());
258 std::string json_parse_error_msg;
259 scoped_ptr<base::Value> parsed_json(
260 base::JSONReader::ReadAndReturnError(
261 upload_data,
262 base::JSON_PARSE_RFC,
263 NULL,
264 &json_parse_error_msg));
265 EXPECT_TRUE(json_parse_error_msg.empty());
266 ASSERT_TRUE(parsed_json.get() != NULL);
268 const base::DictionaryValue* request_json;
269 ASSERT_TRUE(parsed_json->GetAsDictionary(&request_json));
271 if (!is_default_url) {
272 if (expected_access_token.empty())
273 ASSERT_FALSE(request_json->HasKey(kAccessTokenString));
274 else {
275 std::string access_token;
276 EXPECT_TRUE(request_json->GetString(kAccessTokenString, &access_token));
277 EXPECT_EQ(expected_access_token, access_token);
281 if (expected_wifi_aps) {
282 base::ListValue expected_wifi_aps_json;
283 CreateReferenceWifiScanDataJson(
284 expected_wifi_aps,
285 wifi_start_index,
286 &expected_wifi_aps_json);
287 EXPECT_EQ(size_t(expected_wifi_aps), expected_wifi_aps_json.GetSize());
289 const base::ListValue* wifi_aps_json;
290 ASSERT_TRUE(JsonGetList("wifiAccessPoints", *request_json,
291 &wifi_aps_json));
292 for (size_t i = 0; i < expected_wifi_aps_json.GetSize(); ++i ) {
293 const base::DictionaryValue* expected_json;
294 ASSERT_TRUE(expected_wifi_aps_json.GetDictionary(i, &expected_json));
295 const base::DictionaryValue* actual_json;
296 ASSERT_TRUE(wifi_aps_json->GetDictionary(i, &actual_json));
297 ASSERT_TRUE(JsonFieldEquals("macAddress", *expected_json,
298 *actual_json));
299 ASSERT_TRUE(JsonFieldEquals("signalStrength", *expected_json,
300 *actual_json));
301 ASSERT_TRUE(JsonFieldEquals("channel", *expected_json, *actual_json));
302 ASSERT_TRUE(JsonFieldEquals("signalToNoiseRatio", *expected_json,
303 *actual_json));
305 } else {
306 ASSERT_FALSE(request_json->HasKey("wifiAccessPoints"));
308 EXPECT_TRUE(request_url.is_valid());
311 GURL test_server_url_;
312 base::MessageLoop main_message_loop_;
313 scoped_refptr<FakeAccessTokenStore> access_token_store_;
314 net::TestURLFetcherFactory url_fetcher_factory_;
315 scoped_refptr<MockWifiDataProvider> wifi_data_provider_;
318 TEST_F(GeolocationNetworkProviderTest, CreateDestroy) {
319 // Test fixture members were SetUp correctly.
320 EXPECT_EQ(&main_message_loop_, base::MessageLoop::current());
321 scoped_ptr<LocationProvider> provider(CreateProvider(true));
322 EXPECT_TRUE(NULL != provider.get());
323 provider.reset();
324 SUCCEED();
327 TEST_F(GeolocationNetworkProviderTest, StartProvider) {
328 scoped_ptr<LocationProvider> provider(CreateProvider(true));
329 EXPECT_TRUE(provider->StartProvider(false));
330 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
331 ASSERT_TRUE(fetcher != NULL);
332 CheckRequestIsValid(*fetcher, 0, 0, 0, std::string());
335 TEST_F(GeolocationNetworkProviderTest, StartProviderDefaultUrl) {
336 test_server_url_ = LocationArbitratorImpl::DefaultNetworkProviderURL();
337 scoped_ptr<LocationProvider> provider(CreateProvider(true));
338 EXPECT_TRUE(provider->StartProvider(false));
339 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
340 ASSERT_TRUE(fetcher != NULL);
341 CheckRequestIsValid(*fetcher, 0, 0, 0, std::string());
344 TEST_F(GeolocationNetworkProviderTest, StartProviderLongRequest) {
345 scoped_ptr<LocationProvider> provider(CreateProvider(true));
346 EXPECT_TRUE(provider->StartProvider(false));
347 const int kFirstScanAps = 20;
348 wifi_data_provider_->SetData(CreateReferenceWifiScanData(kFirstScanAps));
349 main_message_loop_.RunUntilIdle();
350 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
351 ASSERT_TRUE(fetcher != NULL);
352 // The request url should have been shortened to less than 2048 characters
353 // in length by not including access points with the lowest signal strength
354 // in the request.
355 EXPECT_LT(fetcher->GetOriginalURL().spec().size(), size_t(2048));
356 CheckRequestIsValid(*fetcher, 0, 16, 4, std::string());
359 TEST_F(GeolocationNetworkProviderTest, MultipleWifiScansComplete) {
360 scoped_ptr<LocationProvider> provider(CreateProvider(true));
361 EXPECT_TRUE(provider->StartProvider(false));
363 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
364 ASSERT_TRUE(fetcher != NULL);
365 EXPECT_TRUE(IsTestServerUrl(fetcher->GetOriginalURL()));
367 // Complete the network request with bad position fix.
368 const char* kNoFixNetworkResponse =
370 " \"status\": \"ZERO_RESULTS\""
371 "}";
372 fetcher->set_url(test_server_url_);
373 fetcher->set_status(net::URLRequestStatus());
374 fetcher->set_response_code(200); // OK
375 fetcher->SetResponseString(kNoFixNetworkResponse);
376 fetcher->delegate()->OnURLFetchComplete(fetcher);
378 Geoposition position;
379 provider->GetPosition(&position);
380 EXPECT_FALSE(position.Validate());
382 // Now wifi data arrives -- SetData will notify listeners.
383 const int kFirstScanAps = 6;
384 wifi_data_provider_->SetData(CreateReferenceWifiScanData(kFirstScanAps));
385 main_message_loop_.RunUntilIdle();
386 fetcher = get_url_fetcher_and_advance_id();
387 ASSERT_TRUE(fetcher != NULL);
388 // The request should have the wifi data.
389 CheckRequestIsValid(*fetcher, 0, kFirstScanAps, 0, std::string());
391 // Send a reply with good position fix.
392 const char* kReferenceNetworkResponse =
394 " \"accessToken\": \"" REFERENCE_ACCESS_TOKEN "\","
395 " \"accuracy\": 1200.4,"
396 " \"location\": {"
397 " \"lat\": 51.0,"
398 " \"lng\": -0.1"
399 " }"
400 "}";
401 fetcher->set_url(test_server_url_);
402 fetcher->set_status(net::URLRequestStatus());
403 fetcher->set_response_code(200); // OK
404 fetcher->SetResponseString(kReferenceNetworkResponse);
405 fetcher->delegate()->OnURLFetchComplete(fetcher);
407 provider->GetPosition(&position);
408 EXPECT_EQ(51.0, position.latitude);
409 EXPECT_EQ(-0.1, position.longitude);
410 EXPECT_EQ(1200.4, position.accuracy);
411 EXPECT_FALSE(position.timestamp.is_null());
412 EXPECT_TRUE(position.Validate());
414 // Token should be in the store.
415 EXPECT_EQ(base::UTF8ToUTF16(REFERENCE_ACCESS_TOKEN),
416 access_token_store_->access_token_set_[test_server_url_]);
418 // Wifi updated again, with one less AP. This is 'close enough' to the
419 // previous scan, so no new request made.
420 const int kSecondScanAps = kFirstScanAps - 1;
421 wifi_data_provider_->SetData(CreateReferenceWifiScanData(kSecondScanAps));
422 main_message_loop_.RunUntilIdle();
423 fetcher = get_url_fetcher_and_advance_id();
424 EXPECT_FALSE(fetcher);
426 provider->GetPosition(&position);
427 EXPECT_EQ(51.0, position.latitude);
428 EXPECT_EQ(-0.1, position.longitude);
429 EXPECT_TRUE(position.Validate());
431 // Now a third scan with more than twice the original amount -> new request.
432 const int kThirdScanAps = kFirstScanAps * 2 + 1;
433 wifi_data_provider_->SetData(CreateReferenceWifiScanData(kThirdScanAps));
434 main_message_loop_.RunUntilIdle();
435 fetcher = get_url_fetcher_and_advance_id();
436 EXPECT_TRUE(fetcher);
437 CheckRequestIsValid(*fetcher, 0, kThirdScanAps, 0, REFERENCE_ACCESS_TOKEN);
438 // ...reply with a network error.
440 fetcher->set_url(test_server_url_);
441 fetcher->set_status(net::URLRequestStatus(net::URLRequestStatus::FAILED, -1));
442 fetcher->set_response_code(200); // should be ignored
443 fetcher->SetResponseString(std::string());
444 fetcher->delegate()->OnURLFetchComplete(fetcher);
446 // Error means we now no longer have a fix.
447 provider->GetPosition(&position);
448 EXPECT_FALSE(position.Validate());
450 // Wifi scan returns to original set: should be serviced from cache.
451 wifi_data_provider_->SetData(CreateReferenceWifiScanData(kFirstScanAps));
452 main_message_loop_.RunUntilIdle();
453 EXPECT_FALSE(get_url_fetcher_and_advance_id()); // No new request created.
455 provider->GetPosition(&position);
456 EXPECT_EQ(51.0, position.latitude);
457 EXPECT_EQ(-0.1, position.longitude);
458 EXPECT_TRUE(position.Validate());
461 TEST_F(GeolocationNetworkProviderTest, NoRequestOnStartupUntilWifiData) {
462 MessageLoopQuitListener listener;
463 wifi_data_provider_->set_got_data(false);
464 scoped_ptr<LocationProvider> provider(CreateProvider(true));
465 EXPECT_TRUE(provider->StartProvider(false));
467 provider->SetUpdateCallback(base::Bind(
468 &MessageLoopQuitListener::OnLocationUpdate, base::Unretained(&listener)));
470 main_message_loop_.RunUntilIdle();
471 EXPECT_FALSE(get_url_fetcher_and_advance_id())
472 << "Network request should not be created right away on startup when "
473 "wifi data has not yet arrived";
475 wifi_data_provider_->SetData(CreateReferenceWifiScanData(1));
476 main_message_loop_.RunUntilIdle();
477 EXPECT_TRUE(get_url_fetcher_and_advance_id());
480 TEST_F(GeolocationNetworkProviderTest, NewDataReplacesExistingNetworkRequest) {
481 // Send initial request with empty data
482 scoped_ptr<LocationProvider> provider(CreateProvider(true));
483 EXPECT_TRUE(provider->StartProvider(false));
484 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
485 EXPECT_TRUE(fetcher);
487 // Now wifi data arrives; new request should be sent.
488 wifi_data_provider_->SetData(CreateReferenceWifiScanData(4));
489 main_message_loop_.RunUntilIdle();
490 fetcher = get_url_fetcher_and_advance_id();
491 EXPECT_TRUE(fetcher);
494 TEST_F(GeolocationNetworkProviderTest, NetworkRequestDeferredForPermission) {
495 scoped_ptr<LocationProvider> provider(CreateProvider(false));
496 EXPECT_TRUE(provider->StartProvider(false));
497 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
498 EXPECT_FALSE(fetcher);
499 provider->OnPermissionGranted();
501 fetcher = get_url_fetcher_and_advance_id();
502 ASSERT_TRUE(fetcher != NULL);
504 EXPECT_TRUE(IsTestServerUrl(fetcher->GetOriginalURL()));
507 TEST_F(GeolocationNetworkProviderTest,
508 NetworkRequestWithWifiDataDeferredForPermission) {
509 access_token_store_->access_token_set_[test_server_url_] =
510 base::UTF8ToUTF16(REFERENCE_ACCESS_TOKEN);
511 scoped_ptr<LocationProvider> provider(CreateProvider(false));
512 EXPECT_TRUE(provider->StartProvider(false));
513 net::TestURLFetcher* fetcher = get_url_fetcher_and_advance_id();
514 EXPECT_FALSE(fetcher);
516 static const int kScanCount = 4;
517 wifi_data_provider_->SetData(CreateReferenceWifiScanData(kScanCount));
518 main_message_loop_.RunUntilIdle();
520 fetcher = get_url_fetcher_and_advance_id();
521 EXPECT_FALSE(fetcher);
523 provider->OnPermissionGranted();
525 fetcher = get_url_fetcher_and_advance_id();
526 ASSERT_TRUE(fetcher != NULL);
528 CheckRequestIsValid(*fetcher, 0, kScanCount, 0, REFERENCE_ACCESS_TOKEN);
531 TEST_F(GeolocationNetworkProviderTest, NetworkPositionCache) {
532 NetworkLocationProvider::PositionCache cache;
534 const int kCacheSize = NetworkLocationProvider::PositionCache::kMaximumSize;
535 for (int i = 1; i < kCacheSize * 2 + 1; ++i) {
536 Geoposition pos = CreateReferencePosition(i);
537 bool ret = cache.CachePosition(CreateReferenceWifiScanData(i), pos);
538 EXPECT_TRUE(ret) << i;
539 const Geoposition* item =
540 cache.FindPosition(CreateReferenceWifiScanData(i));
541 ASSERT_TRUE(item) << i;
542 EXPECT_EQ(pos.latitude, item->latitude) << i;
543 EXPECT_EQ(pos.longitude, item->longitude) << i;
544 if (i <= kCacheSize) {
545 // Nothing should have spilled yet; check oldest item is still there.
546 EXPECT_TRUE(cache.FindPosition(CreateReferenceWifiScanData(1)));
547 } else {
548 const int evicted = i - kCacheSize;
549 EXPECT_FALSE(cache.FindPosition(CreateReferenceWifiScanData(evicted)));
550 EXPECT_TRUE(cache.FindPosition(CreateReferenceWifiScanData(evicted + 1)));
555 } // namespace content