File: interactive_test_internal.h

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 (492 lines) | stat: -rw-r--r-- 17,780 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
486
487
488
489
490
491
492
// 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.

#ifndef UI_BASE_INTERACTION_INTERACTIVE_TEST_INTERNAL_H_
#define UI_BASE_INTERACTION_INTERACTIVE_TEST_INTERNAL_H_

#include <algorithm>
#include <concepts>
#include <functional>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <variant>

#include "base/callback_list.h"
#include "base/containers/contains.h"
#include "base/gtest_prod_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/no_destructor.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/rectify_callback.h"
#include "base/types/is_instantiation.h"
#include "base/types/pass_key.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.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/base/interaction/interaction_sequence.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/base/interaction/interactive_test_definitions.h"
#include "ui/base/interaction/state_observer.h"
#include "ui/gfx/geometry/rect.h"

class ChromeOSTestLauncherDelegate;
class InteractiveUITestSuite;

namespace ui::test {

class InteractiveTestApi;
class InteractiveTestTest;

namespace internal {

// Element that is present during interactive tests that actions can bounce
// events off of.
DECLARE_ELEMENT_IDENTIFIER_VALUE(kInteractiveTestPivotElementId);
DECLARE_CUSTOM_ELEMENT_EVENT_TYPE(kInteractiveTestPivotEventType);

extern const char kInteractiveTestFailedMessagePrefix[];
extern const char kNoCheckDescriptionSpecified[];

class StateObserverElement;

// Class that implements functionality for InteractiveTest* that should be
// hidden from tests that inherit the API.
class InteractiveTestPrivate {
 public:
  using MultiStep = internal::MultiStep;

  // Describes what should happen when an action isn't compatible with the
  // current build, platform, or environment. For example, not all tests are set
  // up to handle screenshots, and some Linux window managers cannot bring a
  // background window to the front.
  //
  // See chrome/test/interaction/README.md for best practices.
  enum class OnIncompatibleAction {
    // The test should fail. This is the default, and should be used in almost
    // all cases.
    kFailTest,
    // The sequence should abort immediately and the test should be skipped.
    // Use this when the remainder of the test would depend on the result of the
    // incompatible step. Good for smoke/regression tests that have known
    // incompatibilities but still need to be run in as many environments as
    // possible.
    kSkipTest,
    // As `kSkipTest`, but instead of marking the test as skipped, just stops
    // the test sequence. This is useful when the test cannot continue past the
    // problematic step, but you also want to preserve any non-fatal errors that
    // may have occurred up to that point (or check any conditions after the
    // test stops).
    kHaltTest,
    // The failure should be ignored and the test should continue.
    // Use this when the step does not affect the outcome of the test, such as
    // taking an incidental screenshot in a test job that doesn't support
    // screenshots.
    kIgnoreAndContinue,
  };

  // Provides a copyable handle to some test state that can be output in the
  // event of a test failure. The context will persist until `End()` is called
  // or the test ends.
  //
  // Example:
  // ```
  //   auto MyVerb() {
  //     AdditionalContext context = CreateAdditionalContext();
  //     return Steps(
  //
  //       // Set the context. Note the use of the `mutable` keyword:
  //       AfterShow(..., [context]() mutable {
  //         context.Set(...);
  //       }),
  //
  //       // Context is still valid here, even if it's not modified.
  //       WithElement(..., [](ui::TrackedElement*) {
  //         ...
  //       }),
  //
  //       Do([context]() { context.End(); })
  //
  //       // Since no more steps reference `context` it is no longer valid
  //       // here; if the test were to fail, no additional information would
  //       // be printed.
  //       PressButton(...));
  //   }
  // ```
  class AdditionalContext {
   public:
    AdditionalContext();
    AdditionalContext(const AdditionalContext& other);
    AdditionalContext& operator=(const AdditionalContext& other);
    ~AdditionalContext();

    // Adds or replaces the existing value with `additional_context`. Until this
    // is called, nothing will be stored or output.
    void Set(const std::string_view& additional_context);

    // Fetches the current value of the context.
    std::string Get() const;

    // Removes the context.
    void Clear();

