File: lobster_page_handler_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (289 lines) | stat: -rw-r--r-- 11,065 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// 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/ui/webui/ash/lobster/lobster_page_handler.h"

#include <optional>
#include <string_view>
#include <vector>

#include "ash/public/cpp/lobster/lobster_enums.h"
#include "ash/public/cpp/lobster/lobster_result.h"
#include "ash/public/cpp/lobster/lobster_session.h"
#include "base/base64.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/test/test_future.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_core_service_factory.h"
#include "chrome/browser/download/download_core_service_impl.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ash {

namespace {

constexpr std::string_view kRawBytes1 = "a1b2c3";
constexpr std::string_view kRawBytes2 = "d4e5f6";

class FakeLobsterSession : public LobsterSession {
 public:
  FakeLobsterSession(const LobsterResult& result,
                     bool commit_or_download_status,
                     bool feedback_submission_status)
      : result_(result),
        commit_or_download_status_(commit_or_download_status),
        feedback_submission_status_(feedback_submission_status) {}
  ~FakeLobsterSession() override = default;

  void DownloadCandidate(int candidate_id,
                         const base::FilePath& file_path,
                         StatusCallback callback) override {
    std::move(callback).Run(commit_or_download_status_);
  }
  void CommitAsInsert(int candidate_id, StatusCallback callback) override {
    std::move(callback).Run(commit_or_download_status_);
  }
  void CommitAsDownload(int candidate_id,
                        const base::FilePath& file_path,
                        StatusCallback callback) override {
    std::move(callback).Run(commit_or_download_status_);
  }
  void RequestCandidates(const std::string& query,
                         int num_candidates,
                         RequestCandidatesCallback callback) override {
    std::move(callback).Run(result_);
  }
  void PreviewFeedback(int candidate_id,
                       LobsterPreviewFeedbackCallback callback) override {}
  bool SubmitFeedback(int candidate_id,
                      const std::string& description) override {
    return feedback_submission_status_;
  }
  void ShowDisclaimerUIAndCacheContext(
      std::optional<std::string> query,
      const gfx::Rect& anchor_bounds) override {}
  void LoadUI(std::optional<std::string> query,
              LobsterMode mode,
              const gfx::Rect& caret_bounds) override {}
  void LoadUIFromCachedContext() override {}
  void ShowUI() override {}
  void CloseUI() override {}
  void RecordWebUIMetricEvent(LobsterMetricState metric_state) override {
    metric_state_ = metric_state;
  }

  LobsterMetricState metric_state() { return metric_state_; }

 private:
  LobsterResult result_;
  bool commit_or_download_status_;
  bool feedback_submission_status_;
  LobsterMetricState metric_state_;
};

class LobsterPageHandlerTest : public testing::Test {
 public:
  void SetUp() override {
    DownloadCoreServiceFactory::GetForBrowserContext(&profile_)
        ->SetDownloadManagerDelegateForTesting(
            std::make_unique<ChromeDownloadManagerDelegate>(&profile_));

    // Use a temporary directory for downloads.
    ASSERT_TRUE(download_dir_.CreateUniqueTempDir());
    DownloadPrefs* prefs =
        DownloadPrefs::FromDownloadManager(profile_.GetDownloadManager());
    prefs->SetDownloadPath(download_dir_.GetPath());
    prefs->SkipSanitizeDownloadTargetPathForTesting();
  }
  TestingProfile& profile() { return profile_; }

 protected:
  content::BrowserTaskEnvironment task_environment_;
  base::ScopedTempDir download_dir_;

