summaryrefslogtreecommitdiffstats
path: root/chromium/chrome/browser/media/webrtc/region_capture_browsertest.cc
blob: baa9ac61fa458ab6907990f83e91f4ee9d5b45f4 (plain)
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <set>
#include <string>
#include <vector>

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/guid.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/media/webrtc/webrtc_browsertest_base.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/permissions/permission_request_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_base.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"

// TODO(crbug.com/1215089): Enable this test suite on Lacros.
#if !BUILDFLAG(IS_CHROMEOS_LACROS)

namespace {

using content::WebContents;
using testing::Bool;
using testing::Combine;
using testing::TestParamInfo;
using testing::Values;
using testing::WithParamInterface;

// TODO(crbug.com/1247761): Add tests that verify excessive calls to
// produceCropId() yield the empty string.
MATCHER(IsEmptyCropId, "") {
  static_assert(std::is_same<decltype(arg), const std::string&>::value, "");
  return arg == "empty-crop-id";  // See region_capture_main.html for rationale.
}

MATCHER(IsValidCropId, "") {
  static_assert(std::is_same<decltype(arg), const std::string&>::value, "");
  return base::GUID::ParseLowercase(arg).is_valid();
}

const char kMainPageTitle[] = "Region Capture Test - Page 1 (Main)";
const char kOtherPageTitle[] = "Region Capture Test - Page 2 (Main)";

// Tracks CropIdWebContentsHelper::kMaxCropIdsPerWebContents.
constexpr size_t kMaxCropIdsPerWebContents = 100;

enum {
  kMainPageTopLevelDocument,
  kMainPageEmbeddedDocument,
  kOtherPageTopLevelDocument,
  kOtherPageEmbeddedDocument,
  kServerCount  // Must be last.
};

enum Tab {
  kMainTab,
  kOtherTab,
  kTabCount  // Must be last.
};

enum class Frame {
  kNone,
  kTopLevelDocument,
  kEmbeddedFrame,
};

// Conveniently pack together all relevant information about a tab and
// conveniently expose test controls on it.
struct TabInfo {
  void StartEmbeddingFrame(const GURL& url) {
    std::string script_result;
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents->GetMainFrame(),
        base::StringPrintf("startEmbeddingFrame('%s');", url.spec().c_str()),
        &script_result));
    EXPECT_EQ(script_result, "embedding-done");
  }

  void StartCapture() {
    // Bring the tab into focus. This avoids getDisplayMedia rejection.
    browser->tab_strip_model()->ActivateTabAt(tab_strip_index);

    std::string script_result;
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents->GetMainFrame(), "startCapture();", &script_result));
    EXPECT_EQ(script_result, "capture-success");
  }

  void StartCaptureFromEmbeddedFrame() {
    // Bring the tab into focus. This avoids getDisplayMedia rejection.
    browser->tab_strip_model()->ActivateTabAt(tab_strip_index);

    std::string script_result;
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents->GetMainFrame(), "startCaptureFromEmbeddedFrame();",
        &script_result));
    EXPECT_EQ(script_result, "embedded-capture-success");
  }

  std::string ProduceCropId(Frame frame,
                            const std::string& element_id = "div") {
    DCHECK_NE(frame, Frame::kNone);
    const std::string frame_js =
        (frame == Frame::kTopLevelDocument) ? "top" : "embedded";
    std::string script_result = "error-not-modified";
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents->GetMainFrame(),
        base::StrCat(
            {"produceCropId(\"", frame_js, "\", \"" + element_id + "\");"}),
        &script_result));
    return script_result;
  }

  std::string CropTo(const std::string& crop_id) {
    std::string script_result = "error-not-modified";
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents->GetMainFrame(),
        base::StrCat({"cropTo(\"", crop_id, "\");"}), &script_result));
    return script_result;
  }

  std::string CreateNewDivElement(Frame frame, const std::string& div_id) {
    DCHECK_NE(frame, Frame::kNone);
    const std::string frame_js =
        (frame == Frame::kTopLevelDocument) ? "top" : "embedded";
    std::string script_result = "error-not-modified";
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents->GetMainFrame(),
        base::StrCat(
            {"createNewDivElement(\"", frame_js, "\", \"", div_id, "\");"}),
        &script_result));
    return script_result;
  }

  Browser* browser;
  WebContents* web_contents;
  int tab_strip_index;
};

}  // namespace