   private:
    friend InteractiveTestPrivate;

    // Creates a new context with the given `owner` and `handle`.
    AdditionalContext(InteractiveTestPrivate& owner, intptr_t handle);

    base::WeakPtr<InteractiveTestPrivate> owner_;
    intptr_t handle_ = 0;
  };

  explicit InteractiveTestPrivate(
      std::unique_ptr<InteractionTestUtil> test_util);
  virtual ~InteractiveTestPrivate();
  InteractiveTestPrivate(const InteractiveTestPrivate&) = delete;
  void operator=(const InteractiveTestPrivate&) = delete;

  InteractionTestUtil& test_util() { return *test_util_; }

  OnIncompatibleAction on_incompatible_action() const {
    return on_incompatible_action_;
  }

  bool sequence_skipped() const { return sequence_skipped_; }

  base::WeakPtr<InteractiveTestPrivate> GetAsWeakPtr();

  // Possibly fails or skips a sequence based on the result of an action
  // simulation.
  void HandleActionResult(InteractionSequence* seq,
                          const TrackedElement* el,
                          const std::string& operation_name,
                          ActionResult result);

  // Gets the pivot element for the specified context, which must exist.
  TrackedElement* GetPivotElement(ElementContext context) const;

  // Adds `state_observer` and associates it with an element with identifier
  // `id` and context `context`. Must be unique in its context.
  // Returns true on success.
  template <typename Observer, typename V = Observer::ValueType>
  bool AddStateObserver(ElementIdentifier id,
                        ElementContext context,
                        std::unique_ptr<Observer> state_observer);

  // Removes `StateObserver` with identifier `id` in `context`; if the context
  // is null, assumes there is exactly one matching observer in some context.
  // Returns true on success.
  bool RemoveStateObserver(ElementIdentifier id, ElementContext context);

  // Creates an additional context that will persist as long as copies of the
  // context exist.
  [[nodiscard]] AdditionalContext CreateAdditionalContext();

  // Gets a string representation of the current additional context for this
  // test.
  std::vector<std::string> GetAdditionalContext() const;

  // Call this method during test SetUp(), or SetUpOnMainThread() for browser
  // tests.
  virtual void DoTestSetUp();

  // Call this method during test TearDown(), or TearDownOnMainThread() for
  // browser tests.
  virtual void DoTestTearDown();

  // Called when the sequence ends, but before we break out of the run loop
  // in RunTestSequenceImpl().
  virtual void OnSequenceComplete();
  virtual void OnSequenceAborted(const InteractionSequence::AbortedData& data);

  // Sets a callback that is called if the test sequence fails instead of
  // failing the current test. Should only be called in tests that are testing
  // InteractiveTestApi or descendant classes.
  void set_aborted_callback_for_testing(
      InteractionSequence::AbortedCallback aborted_callback_for_testing) {
    aborted_callback_for_testing_ = std::move(aborted_callback_for_testing);
  }

  // The following are the classes allowed to set the "allow interactive test
  // verbs" flag.
  template <typename T>
    requires std::same_as<T, ui::test::InteractiveTestTest> ||
             std::same_as<T, ChromeOSTestLauncherDelegate> ||
             std::same_as<T, InteractiveUITestSuite>
  static void set_interactive_test_verbs_allowed(base::PassKey<T>) {
    allow_interactive_test_verbs_ = true;
  }

  // Represents a node in a debug tree of UI elements that can be pretty-
  // printed.
  struct DebugTreeNode {
    DebugTreeNode();
    explicit DebugTreeNode(std::string initial_text);
    DebugTreeNode(DebugTreeNode&& other) noexcept;
    DebugTreeNode& operator=(DebugTreeNode&& other) noexcept;
    ~DebugTreeNode();

    std::string text;
    std::vector<DebugTreeNode> children;

    void PrintTo(std::ostream& stream) const;
  };

 protected:
  // Dumps the entire tree of named elements. Default implementation organizes
  // all elements by context. This is the entry point when printing test failure
  // information. The `current_context` is the current context in the test, if
  // known.
  virtual DebugTreeNode DebugDumpElements(
      ui::ElementContext current_context) const;

