File: interactive_test_internal.cc

package info (click to toggle)
chromium 145.0.7632.159-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,976,224 kB
  • sloc: cpp: 36,198,469; ansic: 7,634,080; javascript: 3,564,060; python: 1,649,622; xml: 838,470; asm: 717,087; pascal: 185,708; sh: 88,786; perl: 88,718; objc: 79,984; sql: 59,811; cs: 42,452; fortran: 24,101; makefile: 21,144; tcl: 15,277; php: 14,022; yacc: 9,066; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,328; ada: 727; jsp: 228; sed: 36
file content (485 lines) | stat: -rw-r--r-- 17,014 bytes parent folder | download | duplicates (4)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/interaction/interactive_test_internal.h"

#include <iterator>
#include <memory>
#include <ostream>
#include <sstream>
#include <string_view>
#include <variant>
#include <vector>

#include "base/callback_list.h"
#include "base/check.h"
#include "base/containers/adapters.h"
#include "base/functional/bind.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/functional/overload.h"
#include "ui/base/interaction/element_identifier.h"
#include "ui/base/interaction/element_test_util.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/framework_specific_implementation.h"
#include "ui/gfx/native_ui_types.h"

namespace ui::test::internal {

namespace {

// Basic implementation of the framework for dumping generic elements.
class InteractiveTestPrivateFrameworkImpl
    : public InteractiveTestPrivateFrameworkBase {
 public:
  DECLARE_FRAMEWORK_SPECIFIC_METADATA()

  explicit InteractiveTestPrivateFrameworkImpl(
      InteractiveTestPrivate& test_impl)
      : InteractiveTestPrivateFrameworkBase(test_impl) {}
  ~InteractiveTestPrivateFrameworkImpl() override = default;

  std::vector<DebugTreeNode> DebugDumpElements(
      std::set<const ui::TrackedElement*>& elements) const override {
    std::vector<DebugTreeNode> nodes;
    for (auto* el : elements) {
      if (el->identifier() == kInteractiveTestPivotElementId) {
        nodes.insert(nodes.begin(),
                     DebugTreeNode("Pivot element (part of test automation)"));
      } else {
        nodes.emplace_back(
            base::StringPrintf("%s - %s at %s", el->GetImplementationName(),
                               el->identifier().GetName().c_str(),
                               DebugDumpBounds(el->GetScreenBounds())));
      }
    }
    elements.clear();
    return nodes;
  }

  std::string DebugDescribeContext(ui::ElementContext context) const override {
    std::ostringstream oss;
    oss << context;
    return oss.str();
  }
};

DEFINE_FRAMEWORK_SPECIFIC_METADATA(InteractiveTestPrivateFrameworkImpl)

}  // namespace

DEFINE_ELEMENT_IDENTIFIER_VALUE(kInteractiveTestPivotElementId);
DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kInteractiveTestPivotEventType);
DEFINE_STATE_IDENTIFIER_VALUE(PollingStateObserver<bool>,
                              kInteractiveTestPollUntilState);

StateObserverElement::StateObserverElement(ElementIdentifier id,
                                           ElementContext context)
    : TestElementBase(id, context) {}

StateObserverElement::~StateObserverElement() = default;

DEFINE_FRAMEWORK_SPECIFIC_METADATA(StateObserverElement)

// static
bool InteractiveTestPrivate::allow_interactive_test_verbs_ = false;

InteractiveTestPrivate::AdditionalContext::AdditionalContext() = default;

InteractiveTestPrivate::AdditionalContext::AdditionalContext(
    InteractiveTestPrivate& owner,
    intptr_t handle)
    : owner_(owner.GetAsWeakPtr()), handle_(handle) {
  CHECK(handle);
}

InteractiveTestPrivate::AdditionalContext::AdditionalContext(
    const AdditionalContext& other) = default;

InteractiveTestPrivate::AdditionalContext&
InteractiveTestPrivate::AdditionalContext::operator=(
    const AdditionalContext& other) = default;

InteractiveTestPrivate::AdditionalContext::~AdditionalContext() = default;

void InteractiveTestPrivate::AdditionalContext::Set(
    const std::string_view& additional_context) {
  auto* const owner = owner_.get();
  CHECK(owner) << "Set() should never be executed after destruction of the "
                  "owning sequence.";
  CHECK(handle_)
      << "Set() should never be executed on a default-constructed object.";
  owner_->additional_context_data_[handle_] = additional_context;
}