// Essentially depends on InProcessBrowserTest, but WebRtcTestBase provides
// detection of JS errors.
class RegionCaptureBrowserTest : public WebRtcTestBase {
 public:
  ~RegionCaptureBrowserTest() override = default;

  void SetUpInProcessBrowserTestFixture() override {
    WebRtcTestBase::SetUpInProcessBrowserTestFixture();

    DetectErrorsInJavaScript();

    base::FilePath test_dir;
    ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));

    for (int i = 0; i < kServerCount; ++i) {
      servers_.emplace_back(std::make_unique<net::EmbeddedTestServer>());
      servers_[i]->ServeFilesFromDirectory(test_dir);
      ASSERT_TRUE(servers_[i]->Start());
    }
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(
        switches::kEnableExperimentalWebPlatformFeatures);
    command_line_ = command_line;
  }

  void TearDownOnMainThread() override {
    for (auto& server : servers_) {
      if (server) {
        ASSERT_TRUE(server->ShutdownAndWaitUntilComplete());
      }
    }

    WebRtcTestBase::TearDownOnMainThread();
  }

  // Same as WebRtcTestBase::OpenTestPageInNewTab, but does not assume
  // a single embedded server is used for all pages, and also embeds
  // a cross-origin iframe.
  void SetUpPage(const std::string& top_level_document_document,
                 net::EmbeddedTestServer* top_level_document_server,
                 const std::string& embedded_iframe_document,
                 net::EmbeddedTestServer* embedded_iframe_server,
                 TabInfo* tab_info) const {
    chrome::AddTabAt(browser(), GURL(url::kAboutBlankURL), -1, true);
    EXPECT_TRUE(ui_test_utils::NavigateToURL(
        browser(),
        top_level_document_server->GetURL(top_level_document_document)));

    WebContents* const web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    // web_contents_vector_.push_back(web_contents);
    permissions::PermissionRequestManager::FromWebContents(web_contents)
        ->set_auto_response_for_test(
            permissions::PermissionRequestManager::ACCEPT_ALL);

    *tab_info = {browser(), web_contents,
                 browser()->tab_strip_model()->active_index()};
    tab_info->StartEmbeddingFrame(
        embedded_iframe_server->GetURL(embedded_iframe_document));
  }

  // Set up all (necessary) tabs, loads iframes, and start capturing the
  // relevant tab.
  void SetUpTest(Frame capturing_entity, bool self_capture) {
    // Other page (for other-tab-capture).
    SetUpPage("/webrtc/region_capture_other_main.html",
              servers_[kOtherPageTopLevelDocument].get(),
              "/webrtc/region_capture_other_embedded.html",
              servers_[kOtherPageEmbeddedDocument].get(), &tabs_[kOtherTab]);

    // Main page (for self-capture). Instantiate it second to help it get focus.
    SetUpPage("/webrtc/region_capture_main.html",
              servers_[kMainPageTopLevelDocument].get(),
              "/webrtc/region_capture_embedded.html",
              servers_[kMainPageEmbeddedDocument].get(), &tabs_[kMainTab]);

    DCHECK(command_line_);
    command_line_->AppendSwitchASCII(
        switches::kAutoSelectTabCaptureSourceByTitle,
        self_capture ? kMainPageTitle : kOtherPageTitle);

    if (capturing_entity == Frame::kTopLevelDocument) {
      tabs_[kMainTab].StartCapture();
    } else if (capturing_entity == Frame::kEmbeddedFrame) {
      tabs_[kMainTab].StartCaptureFromEmbeddedFrame();
    }
  }

  // Manipulation after SetUpCommandLine, but before capture starts,
  // allows tests to set which tab to capture.
  base::CommandLine* command_line_ = nullptr;

  // Holds the tabs manipulated by this test.
  TabInfo tabs_[kTabCount];

  // Each page is served from a distinct origin, thereby proving that cropping
  // works irrespective of whether iframes are in/out-of-process.
  std::vector<std::unique_ptr<net::EmbeddedTestServer>> servers_;
};

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       ProduceCropIdReturnsValidIdInMainPage) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  EXPECT_THAT(tabs_[kMainTab].ProduceCropId(Frame::kTopLevelDocument),
              IsValidCropId());
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       ProduceCropIdReturnsValidIdInCrossOriginIframe) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  EXPECT_THAT(tabs_[kMainTab].ProduceCropId(Frame::kEmbeddedFrame),
              IsValidCropId());
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       ProduceCropIdReturnsSameIdIfSameElement) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  EXPECT_EQ(tabs_[kMainTab].ProduceCropId(Frame::kTopLevelDocument),
            tabs_[kMainTab].ProduceCropId(Frame::kTopLevelDocument));
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       CropToAllowedIfTopLevelCropsToElementInTopLevel) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());
  EXPECT_EQ(tab.CropTo(crop_id), "top-level-crop-success");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       CropToAllowedIfTopLevelCropsToElementInEmbedded) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kEmbeddedFrame);
  ASSERT_THAT(crop_id, IsValidCropId());
  EXPECT_EQ(tab.CropTo(crop_id), "top-level-crop-success");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       CropToAllowedIfEmbeddedFrameCropsToElementInTopLevel) {
  SetUpTest(Frame::kEmbeddedFrame, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());
  EXPECT_EQ(tab.CropTo(crop_id), "embedded-crop-success");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       CropToAllowedIfEmbeddedFrameCropsToElementInEmbedded) {
  SetUpTest(Frame::kEmbeddedFrame, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kEmbeddedFrame);
  ASSERT_THAT(crop_id, IsValidCropId());
  EXPECT_EQ(tab.CropTo(crop_id), "embedded-crop-success");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropToAllowedToUncrop) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());
  ASSERT_EQ(tab.CropTo(crop_id), "top-level-crop-success");

  EXPECT_EQ(tab.CropTo(""), "top-level-crop-success");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropToRejectedIfUnknown) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());

  DCHECK(!crop_id.empty());  // Test sanity.
  const std::string::value_type wrong_char = (crop_id[0] == 'a' ? 'b' : 'a');
  const std::string wrong_crop_id = wrong_char + crop_id.substr(1);
  EXPECT_EQ(tab.CropTo(wrong_crop_id), "top-level-crop-error");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, CropToRejectedIfInvalid) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());

  EXPECT_EQ(tab.CropTo("invalid-crop-id"), "top-level-crop-error");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       CropToRejectedIfProduceCropIdWasNeverCalled) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());

  const std::string kValidCropId = "01234567-0123-0123-0123-0123456789ab";
  ASSERT_THAT(kValidCropId, IsValidCropId());  // Test is sane.

  EXPECT_EQ(tab.CropTo(kValidCropId), "top-level-crop-error");
}