  // Dumps the contents of a particular context.
  virtual DebugTreeNode DebugDumpContext(
      const ui::ElementContext context) const;

  // Dumps the context of a particular element.
  virtual DebugTreeNode DebugDumpElement(const ui::TrackedElement* el) const;

  // Provides the top-level description for a context.
  virtual std::string DebugDescribeContext(ui::ElementContext context) const;

  // Gets a verbose string representation of a set of `bounds` for debug
  // purposes.
  virtual std::string DebugDumpBounds(const gfx::Rect& bounds) const;

 private:
  friend class ui::test::InteractiveTestTest;
  friend class ui::test::InteractiveTestApi;

  // Prepare for a sequence to start.
  void Init(ElementContext initial_context);

  // Clean up after a sequence.
  void Cleanup();

  // Note when a new element appears; we may update the context list.
  void OnElementAdded(TrackedElement* el);

  // Maybe adds a pivot element for the given context.
  void MaybeAddPivotElement(ElementContext context);

  // Tracks whether a sequence succeeded or failed.
  bool success_ = false;

  // Specifies how an incompatible action should be handled.
  OnIncompatibleAction on_incompatible_action_ =
      OnIncompatibleAction::kFailTest;
  std::string on_incompatible_action_reason_;

  // Tracks whether a sequence is skipped. Will only be set if
  // `skip_on_unsupported_operation` is true.
  bool sequence_skipped_ = false;

  // Used to simulate input to UI elements.
  std::unique_ptr<InteractionTestUtil> test_util_;

  // Used to keep track of valid contexts.
  base::CallbackListSubscription context_subscription_;

  // Used to track state observers and their associated elements.
  std::vector<std::unique_ptr<StateObserverElement>> state_observer_elements_;

  // Used to relay events to trigger follow-up steps.
  std::map<ElementContext, std::unique_ptr<TrackedElement>> pivot_elements_;

  // Overrides the default test failure behavior to test the API itself.
  InteractionSequence::AbortedCallback aborted_callback_for_testing_;

  intptr_t next_additional_context_handle_ = 1U;
  std::map<intptr_t, std::string> additional_context_data_;

  base::WeakPtrFactory<InteractiveTestPrivate> weak_ptr_factory_{this};

  // Whether interactive test verbs are allowed. See
  // `InteractiveTestApi::RequireInteractiveTest()` for more info.
  static bool allow_interactive_test_verbs_;
};

class StateObserverElement : public TestElementBase {
 public:
  StateObserverElement(ElementIdentifier id, ElementContext context);
  ~StateObserverElement() override;

  DECLARE_FRAMEWORK_SPECIFIC_METADATA()
};

// Implements an element that is shown when an observed state matches a desired
// value or pattern, and hidden when it does not.
template <typename T>
class StateObserverElementT : public StateObserverElement {
 public:
  // A lookup table is provided per value of `T`.
  using LookupTable = std::map<std::pair<ElementIdentifier, ElementContext>,
                               StateObserverElementT<T>*>;
  using TestContext = InteractiveTestPrivate::AdditionalContext;

  // Specify the `id` and `context` of the element to be created, as well as the
  // associated `observer` which will be linked to this element.
  StateObserverElementT(ElementIdentifier id,
                        ElementContext context,
                        std::unique_ptr<StateObserver<T>> observer,
                        TestContext test_context)
      : StateObserverElement(id, context),
        test_context_(test_context),
        current_value_(observer->GetStateObserverInitialState()),
        observer_(std::move(observer)) {
    auto& table = GetLookupTable();
    CHECK(!base::Contains(table, std::make_pair(id, context)))
        << "Duplicate ID + context for StateObserver not allowed: " << id
        << ", " << context;
    table.emplace(std::make_pair(id, context), this);
    observer_->SetStateObserverStateChangedCallback(base::BindRepeating(
        &StateObserverElementT::OnStateChanged, base::Unretained(this)));
    OnStateChanged(current_value_);
  }
  ~StateObserverElementT() override {
    CHECK(GetLookupTable().erase(std::make_pair(identifier(), context())));
  }