std::string InteractiveTestPrivate::AdditionalContext::Get() const {
  auto* const owner = owner_.get();
  CHECK(owner) << "Set() should never be executed after destruction of the "
                  "owning sequence.";
  CHECK(handle_)
      << "Set() should never be executed on a default-constructed object.";
  const auto it = owner_->additional_context_data_.find(handle_);
  return (it != owner_->additional_context_data_.end()) ? it->second
                                                        : std::string();
}

void InteractiveTestPrivate::AdditionalContext::Clear() {
  auto* const owner = owner_.get();
  CHECK(owner) << "Clear() should never be executed after destruction of the "
                  "owning sequence.";
  CHECK(handle_)
      << "Clear() should never be executed on a default-constructed object.";
  owner_->additional_context_data_.erase(handle_);
}

InteractiveTestPrivate::InteractiveTestPrivate() {
  MaybeRegisterFrameworkImpl<InteractiveTestPrivateFrameworkImpl>();
}

InteractiveTestPrivate::~InteractiveTestPrivate() = default;

void InteractiveTestPrivate::Init(ElementContext initial_context) {
  success_ = false;
  sequence_skipped_ = false;
  MaybeAddPivotElement(initial_context);
  for (ElementContext context :
       ElementTracker::GetElementTracker()->GetAllContextsForTesting()) {
    MaybeAddPivotElement(context);
  }
  context_subscription_ =
      ElementTracker::GetElementTracker()->AddAnyElementShownCallbackForTesting(
          base::BindRepeating(&InteractiveTestPrivate::OnElementAdded,
                              base::Unretained(this)));
}

void InteractiveTestPrivate::Cleanup() {
  context_subscription_ = base::CallbackListSubscription();
  pivot_elements_.clear();
}

void InteractiveTestPrivate::OnElementAdded(TrackedElement* el) {
  if (el->identifier() == kInteractiveTestPivotElementId)
    return;
  MaybeAddPivotElement(el->context());
}

void InteractiveTestPrivate::MaybeAddPivotElement(ElementContext context) {
  CHECK(context) << "Attempted to run steps in an invalid (null) context.";
  if (!pivot_elements_.contains(context)) {
    auto pivot =
        std::make_unique<TestElement>(kInteractiveTestPivotElementId, context);
    auto* const el = pivot.get();
    pivot_elements_.emplace(context, std::move(pivot));
    el->Show();
  }
}

base::WeakPtr<InteractiveTestPrivate> InteractiveTestPrivate::GetAsWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

gfx::NativeWindow InteractiveTestPrivate::GetNativeWindowFor(
    const ui::TrackedElement* el) const {
  for (auto& framework : framework_implementations_) {
    if (auto result = framework.GetNativeWindowFromElement(el)) {
      return result;
    }
  }
  for (auto& framework : framework_implementations_) {
    if (auto result = framework.GetNativeWindowFromContext(el->context())) {
      return result;
    }
  }
  return gfx::NativeWindow();
}

void InteractiveTestPrivate::HandleActionResult(
    InteractionSequence* seq,
    const TrackedElement* el,
    const std::string& operation_name,
    ActionResult result) {
  switch (result) {
    case ActionResult::kSucceeded:
      break;
    case ActionResult::kFailed:
      LOG(ERROR) << operation_name << " failed for " << *el;
      seq->FailForTesting();
      break;
    case ActionResult::kNotAttempted:
      LOG(ERROR) << operation_name << " could not be applied to " << *el;
      seq->FailForTesting();
      break;
    case ActionResult::kKnownIncompatible:
      LOG(WARNING) << operation_name
                   << " failed because it is unsupported on this platform for "
                   << *el;
      if (!on_incompatible_action_reason_.empty()) {
        LOG(WARNING) << "Unsupported action was expected: "
                     << on_incompatible_action_reason_;
      } else {
        LOG(ERROR) << "Unsupported action was unexpected. "
                      "Did you forget to call SetOnIncompatibleAction()?";
      }
      switch (on_incompatible_action_) {
        case OnIncompatibleAction::kFailTest:
          seq->FailForTesting();
          break;
        case OnIncompatibleAction::kSkipTest:
        case OnIncompatibleAction::kHaltTest:
          sequence_skipped_ = true;
          seq->FailForTesting();
          break;
        case OnIncompatibleAction::kIgnoreAndContinue:
          break;
      }
      break;
  }
}

TrackedElement* InteractiveTestPrivate::GetPivotElement(
    ElementContext context) const {
  const auto it = pivot_elements_.find(context);
  CHECK(it != pivot_elements_.end())
      << "Tried to reference non-existent context.";
  return it->second.get();
}