IN_PROC_BROWSER_TEST_F(
    RegionCaptureBrowserTest,
    CropToForUncroppingRejectedIfProduceCropIdWasCalledButTrackUncropped) {
  SetUpTest(Frame::kTopLevelDocument, /*self_capture=*/true);
  TabInfo& tab = tabs_[kMainTab];

  const std::string crop_id = tab.ProduceCropId(Frame::kTopLevelDocument);
  ASSERT_THAT(crop_id, IsValidCropId());
  // CropTo(crop_id) with a non-empty |crop_id| is intentionally not called.
  // Instead, the test immediately calls CropTo("") on a still-uncropped track,
  // attempting to stop cropping when no cropping was ever specified.
  EXPECT_EQ(tab.CropTo(""), "top-level-crop-success");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, MaxCropIdsInTopLevelDocument) {
  SetUpTest(Frame::kNone, /*self_capture=*/false);
  TabInfo& tab = tabs_[kMainTab];

  // Create kMaxCropIdsPerWebContents new elements and assign each a crop-ID.
  std::set<std::string> crop_ids;
  for (size_t i = 0; i < kMaxCropIdsPerWebContents; ++i) {
    const std::string element_id = ("new_id_" + base::NumberToString(i));
    ASSERT_EQ(tab.CreateNewDivElement(Frame::kTopLevelDocument, element_id),
              "top-level-new-div-success");
    const std::string crop_id =
        tab.ProduceCropId(Frame::kTopLevelDocument, element_id);
    ASSERT_THAT(crop_id, IsValidCropId());
    crop_ids.insert(crop_id);
  }
  EXPECT_EQ(crop_ids.size(), kMaxCropIdsPerWebContents);

  // Create one more element - this one won't get a crop-ID.
  const std::string element_id =
      ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents));
  ASSERT_EQ(tab.CreateNewDivElement(Frame::kTopLevelDocument, element_id),
            "top-level-new-div-success");
  EXPECT_EQ(tab.ProduceCropId(Frame::kTopLevelDocument, element_id),
            "top-level-produce-crop-id-error");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest, MaxCropIdsInEmbeddedFrame) {
  SetUpTest(Frame::kNone, /*self_capture=*/false);
  TabInfo& tab = tabs_[kMainTab];

  // Create kMaxCropIdsPerWebContents new elements and assign each a crop-ID.
  std::set<std::string> crop_ids;
  for (size_t i = 0; i < kMaxCropIdsPerWebContents; ++i) {
    const std::string element_id = ("new_id_" + base::NumberToString(i));
    ASSERT_EQ(tab.CreateNewDivElement(Frame::kEmbeddedFrame, element_id),
              "embedded-new-div-success");
    const std::string crop_id =
        tab.ProduceCropId(Frame::kEmbeddedFrame, element_id);
    ASSERT_THAT(crop_id, IsValidCropId());
    crop_ids.insert(crop_id);
  }
  EXPECT_EQ(crop_ids.size(), kMaxCropIdsPerWebContents);

  // Create one more element - this one won't get a crop-ID.
  const std::string element_id =
      ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents));
  ASSERT_EQ(tab.CreateNewDivElement(Frame::kEmbeddedFrame, element_id),
            "embedded-new-div-success");
  EXPECT_EQ(tab.ProduceCropId(Frame::kEmbeddedFrame, element_id),
            "embedded-produce-crop-id-error");
}