  void SetTarget(testing::Matcher<T> target) {
    target_value_ = std::move(target);
    UpdateVisibility();
  }

  // Helper method that looks up an element based on `id`, `context`, and
  // whether `seq` allows all contexts to be searched. Fails the sequence if the
  // element is not found.
  static StateObserverElementT<T>* LookupElement(ElementIdentifier id,
                                                 ElementContext context,
                                                 bool search_all_contexts) {
    const auto& lookup_table = GetLookupTable();
    const auto it = lookup_table.find(std::make_pair(id, context));
    if (it != lookup_table.end()) {
      return it->second;
    }

    if (search_all_contexts) {
      for (const auto& [key, ptr] : lookup_table) {
        if (key.first == id) {
          return ptr;
        }
      }
    }

    return nullptr;
  }

  const T& current_value() const { return current_value_; }

 private:
  void OnStateChanged(T new_state) {
    current_value_ = new_state;
    UpdateVisibility();
  }

  void UpdateVisibility() {
    testing::StringMatchResultListener listener;
    if (target_value_ &&
        target_value_->MatchAndExplain(current_value_, &listener)) {
      test_context_.Clear();
      Show();
    } else {
      std::ostringstream oss;
      oss << "Waiting for state " << identifier() << " " << listener.str();
      test_context_.Set(oss.str());
      Hide();
    }
  }

  // Fetch the lookup table associated with a value type/template instantiation.
  //
  // This table does not own the instances, just tracks them as long as they are
  // alive and allows them to be retrieved. There is one static table per
  // template instantiation due to the use of `base::NoDestructor`,
  static LookupTable& GetLookupTable() {
    static base::NoDestructor<LookupTable> lookup_table;
    return *lookup_table;
  }

 private:
  // Since the context can be updated on observer shutdown and needs access to
  // the current value, it needs to be destructed last.
  TestContext test_context_;
  T current_value_;
  std::optional<testing::Matcher<T>> target_value_;
  std::unique_ptr<StateObserver<T>> observer_;
};

// Applies `matcher` to `value` and returns the result; on failure a useful
// error message is printed using `test_name`, `value`, and `matcher`.
//
// Steps which use this method will fail if it returns false, printing out the
// details of the step in the usual way.
template <typename T, typename V = std::decay_t<T>>
bool MatchAndExplain(std::string_view test_name,
                     const testing::Matcher<V>& matcher,
                     const T& value) {
  testing::StringMatchResultListener listener;
  if (matcher.MatchAndExplain(value, &listener)) {
    return true;
  }
  std::ostringstream oss;
  oss << test_name << " failed.\nExpected: ";
  matcher.DescribeTo(&oss);
  oss << "\nActual: " << testing::PrintToString(value);
  if (!listener.str().empty()) {
    oss << "\n" << listener.str();
  }
  LOG(ERROR) << oss.str();
  return false;
}

template <typename Observer, typename V>
bool InteractiveTestPrivate::AddStateObserver(
    ElementIdentifier id,
    ElementContext context,
    std::unique_ptr<Observer> state_observer) {
  CHECK(id);
  CHECK(context);
  for (const auto& existing : state_observer_elements_) {
    if (existing->identifier() == id && existing->context() == context) {
      LOG(ERROR) << "AddStateObserver: Duplicate observer added for " << id;
      return false;
    }
  }
  state_observer_elements_.emplace_back(
      std::make_unique<StateObserverElementT<V>>(
          id, context, std::move(state_observer), CreateAdditionalContext()));
  return true;
}

}  // namespace internal

}  // namespace ui::test

inline ui::test::internal::MultiStep& operator+=(
    ui::test::internal::MultiStep& steps,
    ui::InteractionSequence::StepBuilder&& step) {
  steps.push_back(std::move(step));
  return steps;
}

inline ui::test::internal::MultiStep& operator+=(
    ui::test::internal::MultiStep& steps,
    ui::test::internal::MultiStep&& other) {
  std::ranges::move(other, std::back_inserter(steps));
  return steps;
}

#endif  // UI_BASE_INTERACTION_INTERACTIVE_TEST_INTERNAL_H_