bool InteractiveTestPrivate::RemoveStateObserver(ElementIdentifier id,
                                                 ElementContext context) {
  using It = decltype(state_observer_elements_.begin());
  It found = state_observer_elements_.end();
  for (It it = state_observer_elements_.begin();
       it != state_observer_elements_.end(); ++it) {
    auto& entry = **it;
    if (entry.identifier() == id && (!context || entry.context() == context)) {
      CHECK(found == state_observer_elements_.end())
          << "RemoveStateObserver: Duplicate entries found for " << id;
      found = it;
    }
  }
  if (found == state_observer_elements_.end()) {
    LOG(ERROR) << "RemoveStateObserver: Entry not found for " << id;
    return false;
  }

  state_observer_elements_.erase(found);
  return true;
}

InteractiveTestPrivate::AdditionalContext
InteractiveTestPrivate::CreateAdditionalContext() {
  return AdditionalContext(*this, next_additional_context_handle_++);
}

std::vector<std::string> InteractiveTestPrivate::GetAdditionalContext() const {
  std::vector<std::string> entries;
  std::transform(additional_context_data_.begin(),
                 additional_context_data_.end(), std::back_inserter(entries),
                 [](const auto& entry) { return entry.second; });
  return entries;
}

void InteractiveTestPrivate::DoTestSetUp() {
  for (auto& framework : framework_implementations_) {
    framework.DoTestSetUp();
  }
}
void InteractiveTestPrivate::DoTestTearDown() {
  for (auto& framework : base::Reversed(framework_implementations_)) {
    framework.DoTestTearDown();
  }
  state_observer_elements_.clear();
}

void InteractiveTestPrivate::OnSequenceComplete() {
  for (auto& framework : base::Reversed(framework_implementations_)) {
    framework.OnSequenceComplete();
  }
  success_ = true;
}

void InteractiveTestPrivate::OnSequenceAborted(
    const InteractionSequence::AbortedData& data) {
  for (auto& framework : base::Reversed(framework_implementations_)) {
    framework.OnSequenceAborted(data);
  }
  if (aborted_callback_for_testing_) {
    std::move(aborted_callback_for_testing_).Run(data);
    return;
  }
  if (sequence_skipped_) {
    LOG(WARNING) << kInteractiveTestFailedMessagePrefix << data;
    if (on_incompatible_action_ == OnIncompatibleAction::kSkipTest) {
      GTEST_SKIP();
    } else {
      DCHECK_EQ(OnIncompatibleAction::kHaltTest, on_incompatible_action_);
    }
  } else {
    std::ostringstream additional_message;
    if (data.aborted_reason == InteractionSequence::AbortedReason::
                                   kElementHiddenBetweenTriggerAndStepStart) {
      additional_message
          << "\nNOTE: Please check for one of the following common mistakes:\n"
             " - A RunLoop whose type is not set to kNestableTasksAllowed. "
             "Change the type and try again.\n"
             " - A check being performed on an element that has been hidden. "
             "Wrap waiting for the hide and subsequent checks in a "
             "WithoutDelay() to avoid possible access-after-delete.";
    }
    const auto additional_context = GetAdditionalContext();
    if (!additional_context.empty()) {
      additional_message << "\nAdditional test context:";
      for (const auto& ctx : additional_context) {
        additional_message << "\n * " << ctx;
      }
    }
    DebugDumpElements(data.context).PrintTo(additional_message);
    GTEST_FAIL() << "Interactive test failed " << data
                 << additional_message.str();
  }
}

InteractiveTestPrivateFrameworkBase::InteractiveTestPrivateFrameworkBase(
    InteractiveTestPrivate& test_impl)
    : test_impl_(test_impl) {}
InteractiveTestPrivateFrameworkBase::~InteractiveTestPrivateFrameworkBase() =
    default;
InteractiveTestPrivateFrameworkBase::DebugTreeNode::DebugTreeNode() = default;
InteractiveTestPrivateFrameworkBase::DebugTreeNode::DebugTreeNode(
    std::string initial_text)
    : text(initial_text) {}
InteractiveTestPrivateFrameworkBase::DebugTreeNode::DebugTreeNode(
    DebugTreeNode&&) noexcept = default;
InteractiveTestPrivateFrameworkBase::DebugTreeNode&
InteractiveTestPrivateFrameworkBase::DebugTreeNode::operator=(
    DebugTreeNode&&) noexcept = default;