IN_PROC_BROWSER_TEST_F(RegionCaptureBrowserTest,
                       MaxCropIdsSharedBetweenFramesInTab) {
  SetUpTest(Frame::kNone, /*self_capture=*/false);
  TabInfo& tab = tabs_[kMainTab];

  static_assert(kMaxCropIdsPerWebContents > 1, "");

  // Create (kMaxCropIdsPerWebContents - 1) new elements and assign each a
  // crop-ID.
  std::set<std::string> crop_ids;
  for (size_t i = 0; i < kMaxCropIdsPerWebContents - 1; ++i) {
    const std::string element_id = ("new_id_" + base::NumberToString(i));
    ASSERT_EQ(tab.CreateNewDivElement(Frame::kTopLevelDocument, element_id),
              "top-level-new-div-success");
    const std::string crop_id =
        tab.ProduceCropId(Frame::kTopLevelDocument, element_id);
    ASSERT_THAT(crop_id, IsValidCropId());
    crop_ids.insert(crop_id);
  }
  EXPECT_EQ(crop_ids.size(), kMaxCropIdsPerWebContents - 1);

  // One more in the embedded frame is possible.
  std::string element_id =
      ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents - 1));
  ASSERT_EQ(tab.CreateNewDivElement(Frame::kEmbeddedFrame, element_id),
            "embedded-new-div-success");
  std::string crop_id = tab.ProduceCropId(Frame::kEmbeddedFrame, element_id);
  EXPECT_THAT(crop_id, IsValidCropId());
  EXPECT_TRUE(crop_ids.find(crop_id) == crop_ids.end());

  // Create one more element - this one won't get a crop-ID.
  element_id = ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents));
  ASSERT_EQ(tab.CreateNewDivElement(Frame::kTopLevelDocument, element_id),
            "top-level-new-div-success");
  EXPECT_EQ(tab.ProduceCropId(Frame::kTopLevelDocument, element_id),
            "top-level-produce-crop-id-error");
  // Neither in the top-level nor in the embedded frame.
  element_id =
      ("new_id_" + base::NumberToString(kMaxCropIdsPerWebContents + 1));
  ASSERT_EQ(tab.CreateNewDivElement(Frame::kEmbeddedFrame, element_id),
            "embedded-new-div-success");
  EXPECT_EQ(tab.ProduceCropId(Frame::kEmbeddedFrame, element_id),
            "embedded-produce-crop-id-error");
}

