File: test_util.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (241 lines) | stat: -rw-r--r-- 9,380 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/on_device_translation/test/test_util.h"

#include "base/files/file_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/on_device_translation/language_pack_util.h"
#include "chrome/browser/on_device_translation/pref_names.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "components/prefs/pref_service.h"
#include "components/services/on_device_translation/test/test_util.h"
#include "content/public/test/browser_test_utils.h"

using ::testing::_;
using ::testing::Invoke;

namespace on_device_translation {

MockComponentManager::MockComponentManager(const base::FilePath& package_dir)
    : package_dir_(package_dir),
      mock_component_manager_(ComponentManager::SetForTesting(this)) {}

MockComponentManager::~MockComponentManager() = default;
void MockComponentManager::DoNotExpectCallRegisterTranslateKitComponent() {
  EXPECT_CALL(*this, RegisterTranslateKitComponentImpl()).Times(0);
}

void MockComponentManager::ExpectCallRegisterTranslateKitComponentAndInstall() {
  EXPECT_CALL(*this, RegisterTranslateKitComponentImpl())
      .WillOnce(Invoke([&]() { InstallMockTranslateKitComponentLater(); }));
}

void MockComponentManager::DoNotExpectCallRegisterLanguagePackComponent() {
  EXPECT_CALL(*this, RegisterTranslateKitLanguagePackComponent(_)).Times(0);
}

void MockComponentManager::ExpectCallRegisterLanguagePackComponentAndInstall(
    const base::span<const LanguagePackKey>& language_pack_keys) {
  auto& expectation =
      EXPECT_CALL(*this, RegisterTranslateKitLanguagePackComponent(_));
  for (const auto expected_key : language_pack_keys) {
    expectation.WillOnce(Invoke([&, expected_key](LanguagePackKey key) {
      EXPECT_EQ(key, expected_key);
      InstallMockLanguagePackLater(key);
    }));
  }
}

void MockComponentManager::InstallMockTranslateKitComponent() {
  InstallComponent(GetMockLibraryPath());
}

void MockComponentManager::InstallMockInvalidFunctionPointerLibraryComponent() {
  InstallComponent(GetMockInvalidFunctionPointerLibraryPath());
}

void MockComponentManager::InstallMockFailingLibraryComponent() {
  InstallComponent(GetMockFailingLibraryPath());
}

void MockComponentManager::InstallEmptyMockComponent() {
  g_browser_process->local_state()->SetFilePath(
      prefs::kTranslateKitBinaryPath, package_dir_.AppendASCII("fakefile"));
}

void MockComponentManager::InstallComponent(base::FilePath library_path) {
  CHECK(!library_path.empty());
  base::ScopedAllowBlockingForTesting allow_io;
  const auto binary_path = package_dir_.Append(library_path.BaseName());
  if (!base::DirectoryExists(binary_path.DirName())) {
    CHECK(base::CreateDirectory(binary_path.DirName()));
  }
  CHECK(base::CopyFile(library_path, binary_path));
  g_browser_process->local_state()->SetFilePath(prefs::kTranslateKitBinaryPath,
                                                binary_path);
}

void MockComponentManager::InstallMockLanguagePack(
    LanguagePackKey language_pack_key) {
  InstallMockLanguagePack(
      language_pack_key,
      CreateFakeDictionaryData(GetSourceLanguageCode(language_pack_key),
                               GetTargetLanguageCode(language_pack_key)));
}

void MockComponentManager::RegisterLanguagePack(
    LanguagePackKey language_pack_key) {
  const LanguagePackComponentConfig* config =
      kLanguagePackComponentConfigMap.at(language_pack_key);
  g_browser_process->local_state()->SetBoolean(
      GetRegisteredFlagPrefName(*config), true);
}

void MockComponentManager::InstallMockLanguagePack(
    LanguagePackKey language_pack_key,
    const std::string_view fake_dictionary_data) {
  base::ScopedAllowBlockingForTesting allow_io;
  const auto dict_dir_path =
      package_dir_.AppendASCII(GetPackageInstallDirName(language_pack_key));
  const auto dict_path = dict_dir_path.AppendASCII("dict.dat");
  if (!base::DirectoryExists(dict_dir_path)) {
    CHECK(base::CreateDirectory(dict_dir_path));
  }
  CHECK(base::File(dict_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE)
            .WriteAndCheck(0, base::as_byte_span(fake_dictionary_data)));
  const LanguagePackComponentConfig* config =
      kLanguagePackComponentConfigMap.at(language_pack_key);
  g_browser_process->local_state()->SetBoolean(
      GetRegisteredFlagPrefName(*config), true);
  g_browser_process->local_state()->SetFilePath(
      GetComponentPathPrefName(*config), dict_dir_path);
}

void MockComponentManager::InstallMockTranslateKitComponentLater() {
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(&MockComponentManager::InstallMockTranslateKitComponent,
                     weak_ptr_factory_.GetWeakPtr()));
}

