Give names to all utility processes.
[chromium-blink-merge.git] / components / search_provider_logos / logo_tracker_unittest.cc
blob13b105ede4d808ed8330c3ed7a5e70c2ffb17efc
1 // Copyright 2014 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 "components/search_provider_logos/logo_tracker.h"
7 #include <vector>
9 #include "base/base64.h"
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/files/file_path.h"
13 #include "base/json/json_writer.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/run_loop.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/test/simple_test_clock.h"
20 #include "base/time/time.h"
21 #include "base/values.h"
22 #include "components/search_provider_logos/google_logo_api.h"
23 #include "net/base/url_util.h"
24 #include "net/http/http_response_headers.h"
25 #include "net/http/http_status_code.h"
26 #include "net/url_request/test_url_fetcher_factory.h"
27 #include "net/url_request/url_request_status.h"
28 #include "net/url_request/url_request_test_util.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31 #include "ui/gfx/image/image.h"
33 using ::testing::_;
34 using ::testing::AnyNumber;
35 using ::testing::AtMost;
36 using ::testing::InSequence;
37 using ::testing::Invoke;
38 using ::testing::Mock;
39 using ::testing::NiceMock;
40 using ::testing::Return;
42 namespace search_provider_logos {
44 namespace {
46 bool AreImagesSameSize(const SkBitmap& bitmap1, const SkBitmap& bitmap2) {
47 return bitmap1.width() == bitmap2.width() &&
48 bitmap1.height() == bitmap2.height();
51 scoped_refptr<base::RefCountedString> EncodeBitmapAsPNG(
52 const SkBitmap& bitmap) {
53 scoped_refptr<base::RefCountedMemory> png_bytes =
54 gfx::Image::CreateFrom1xBitmap(bitmap).As1xPNGBytes();
55 scoped_refptr<base::RefCountedString> str = new base::RefCountedString();
56 str->data().assign(png_bytes->front_as<char>(), png_bytes->size());
57 return str;
60 std::string EncodeBitmapAsPNGBase64(const SkBitmap& bitmap) {
61 scoped_refptr<base::RefCountedString> png_bytes = EncodeBitmapAsPNG(bitmap);
62 std::string encoded_image_base64;
63 base::Base64Encode(png_bytes->data(), &encoded_image_base64);
64 return encoded_image_base64;
67 SkBitmap MakeBitmap(int width, int height) {
68 SkBitmap bitmap;
69 bitmap.allocN32Pixels(width, height);
70 bitmap.eraseColor(SK_ColorBLUE);
71 return bitmap;
74 EncodedLogo EncodeLogo(const Logo& logo) {
75 EncodedLogo encoded_logo;
76 encoded_logo.encoded_image = EncodeBitmapAsPNG(logo.image);
77 encoded_logo.metadata = logo.metadata;
78 return encoded_logo;
81 Logo DecodeLogo(const EncodedLogo& encoded_logo) {
82 Logo logo;
83 logo.image = gfx::Image::CreateFrom1xPNGBytes(
84 encoded_logo.encoded_image->front(),
85 encoded_logo.encoded_image->size()).AsBitmap();
86 logo.metadata = encoded_logo.metadata;
87 return logo;
90 Logo GetSampleLogo(const GURL& logo_url, base::Time response_time) {
91 Logo logo;
92 logo.image = MakeBitmap(2, 5);
93 logo.metadata.can_show_after_expiration = false;
94 logo.metadata.expiration_time =
95 response_time + base::TimeDelta::FromHours(19);
96 logo.metadata.fingerprint = "8bc33a80";
97 logo.metadata.source_url = logo_url.spec();
98 logo.metadata.on_click_url = "http://www.google.com/search?q=potato";
99 logo.metadata.alt_text = "A logo about potatoes";
100 logo.metadata.animated_url = "http://www.google.com/logos/doodle.png";
101 logo.metadata.mime_type = "image/png";
102 return logo;
105 Logo GetSampleLogo2(const GURL& logo_url, base::Time response_time) {
106 Logo logo;
107 logo.image = MakeBitmap(4, 3);
108 logo.metadata.can_show_after_expiration = true;
109 logo.metadata.expiration_time = base::Time();
110 logo.metadata.fingerprint = "71082741021409127";
111 logo.metadata.source_url = logo_url.spec();
112 logo.metadata.on_click_url = "http://example.com/page25";
113 logo.metadata.alt_text = "The logo for example.com";
114 logo.metadata.mime_type = "image/png";
115 return logo;
118 std::string MakeServerResponse(
119 const SkBitmap& image,
120 const std::string& on_click_url,
121 const std::string& alt_text,
122 const std::string& animated_url,
123 const std::string& mime_type,
124 const std::string& fingerprint,
125 base::TimeDelta time_to_live) {
126 base::DictionaryValue dict;
127 if (!image.isNull()) {
128 dict.SetString("update.logo.data", EncodeBitmapAsPNGBase64(image));
131 dict.SetString("update.logo.target", on_click_url);
132 dict.SetString("update.logo.alt", alt_text);
133 if (!animated_url.empty()) {
134 dict.SetString("update.logo.url", animated_url);
136 dict.SetString("update.logo.mime_type", mime_type);
137 dict.SetString("update.logo.fingerprint", fingerprint);
138 if (time_to_live.ToInternalValue() != 0)
139 dict.SetInteger("update.logo.time_to_live",
140 static_cast<int>(time_to_live.InMilliseconds()));
142 std::string output;
143 base::JSONWriter::Write(&dict, &output);
144 return output;
147 std::string MakeServerResponse(const Logo& logo, base::TimeDelta time_to_live) {
148 return MakeServerResponse(logo.image,
149 logo.metadata.on_click_url,
150 logo.metadata.alt_text,
151 logo.metadata.animated_url,
152 logo.metadata.mime_type,
153 logo.metadata.fingerprint,
154 time_to_live);
157 void ExpectLogosEqual(const Logo* expected_logo,
158 const Logo* actual_logo) {
159 if (!expected_logo) {
160 ASSERT_FALSE(actual_logo);
161 return;
163 ASSERT_TRUE(actual_logo);
164 EXPECT_TRUE(AreImagesSameSize(expected_logo->image, actual_logo->image));
165 EXPECT_EQ(expected_logo->metadata.on_click_url,
166 actual_logo->metadata.on_click_url);
167 EXPECT_EQ(expected_logo->metadata.source_url,
168 actual_logo->metadata.source_url);
169 EXPECT_EQ(expected_logo->metadata.animated_url,
170 actual_logo->metadata.animated_url);
171 EXPECT_EQ(expected_logo->metadata.alt_text,
172 actual_logo->metadata.alt_text);
173 EXPECT_EQ(expected_logo->metadata.mime_type,
174 actual_logo->metadata.mime_type);
175 EXPECT_EQ(expected_logo->metadata.fingerprint,
176 actual_logo->metadata.fingerprint);
177 EXPECT_EQ(expected_logo->metadata.can_show_after_expiration,
178 actual_logo->metadata.can_show_after_expiration);
181 void ExpectLogosEqual(const Logo* expected_logo,
182 const EncodedLogo* actual_encoded_logo) {
183 Logo actual_logo;
184 if (actual_encoded_logo)
185 actual_logo = DecodeLogo(*actual_encoded_logo);
186 ExpectLogosEqual(expected_logo, actual_encoded_logo ? &actual_logo : NULL);
189 ACTION_P(ExpectLogosEqualAction, expected_logo) {
190 ExpectLogosEqual(expected_logo, arg0);
193 class MockLogoCache : public LogoCache {
194 public:
195 MockLogoCache() : LogoCache(base::FilePath()) {
196 // Delegate actions to the *Internal() methods by default.
197 ON_CALL(*this, UpdateCachedLogoMetadata(_)).WillByDefault(
198 Invoke(this, &MockLogoCache::UpdateCachedLogoMetadataInternal));
199 ON_CALL(*this, GetCachedLogoMetadata()).WillByDefault(
200 Invoke(this, &MockLogoCache::GetCachedLogoMetadataInternal));
201 ON_CALL(*this, SetCachedLogo(_))
202 .WillByDefault(Invoke(this, &MockLogoCache::SetCachedLogoInternal));
205 MOCK_METHOD1(UpdateCachedLogoMetadata, void(const LogoMetadata& metadata));
206 MOCK_METHOD0(GetCachedLogoMetadata, const LogoMetadata*());
207 MOCK_METHOD1(SetCachedLogo, void(const EncodedLogo* logo));
208 // GetCachedLogo() can't be mocked since it returns a scoped_ptr, which is
209 // non-copyable. Instead create a method that's pinged when GetCachedLogo() is
210 // called.
211 MOCK_METHOD0(OnGetCachedLogo, void());
213 void EncodeAndSetCachedLogo(const Logo& logo) {
214 EncodedLogo encoded_logo = EncodeLogo(logo);
215 SetCachedLogo(&encoded_logo);
218 void ExpectSetCachedLogo(const Logo* expected_logo) {
219 Mock::VerifyAndClearExpectations(this);
220 EXPECT_CALL(*this, SetCachedLogo(_))
221 .WillOnce(ExpectLogosEqualAction(expected_logo));
224 void UpdateCachedLogoMetadataInternal(const LogoMetadata& metadata) {
225 metadata_.reset(new LogoMetadata(metadata));
228 virtual const LogoMetadata* GetCachedLogoMetadataInternal() {
229 return metadata_.get();
232 virtual void SetCachedLogoInternal(const EncodedLogo* logo) {
233 logo_.reset(logo ? new EncodedLogo(*logo) : NULL);
234 metadata_.reset(logo ? new LogoMetadata(logo->metadata) : NULL);
237 virtual scoped_ptr<EncodedLogo> GetCachedLogo() override {
238 OnGetCachedLogo();
239 return make_scoped_ptr(logo_ ? new EncodedLogo(*logo_) : NULL);
242 private:
243 scoped_ptr<LogoMetadata> metadata_;
244 scoped_ptr<EncodedLogo> logo_;
247 class MockLogoObserver : public LogoObserver {
248 public:
249 virtual ~MockLogoObserver() {}
251 void ExpectNoLogo() {
252 Mock::VerifyAndClearExpectations(this);
253 EXPECT_CALL(*this, OnLogoAvailable(_, _)).Times(0);
254 EXPECT_CALL(*this, OnObserverRemoved()).Times(1);
257 void ExpectCachedLogo(const Logo* expected_cached_logo) {
258 Mock::VerifyAndClearExpectations(this);
259 EXPECT_CALL(*this, OnLogoAvailable(_, true))
260 .WillOnce(ExpectLogosEqualAction(expected_cached_logo));
261 EXPECT_CALL(*this, OnLogoAvailable(_, false)).Times(0);
262 EXPECT_CALL(*this, OnObserverRemoved()).Times(1);
265 void ExpectFreshLogo(const Logo* expected_fresh_logo) {
266 Mock::VerifyAndClearExpectations(this);
267 EXPECT_CALL(*this, OnLogoAvailable(_, true)).Times(0);
268 EXPECT_CALL(*this, OnLogoAvailable(NULL, true));
269 EXPECT_CALL(*this, OnLogoAvailable(_, false))
270 .WillOnce(ExpectLogosEqualAction(expected_fresh_logo));
271 EXPECT_CALL(*this, OnObserverRemoved()).Times(1);
274 void ExpectCachedAndFreshLogos(const Logo* expected_cached_logo,
275 const Logo* expected_fresh_logo) {
276 Mock::VerifyAndClearExpectations(this);
277 InSequence dummy;
278 EXPECT_CALL(*this, OnLogoAvailable(_, true))
279 .WillOnce(ExpectLogosEqualAction(expected_cached_logo));
280 EXPECT_CALL(*this, OnLogoAvailable(_, false))
281 .WillOnce(ExpectLogosEqualAction(expected_fresh_logo));
282 EXPECT_CALL(*this, OnObserverRemoved()).Times(1);
285 MOCK_METHOD2(OnLogoAvailable, void(const Logo*, bool));
286 MOCK_METHOD0(OnObserverRemoved, void());
289 class TestLogoDelegate : public LogoDelegate {
290 public:
291 TestLogoDelegate() {}
292 ~TestLogoDelegate() override {}
294 void DecodeUntrustedImage(
295 const scoped_refptr<base::RefCountedString>& encoded_image,
296 base::Callback<void(const SkBitmap&)> image_decoded_callback) override {
297 SkBitmap bitmap =
298 gfx::Image::CreateFrom1xPNGBytes(encoded_image->front(),
299 encoded_image->size()).AsBitmap();
300 base::MessageLoopProxy::current()->PostTask(
301 FROM_HERE, base::Bind(image_decoded_callback, bitmap));
305 class LogoTrackerTest : public ::testing::Test {
306 protected:
307 LogoTrackerTest()
308 : message_loop_(new base::MessageLoop()),
309 logo_url_("https://google.com/doodleoftheday?size=hp"),
310 test_clock_(new base::SimpleTestClock()),
311 logo_cache_(new NiceMock<MockLogoCache>()),
312 fake_url_fetcher_factory_(NULL) {
313 test_clock_->SetNow(base::Time::FromJsTime(GG_INT64_C(1388686828000)));
314 logo_tracker_ = new LogoTracker(
315 base::FilePath(),
316 base::MessageLoopProxy::current(),
317 base::MessageLoopProxy::current(),
318 new net::TestURLRequestContextGetter(base::MessageLoopProxy::current()),
319 scoped_ptr<LogoDelegate>(new TestLogoDelegate()));
320 logo_tracker_->SetServerAPI(logo_url_,
321 base::Bind(&GoogleParseLogoResponse),
322 base::Bind(&GoogleAppendFingerprintToLogoURL));
323 logo_tracker_->SetClockForTests(scoped_ptr<base::Clock>(test_clock_));
324 logo_tracker_->SetLogoCacheForTests(scoped_ptr<LogoCache>(logo_cache_));
327 virtual void TearDown() {
328 // logo_tracker_ owns logo_cache_, which gets destructed on the file thread
329 // after logo_tracker_'s destruction. Ensure that logo_cache_ is actually
330 // destructed before the test ends to make gmock happy.
331 delete logo_tracker_;
332 message_loop_->RunUntilIdle();
335 // Returns the response that the server would send for the given logo.
336 std::string ServerResponse(const Logo& logo) const;
338 // Sets the response to be returned when the LogoTracker fetches the logo.
339 void SetServerResponse(const std::string& response,
340 net::URLRequestStatus::Status request_status =
341 net::URLRequestStatus::SUCCESS,
342 net::HttpStatusCode response_code = net::HTTP_OK);
344 // Sets the response to be returned when the LogoTracker fetches the logo and
345 // provides the given fingerprint.
346 void SetServerResponseWhenFingerprint(
347 const std::string& fingerprint,
348 const std::string& response_when_fingerprint,
349 net::URLRequestStatus::Status request_status =
350 net::URLRequestStatus::SUCCESS,
351 net::HttpStatusCode response_code = net::HTTP_OK);
353 // Calls logo_tracker_->GetLogo() with listener_ and waits for the
354 // asynchronous response(s).
355 void GetLogo();
357 scoped_ptr<base::MessageLoop> message_loop_;
358 GURL logo_url_;
359 base::SimpleTestClock* test_clock_;
360 NiceMock<MockLogoCache>* logo_cache_;
361 net::FakeURLFetcherFactory fake_url_fetcher_factory_;
362 LogoTracker* logo_tracker_;
363 NiceMock<MockLogoObserver> observer_;
366 std::string LogoTrackerTest::ServerResponse(const Logo& logo) const {
367 base::TimeDelta time_to_live;
368 if (!logo.metadata.expiration_time.is_null())
369 time_to_live = logo.metadata.expiration_time - test_clock_->Now();
370 return MakeServerResponse(logo, time_to_live);
373 void LogoTrackerTest::SetServerResponse(
374 const std::string& response,
375 net::URLRequestStatus::Status request_status,
376 net::HttpStatusCode response_code) {
377 fake_url_fetcher_factory_.SetFakeResponse(
378 logo_url_, response, response_code, request_status);
381 void LogoTrackerTest::SetServerResponseWhenFingerprint(
382 const std::string& fingerprint,
383 const std::string& response_when_fingerprint,
384 net::URLRequestStatus::Status request_status,
385 net::HttpStatusCode response_code) {
386 GURL url_with_fp = GoogleAppendFingerprintToLogoURL(logo_url_, fingerprint);
387 fake_url_fetcher_factory_.SetFakeResponse(
388 url_with_fp, response_when_fingerprint, response_code, request_status);
391 void LogoTrackerTest::GetLogo() {
392 logo_tracker_->GetLogo(&observer_);
393 base::RunLoop().RunUntilIdle();
396 // Tests -----------------------------------------------------------------------
398 TEST_F(LogoTrackerTest, FingerprintURLHasColon) {
399 GURL url_with_fp = GoogleAppendFingerprintToLogoURL(
400 GURL("http://logourl.com/path"), "abc123");
401 EXPECT_EQ("http://logourl.com/path?async=es_dfp:abc123", url_with_fp.spec());
403 url_with_fp = GoogleAppendFingerprintToLogoURL(
404 GURL("http://logourl.com/?a=b"), "cafe0");
405 EXPECT_EQ("http://logourl.com/?a=b&async=es_dfp:cafe0", url_with_fp.spec());
408 TEST_F(LogoTrackerTest, DownloadAndCacheLogo) {
409 Logo logo = GetSampleLogo(logo_url_, test_clock_->Now());
410 SetServerResponse(ServerResponse(logo));
411 logo_cache_->ExpectSetCachedLogo(&logo);
412 observer_.ExpectFreshLogo(&logo);
413 GetLogo();
416 TEST_F(LogoTrackerTest, EmptyCacheAndFailedDownload) {
417 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
418 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
419 EXPECT_CALL(*logo_cache_, SetCachedLogo(NULL)).Times(AnyNumber());
421 SetServerResponse("server is borked");
422 observer_.ExpectCachedLogo(NULL);
423 GetLogo();
425 SetServerResponse("", net::URLRequestStatus::FAILED, net::HTTP_OK);
426 observer_.ExpectCachedLogo(NULL);
427 GetLogo();
429 SetServerResponse("", net::URLRequestStatus::SUCCESS, net::HTTP_BAD_GATEWAY);
430 observer_.ExpectCachedLogo(NULL);
431 GetLogo();
434 TEST_F(LogoTrackerTest, AcceptMinimalLogoResponse) {
435 Logo logo;
436 logo.image = MakeBitmap(1, 2);
437 logo.metadata.source_url = logo_url_.spec();
438 logo.metadata.can_show_after_expiration = true;
439 logo.metadata.mime_type = "image/png";
441 std::string response = ")]}' {\"update\":{\"logo\":{\"data\":\"" +
442 EncodeBitmapAsPNGBase64(logo.image) +
443 "\",\"mime_type\":\"image/png\"}}}";
445 SetServerResponse(response);
446 observer_.ExpectFreshLogo(&logo);
447 GetLogo();
450 TEST_F(LogoTrackerTest, ReturnCachedLogo) {
451 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
452 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
453 SetServerResponseWhenFingerprint(cached_logo.metadata.fingerprint,
455 net::URLRequestStatus::FAILED,
456 net::HTTP_OK);
458 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
459 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
460 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
461 observer_.ExpectCachedLogo(&cached_logo);
462 GetLogo();
465 TEST_F(LogoTrackerTest, ValidateCachedLogoFingerprint) {
466 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
467 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
469 Logo fresh_logo = cached_logo;
470 fresh_logo.image.reset();
471 fresh_logo.metadata.expiration_time =
472 test_clock_->Now() + base::TimeDelta::FromDays(8);
473 SetServerResponseWhenFingerprint(fresh_logo.metadata.fingerprint,
474 ServerResponse(fresh_logo));
476 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(1);
477 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
478 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
479 observer_.ExpectCachedLogo(&cached_logo);
481 GetLogo();
483 EXPECT_TRUE(logo_cache_->GetCachedLogoMetadata() != NULL);
484 EXPECT_EQ(logo_cache_->GetCachedLogoMetadata()->expiration_time,
485 fresh_logo.metadata.expiration_time);
488 TEST_F(LogoTrackerTest, UpdateCachedLogo) {
489 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
490 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
492 Logo fresh_logo = GetSampleLogo2(logo_url_, test_clock_->Now());
493 SetServerResponseWhenFingerprint(cached_logo.metadata.fingerprint,
494 ServerResponse(fresh_logo));
496 logo_cache_->ExpectSetCachedLogo(&fresh_logo);
497 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
498 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
499 observer_.ExpectCachedAndFreshLogos(&cached_logo, &fresh_logo);
501 GetLogo();
504 TEST_F(LogoTrackerTest, InvalidateCachedLogo) {
505 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
506 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
508 // This response means there's no current logo.
509 SetServerResponseWhenFingerprint(cached_logo.metadata.fingerprint,
510 ")]}' {\"update\":{}}");
512 logo_cache_->ExpectSetCachedLogo(NULL);
513 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
514 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
515 observer_.ExpectCachedAndFreshLogos(&cached_logo, NULL);
517 GetLogo();
520 TEST_F(LogoTrackerTest, DeleteCachedLogoFromOldUrl) {
521 SetServerResponse("", net::URLRequestStatus::FAILED, net::HTTP_OK);
522 Logo cached_logo =
523 GetSampleLogo(GURL("http://oldsearchprovider.com"), test_clock_->Now());
524 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
526 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
527 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
528 EXPECT_CALL(*logo_cache_, SetCachedLogo(NULL)).Times(AnyNumber());
529 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
530 observer_.ExpectCachedLogo(NULL);
531 GetLogo();
534 TEST_F(LogoTrackerTest, LogoWithTTLCannotBeShownAfterExpiration) {
535 Logo logo = GetSampleLogo(logo_url_, test_clock_->Now());
536 base::TimeDelta time_to_live = base::TimeDelta::FromDays(3);
537 logo.metadata.expiration_time = test_clock_->Now() + time_to_live;
538 SetServerResponse(ServerResponse(logo));
539 GetLogo();
541 const LogoMetadata* cached_metadata =
542 logo_cache_->GetCachedLogoMetadata();
543 EXPECT_TRUE(cached_metadata != NULL);
544 EXPECT_FALSE(cached_metadata->can_show_after_expiration);
545 EXPECT_EQ(test_clock_->Now() + time_to_live,
546 cached_metadata->expiration_time);
549 TEST_F(LogoTrackerTest, LogoWithoutTTLCanBeShownAfterExpiration) {
550 Logo logo = GetSampleLogo(logo_url_, test_clock_->Now());
551 base::TimeDelta time_to_live = base::TimeDelta();
552 SetServerResponse(MakeServerResponse(logo, time_to_live));
553 GetLogo();
555 const LogoMetadata* cached_metadata =
556 logo_cache_->GetCachedLogoMetadata();
557 EXPECT_TRUE(cached_metadata != NULL);
558 EXPECT_TRUE(cached_metadata->can_show_after_expiration);
559 EXPECT_EQ(test_clock_->Now() + base::TimeDelta::FromDays(30),
560 cached_metadata->expiration_time);
563 TEST_F(LogoTrackerTest, UseSoftExpiredCachedLogo) {
564 SetServerResponse("", net::URLRequestStatus::FAILED, net::HTTP_OK);
565 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
566 cached_logo.metadata.expiration_time =
567 test_clock_->Now() - base::TimeDelta::FromSeconds(1);
568 cached_logo.metadata.can_show_after_expiration = true;
569 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
571 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
572 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
573 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
574 observer_.ExpectCachedLogo(&cached_logo);
575 GetLogo();
578 TEST_F(LogoTrackerTest, RerequestSoftExpiredCachedLogo) {
579 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
580 cached_logo.metadata.expiration_time =
581 test_clock_->Now() - base::TimeDelta::FromDays(5);
582 cached_logo.metadata.can_show_after_expiration = true;
583 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
585 Logo fresh_logo = GetSampleLogo2(logo_url_, test_clock_->Now());
586 SetServerResponse(ServerResponse(fresh_logo));
588 logo_cache_->ExpectSetCachedLogo(&fresh_logo);
589 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
590 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
591 observer_.ExpectCachedAndFreshLogos(&cached_logo, &fresh_logo);
593 GetLogo();
596 TEST_F(LogoTrackerTest, DeleteAncientCachedLogo) {
597 SetServerResponse("", net::URLRequestStatus::FAILED, net::HTTP_OK);
598 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
599 cached_logo.metadata.expiration_time =
600 test_clock_->Now() - base::TimeDelta::FromDays(200);
601 cached_logo.metadata.can_show_after_expiration = true;
602 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
604 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
605 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
606 EXPECT_CALL(*logo_cache_, SetCachedLogo(NULL)).Times(AnyNumber());
607 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
608 observer_.ExpectCachedLogo(NULL);
609 GetLogo();
612 TEST_F(LogoTrackerTest, DeleteExpiredCachedLogo) {
613 SetServerResponse("", net::URLRequestStatus::FAILED, net::HTTP_OK);
614 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
615 cached_logo.metadata.expiration_time =
616 test_clock_->Now() - base::TimeDelta::FromSeconds(1);
617 cached_logo.metadata.can_show_after_expiration = false;
618 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
620 EXPECT_CALL(*logo_cache_, UpdateCachedLogoMetadata(_)).Times(0);
621 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(0);
622 EXPECT_CALL(*logo_cache_, SetCachedLogo(NULL)).Times(AnyNumber());
623 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(1));
624 observer_.ExpectCachedLogo(NULL);
625 GetLogo();
628 // Tests that deal with multiple listeners.
630 void EnqueueObservers(LogoTracker* logo_tracker,
631 const ScopedVector<MockLogoObserver>& observers,
632 size_t start_index) {
633 if (start_index >= observers.size())
634 return;
636 logo_tracker->GetLogo(observers[start_index]);
637 base::MessageLoop::current()->PostTask(FROM_HERE,
638 base::Bind(&EnqueueObservers,
639 logo_tracker,
640 base::ConstRef(observers),
641 start_index + 1));
644 TEST_F(LogoTrackerTest, SupportOverlappingLogoRequests) {
645 Logo cached_logo = GetSampleLogo(logo_url_, test_clock_->Now());
646 logo_cache_->EncodeAndSetCachedLogo(cached_logo);
647 ON_CALL(*logo_cache_, SetCachedLogo(_)).WillByDefault(Return());
649 Logo fresh_logo = GetSampleLogo2(logo_url_, test_clock_->Now());
650 std::string response = ServerResponse(fresh_logo);
651 SetServerResponse(response);
652 SetServerResponseWhenFingerprint(cached_logo.metadata.fingerprint, response);
654 const int kNumListeners = 10;
655 ScopedVector<MockLogoObserver> listeners;
656 for (int i = 0; i < kNumListeners; ++i) {
657 MockLogoObserver* listener = new MockLogoObserver();
658 listener->ExpectCachedAndFreshLogos(&cached_logo, &fresh_logo);
659 listeners.push_back(listener);
661 EnqueueObservers(logo_tracker_, listeners, 0);
663 EXPECT_CALL(*logo_cache_, SetCachedLogo(_)).Times(AtMost(3));
664 EXPECT_CALL(*logo_cache_, OnGetCachedLogo()).Times(AtMost(3));
666 base::RunLoop().RunUntilIdle();
669 TEST_F(LogoTrackerTest, DeleteObserversWhenLogoURLChanged) {
670 MockLogoObserver listener1;
671 listener1.ExpectNoLogo();
672 logo_tracker_->GetLogo(&listener1);
674 logo_url_ = GURL("http://example.com/new-logo-url");
675 logo_tracker_->SetServerAPI(logo_url_,
676 base::Bind(&GoogleParseLogoResponse),
677 base::Bind(&GoogleAppendFingerprintToLogoURL));
678 Logo logo = GetSampleLogo(logo_url_, test_clock_->Now());
679 SetServerResponse(ServerResponse(logo));
681 MockLogoObserver listener2;
682 listener2.ExpectFreshLogo(&logo);
683 logo_tracker_->GetLogo(&listener2);
685 base::RunLoop().RunUntilIdle();
688 } // namespace
690 } // namespace search_provider_logos