// Suite of tests ensuring that only self-capture may crop, and that it may
// only crop to targets in its own tab, but that any target in its own tab
// is permitted.
class RegionCaptureSelfCaptureOnlyBrowserTest
    : public RegionCaptureBrowserTest,
      public WithParamInterface<std::tuple<Frame, bool, Tab, Frame>> {
 public:
  RegionCaptureSelfCaptureOnlyBrowserTest()
      : capturing_entity_(std::get<0>(GetParam())),
        self_capture_(std::get<1>(GetParam())),
        target_element_tab_(std::get<2>(GetParam())),
        target_frame_(std::get<3>(GetParam())) {}
  ~RegionCaptureSelfCaptureOnlyBrowserTest() override = default;

 protected:
  // The capture is done from kMainTab in all instances of this parameterized
  // test. |capturing_entity_| controls whether the capture is initiated
  // from the top-level document of said tab, or an embedded frame.
  const Frame capturing_entity_;

  // Whether capturing self, or capturing the other tab.
  const bool self_capture_;

  // Whether the element on whose crop-ID we'll call cropTo():
  // * |target_element_tab_| - whether it's in kMainTab or in kOtherTab.
  // * |target_frame_| - whether it's in the top-level or an embedded frame.
  const Tab target_element_tab_;
  const Frame target_frame_;  // Top-level or embedded frame.
};

std::string ParamsToString(
    const TestParamInfo<RegionCaptureSelfCaptureOnlyBrowserTest::ParamType>&
        info) {
  return base::StrCat(
      {std::get<0>(info.param) == Frame::kTopLevelDocument ? "TopLevel"
                                                           : "EmbeddedFrame",
       std::get<1>(info.param) ? "SelfCapturing" : "CapturingOtherTab",
       "AndCroppingToElementIn",
       std::get<2>(info.param) == kMainTab ? "OwnTabs" : "OtherTabs",
       std::get<3>(info.param) == Frame::kTopLevelDocument ? "TopLevel"
                                                           : "EmbeddedFrame"});
}

INSTANTIATE_TEST_SUITE_P(
    _,
    RegionCaptureSelfCaptureOnlyBrowserTest,
    Combine(Values(Frame::kTopLevelDocument, Frame::kEmbeddedFrame),
            Bool(),
            Values(kMainTab, kOtherTab),
            Values(Frame::kTopLevelDocument, Frame::kEmbeddedFrame)),
    ParamsToString);

IN_PROC_BROWSER_TEST_P(RegionCaptureSelfCaptureOnlyBrowserTest, CropTo) {
  SetUpTest(capturing_entity_, self_capture_);

  // Prevent test false-positive - ensure that both tabs participating in the
  // test have at least one associated crop-ID, or otherwise they would not
  // have a CropIdWebContentsHelper.
  // To make things even clearer, ensure both the top-level and the embedded
  // frame have produced crop-IDs. (This should not be necessary, but is
  // done as an extra buffer against false-positives.)
  tabs_[kMainTab].ProduceCropId(Frame::kTopLevelDocument);
  tabs_[kMainTab].ProduceCropId(Frame::kEmbeddedFrame);
  tabs_[kOtherTab].ProduceCropId(Frame::kTopLevelDocument);
  tabs_[kOtherTab].ProduceCropId(Frame::kEmbeddedFrame);

  const std::string crop_id =
      tabs_[target_element_tab_].ProduceCropId(target_frame_);
  ASSERT_THAT(crop_id, IsValidCropId());

  // Cropping only permitted if both conditions hold.
  const bool expect_permitted =
      (self_capture_ && target_element_tab_ == kMainTab);

  const std::string expected_result = base::StrCat(
      {capturing_entity_ == Frame::kTopLevelDocument ? "top-level" : "embedded",
       "-", expect_permitted ? "crop-success" : "crop-error"});

  EXPECT_EQ(tabs_[kMainTab].CropTo(crop_id), expected_result);
}

#endif  //  !BUILDFLAG(IS_CHROMEOS_LACROS)