void MockComponentManager::InstallMockLanguagePackLater(
    LanguagePackKey language_pack_key) {
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(
                     [](base::WeakPtr<MockComponentManager> self,
                        LanguagePackKey language_pack_key) {
                       if (self) {
                         self->InstallMockLanguagePack(language_pack_key);
                       }
                     },
                     weak_ptr_factory_.GetWeakPtr(), language_pack_key));
}

MockTranslationManagerImpl::MockTranslationManagerImpl(
    content::BrowserContext* browser_context,
    const url::Origin& origin)
    : TranslationManagerImpl(browser_context, origin),
      mock_translation_manager_impl_(
          TranslationManagerImpl::SetForTesting(this)) {}

MockTranslationManagerImpl::~MockTranslationManagerImpl() = default;

std::string CreateFakeDictionaryData(const std::string_view sourceLang,
                                     const std::string_view targetLang) {
  return base::StringPrintf("%s to %s: ", sourceLang, targetLang);
}

void TestSimpleTranslationWorks(Browser* browser,
                                LanguagePackKey language_pack_key) {
  TestSimpleTranslationWorks(browser, GetSourceLanguageCode(language_pack_key),
                             GetTargetLanguageCode(language_pack_key));
}

void TestSimpleTranslationWorks(Browser* browser,
                                const std::string_view sourceLang,
                                const std::string_view targetLang) {
  // Translate "hello" from `sourceLang` to `targetLang`.
  // Note: the mock TranslateKit component returns the concatenation of the
  // content of "dict.dat" in the language pack and the input text.
  // See comments in mock_translate_kit_lib.cc for more details.
  EXPECT_EQ(EvalJs(browser->tab_strip_model()->GetActiveWebContents(),
                   base::StringPrintf(R"(
        (async () => {
          try {
            const translator = await Translator.create({
              sourceLanguage: '%s',
              targetLanguage: '%s',
            });
            return await translator.translate('hello');
          } catch (e) {
            return e.toString();
          }
        })();
      )",
                                      sourceLang, targetLang))
                .ExtractString(),
            base::StringPrintf("%s to %s: hello", sourceLang, targetLang));
}

void TestCreateTranslator(Browser* browser,
                          LanguagePackKey language_pack_key,
                          const std::string_view result) {
  TestCreateTranslator(browser, GetSourceLanguageCode(language_pack_key),
                       GetTargetLanguageCode(language_pack_key), result);
}

// Tests that the createTranslator() returns the expected result.
void TestCreateTranslator(Browser* browser,
                          const std::string_view sourceLang,
                          const std::string_view targetLang,
                          const std::string_view result) {
  ASSERT_EQ(EvalJs(browser->tab_strip_model()->GetActiveWebContents(),
                   base::StringPrintf(R"(
  (async () => {
    try {
      await Translator.create({
          sourceLanguage: '%s',
          targetLanguage: '%s',
        });
      return 'OK';
    } catch (e) {
      return e.toString();
    }
    })();
  )",
                                      sourceLang, targetLang))
                .ExtractString(),
            result);
}

// Tests that availability() method returns the expected result for the given
// languages.
void TestTranslationAvailable(Browser* browser,
                              const std::string_view sourceLang,
                              const std::string_view targetLang,
                              const std::string_view result) {
  ASSERT_EQ(EvalJs(browser->tab_strip_model()->GetActiveWebContents(),
                   base::StringPrintf(R"(
  (async () => {
    try {
      return await Translator.availability({
          sourceLanguage: '%s',
          targetLanguage: '%s',
        });
    } catch (e) {
      return e.toString();
    }
    })();
  )",
                                      sourceLang, targetLang))
                .ExtractString(),
            result);
}

}  // namespace on_device_translation