1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/font_family_cache.h"
7 #include "base/strings/utf_string_conversions.h"
8 #include "chrome/test/base/testing_profile.h"
9 #include "components/sync_preferences/testing_pref_service_syncable.h"
10 #include "content/public/test/browser_task_environment.h"
11 #include "testing/gtest/include/gtest/gtest.h"
15 class TestingFontFamilyCache : public FontFamilyCache {
17 explicit TestingFontFamilyCache(Profile* profile)
18 : FontFamilyCache(profile), fetch_font_count_(0) {}
20 TestingFontFamilyCache(const TestingFontFamilyCache&) = delete;
21 TestingFontFamilyCache& operator=(const TestingFontFamilyCache&) = delete;
23 ~TestingFontFamilyCache() override {}
24 std::u16string FetchFont(const char* script, const char* map_name) override {
26 return FontFamilyCache::FetchFont(script, map_name);
29 int fetch_font_count_;
34 // Tests that the cache is correctly set and cleared.
35 TEST(FontFamilyCacheTest, Caching) {
36 content::BrowserTaskEnvironment task_environment_;
37 TestingProfile profile;
38 TestingFontFamilyCache cache(&profile);
39 sync_preferences::TestingPrefServiceSyncable* prefs =
40 profile.GetTestingPrefService();
42 std::string font1("font 1");
43 std::string font2("font 2");
44 std::string map_name("webkit.webprefs.fonts.sansserif");
45 std::string script("Zzyxca");
46 std::string pref_name(map_name + '.' + script);
47 std::string pref_name2(map_name + '.' + "adsf");
49 // Registers 2 preferences, and sets the first one.
50 prefs->registry()->RegisterStringPref(pref_name.c_str(), std::string());
51 prefs->registry()->RegisterStringPref(pref_name2.c_str(), std::string());
52 prefs->SetString(pref_name.c_str(), font1.c_str());
54 // Check that the right preference is returned.
55 std::string result = base::UTF16ToUTF8(
56 cache.FetchAndCacheFont(script.c_str(), map_name.c_str()));
57 EXPECT_EQ(font1, result);
58 EXPECT_EQ(1, cache.fetch_font_count_);
60 // Check that the second access uses the cache.
61 result = base::UTF16ToUTF8(
62 cache.FetchAndCacheFont(script.c_str(), map_name.c_str()));
63 EXPECT_EQ(font1, result);
64 EXPECT_EQ(1, cache.fetch_font_count_);
66 // Changing another preference should have no effect.
67 prefs->SetString(pref_name2.c_str(), "katy perry");
68 result = base::UTF16ToUTF8(
69 cache.FetchAndCacheFont(script.c_str(), map_name.c_str()));
70 EXPECT_EQ(font1, result);
71 EXPECT_EQ(1, cache.fetch_font_count_);
73 // Changing the preferences invalidates the cache.
74 prefs->SetString(pref_name.c_str(), font2.c_str());
75 result = base::UTF16ToUTF8(
76 cache.FetchAndCacheFont(script.c_str(), map_name.c_str()));
77 EXPECT_EQ(font2, result);
78 EXPECT_EQ(2, cache.fetch_font_count_);