 private:
  TestingProfile profile_;
};

TEST_F(LobsterPageHandlerTest,
       RequestCandidatesReturnsImagesInCorrectJpegFormat) {
  std::vector<LobsterImageCandidate> image_candidates = {
      LobsterImageCandidate(/*id=*/0, /*image_bytes=*/kRawBytes1.data(),
                            /*seed=*/20,
                            /*user_query=*/"a nice strawberry",
                            /*rewritten_query=*/"rewritten: a nice strawberry"),
      LobsterImageCandidate(
          /*id=*/1, /*image_bytes=*/kRawBytes2.data(),
          /*seed=*/21,
          /*user_query=*/"a nice strawberry",
          /*rewritten_query=*/"rewritten: a nice strawberry")};
  FakeLobsterSession session(std::move(image_candidates),
                             /*commit_or_download_status=*/true,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<lobster::mojom::ResponsePtr> future;

  page_handler.RequestCandidates("a nice strawberry", 2, future.GetCallback());

  EXPECT_TRUE(future.Get()->is_candidates());

  auto& actual_candidates = future.Get()->get_candidates();

  EXPECT_EQ(actual_candidates.size(), 2u);
  EXPECT_EQ(actual_candidates[0]->id, 0u);
  EXPECT_EQ(actual_candidates[0]->data_url,
            GURL(base::StrCat(
                {"data:image/jpeg;base64,", base::Base64Encode(kRawBytes1)})));
  EXPECT_EQ(actual_candidates[1]->id, 1u);
  EXPECT_EQ(actual_candidates[1]->data_url,
            GURL(base::StrCat(
                {"data:image/jpeg;base64,", base::Base64Encode(kRawBytes2)})));
}

TEST_F(LobsterPageHandlerTest, RequestCandidatesReturnsError) {
  FakeLobsterSession session(
      base::unexpected(
          LobsterError(LobsterErrorCode::kInvalidArgument, "dummy error")),
      /*commit_or_download_status=*/false, /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<lobster::mojom::ResponsePtr> future;

  page_handler.RequestCandidates("a nice strawberry", 2, future.GetCallback());

  EXPECT_TRUE(future.Get()->is_error());

  auto& actual_error = future.Get()->get_error();

  EXPECT_EQ(actual_error->code, LobsterErrorCode::kInvalidArgument);
  EXPECT_EQ(actual_error->message, "dummy error");
}

TEST_F(LobsterPageHandlerTest, DownloadCandidateSucceeds) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/true,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.DownloadCandidate(1, future.GetCallback());

  EXPECT_TRUE(future.Get());
}

TEST_F(LobsterPageHandlerTest, DownloadCandidateFails) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/false,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.DownloadCandidate(/*id=*/1, future.GetCallback());

  EXPECT_FALSE(future.Get());
}

TEST_F(LobsterPageHandlerTest, CommitAsDownloadSucceeds) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/true,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.CommitAsDownload(/*id=*/1, future.GetCallback());

  EXPECT_TRUE(future.Get());
}

TEST_F(LobsterPageHandlerTest, CommitAsDownloadFails) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/false,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.CommitAsDownload(/*id=*/1, future.GetCallback());

  EXPECT_FALSE(future.Get());
}

TEST_F(LobsterPageHandlerTest, CommitAsInsertSucceeds) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/true,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.CommitAsInsert(/*id=*/1, future.GetCallback());

  EXPECT_TRUE(future.Get());
}

TEST_F(LobsterPageHandlerTest, CommitAsInsertFails) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/false,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.CommitAsInsert(/*id=*/1, future.GetCallback());

  EXPECT_FALSE(future.Get());
}

TEST_F(LobsterPageHandlerTest, SubmitFeedbackFails) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/false,
                             /*feedback_submission_status=*/false);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.SubmitFeedback(/*id=*/1, /*description=*/"dummy description",
                              future.GetCallback());

  EXPECT_FALSE(future.Get());
}

TEST_F(LobsterPageHandlerTest, SubmitFeedbackSucceeds) {
  FakeLobsterSession session({}, /*commit_or_download_status=*/false,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());
  base::test::TestFuture<bool> future;

  page_handler.SubmitFeedback(/*id=*/1, /*description=*/"dummy description",
                              future.GetCallback());

  EXPECT_TRUE(future.Get());
}

class LobsterPageHandlerMetrics
    : public LobsterPageHandlerTest,
      public testing::WithParamInterface<LobsterMetricState> {};

INSTANTIATE_TEST_SUITE_P(
    LobsterPageHandlerTest,
    LobsterPageHandlerMetrics,
    testing::ValuesIn<LobsterMetricState>({
        LobsterMetricState::kQueryPageImpression,
        LobsterMetricState::kRequestInitialCandidates,
        LobsterMetricState::kRequestInitialCandidatesSuccess,
        LobsterMetricState::kRequestInitialCandidatesError,
        LobsterMetricState::kInitialCandidatesImpression,
        LobsterMetricState::kRequestMoreCandidates,
        LobsterMetricState::kRequestMoreCandidatesSuccess,
        LobsterMetricState::kRequestMoreCandidatesError,
        LobsterMetricState::kMoreCandidatesAppended,
        LobsterMetricState::kFeedbackThumbsUp,
        LobsterMetricState::kFeedbackThumbsDown,
    }));

TEST_P(LobsterPageHandlerMetrics, EmitMetricEvent) {
  const LobsterMetricState& state = GetParam();
  FakeLobsterSession session({}, /*commit_or_download_status=*/true,
                             /*feedback_submission_status=*/true);
  LobsterPageHandler page_handler = LobsterPageHandler(&session, &profile());

  page_handler.EmitMetricEvent(state);

  EXPECT_EQ(session.metric_state(), state);
}

}  // namespace
}  // namespace ash