InteractiveTestPrivateFrameworkBase::DebugTreeNode::~DebugTreeNode() = default;

std::vector<InteractiveTestPrivateFrameworkBase::DebugTreeNode>
InteractiveTestPrivateFrameworkBase::DebugDumpElements(
    std::set<const ui::TrackedElement*>& el) const {
  return {};
}
std::string InteractiveTestPrivateFrameworkBase::DebugDescribeContext(
    ui::ElementContext context) const {
  return std::string();
}

// static
std::string InteractiveTestPrivateFrameworkBase::DebugDumpBounds(
    const gfx::Rect& bounds) {
  return base::StringPrintf("x:%d-%d y:%d-%d (%dx%d)", bounds.x(),
                            bounds.right(), bounds.y(), bounds.bottom(),
                            bounds.width(), bounds.height());
}

gfx::NativeWindow
InteractiveTestPrivateFrameworkBase::GetNativeWindowFromElement(
    const TrackedElement* el) const {
  // Default answer is "no window is associated with this element".
  // Other framework implementations will provide ways to convert specific
  // types of elements to their native windows.
  return gfx::NativeWindow();
}

gfx::NativeWindow
InteractiveTestPrivateFrameworkBase::GetNativeWindowFromContext(
    ElementContext) const {
  // Default answer is "no window is associated with this context".
  // Other framework implementations will provide ways to convert specific
  // contexts to their native windows.
  return gfx::NativeWindow();
}

namespace {
void PrintDebugTree(std::ostream& stream,
                    const InteractiveTestPrivate::DebugTreeNode& node,
                    std::string prefix,
                    bool last) {
  stream << prefix;
  if (prefix.empty()) {
    stream << "\n";
    prefix += "  ";
  } else {
    if (last) {
      stream << "╰─";
      prefix += "   ";
    } else {
      stream << "├─";
      prefix += "│  ";
    }
  }
  stream << node.text << '\n';
  for (size_t i = 0; i < node.children.size(); ++i) {
    const bool last_child = (i == node.children.size() - 1);
    PrintDebugTree(stream, node.children[i], prefix, last_child);
  }
}
}  // namespace

void InteractiveTestPrivate::DebugTreeNode::PrintTo(
    std::ostream& stream) const {
  PrintDebugTree(stream, *this, "", true);
}

InteractiveTestPrivate::DebugTreeNode InteractiveTestPrivate::DebugDumpElements(
    ui::ElementContext current_context) const {
  DebugTreeNode node("UI Elements");
  const auto* const tracker = ui::ElementTracker::GetElementTracker();
  for (const auto ctx : tracker->GetAllContextsForTesting()) {
    DebugTreeNode ctx_node = DebugDumpContext(ctx);
    if (ctx == current_context) {
      ctx_node.text = "[CURRENT CONTEXT] " + ctx_node.text;
    }
    node.children.emplace_back(std::move(ctx_node));
  }
  return node;
}

InteractiveTestPrivate::DebugTreeNode InteractiveTestPrivate::DebugDumpContext(
    ui::ElementContext context) const {
  std::string context_description;
  for (auto& framework_implementation :
       base::Reversed(framework_implementations_)) {
    context_description =
        framework_implementation.DebugDescribeContext(context);
    if (!context_description.empty()) {
      break;
    }
  }
  CHECK(!context_description.empty());
  DebugTreeNode node(context_description);
  auto element_list =
      ui::ElementTracker::GetElementTracker()->GetAllElementsForTesting(
          context);
  std::set<const ui::TrackedElement*> elements(element_list.begin(),
                                               element_list.end());
  std::vector<std::vector<DebugTreeNode>> temp;
  for (auto& framework_implementation :
       base::Reversed(framework_implementations_)) {
    temp.push_back(framework_implementation.DebugDumpElements(elements));
  }
  CHECK(elements.empty());
  for (auto& nodes : base::Reversed(temp)) {
    std::move(nodes.begin(), nodes.end(), std::back_inserter(node.children));
  }
  return node;
}
std::string DescribeElement(ElementSpecifier element) {
  std::ostringstream oss;
  oss << element;
  return oss.str();
}

InteractionSequence::Builder BuildSubsequence(
    InteractiveTestPrivate::MultiStep steps) {
  InteractionSequence::Builder builder;
  for (auto& step : steps) {
    builder.AddStep(std::move(step));
  }
  return builder;
}

}  // namespace ui::test::internal