File: graph_test_harness.h

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 (377 lines) | stat: -rw-r--r-- 14,600 bytes parent folder | download | duplicates (9)
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
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_PERFORMANCE_MANAGER_TEST_SUPPORT_GRAPH_TEST_HARNESS_H_
#define COMPONENTS_PERFORMANCE_MANAGER_TEST_SUPPORT_GRAPH_TEST_HARNESS_H_

#include <stdint.h>

#include <memory>
#include <string>
#include <utility>

#include "base/check_op.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/test/task_environment.h"
#include "components/performance_manager/embedder/graph_features.h"
#include "components/performance_manager/graph/frame_node_impl.h"
#include "components/performance_manager/graph/graph_impl.h"
#include "components/performance_manager/graph/node_base.h"
#include "components/performance_manager/graph/page_node_impl.h"
#include "components/performance_manager/graph/process_node_impl.h"
#include "components/performance_manager/graph/system_node_impl.h"
#include "components/performance_manager/graph/worker_node_impl.h"
#include "components/performance_manager/public/browser_child_process_host_id.h"
#include "components/performance_manager/public/browser_child_process_host_proxy.h"
#include "components/performance_manager/public/render_process_host_id.h"
#include "components/performance_manager/public/render_process_host_proxy.h"
#include "content/public/browser/browsing_instance_id.h"
#include "content/public/test/browser_task_environment.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/tokens/tokens.h"
#include "url/origin.h"

namespace content {
class WebContents;
}

namespace performance_manager {

// Returns a unique frame routing ID to use for test FrameNodes. The generated
// id is not guaranteed to be different from ids set explicitly by the test.
int NextTestFrameRoutingId();

// Returns a unique RenderProcessHostId to use for test ProcessNodes. The
// generated id is not guaranteed to be different from ids set explicitly by the
// test.
RenderProcessHostId NextTestRenderProcessHostId();

// Returns a unique BrowserChildProcessHostId to use for test ProcessNodes. The
// generated id is not guaranteed to be different from ids set explicitly by the
// test.
BrowserChildProcessHostId NextTestBrowserChildProcessHostId();

template <class NodeClass>
class TestNodeWrapper {
 public:
  struct Factory;

  template <typename... Args>
  static TestNodeWrapper<NodeClass> Create(GraphImpl* graph, Args&&... args);

  TestNodeWrapper() = default;

  explicit TestNodeWrapper(std::unique_ptr<NodeClass> impl)
      : impl_(std::move(impl)) {
    DCHECK(impl_.get());
  }

  TestNodeWrapper(TestNodeWrapper&& other) : impl_(std::move(other.impl_)) {}
  TestNodeWrapper& operator=(TestNodeWrapper&& other) {
    if (this != &other) {
      reset();
      impl_ = std::move(other.impl_);
    }
    return *this;
  }

  TestNodeWrapper(const TestNodeWrapper& other) = delete;
  TestNodeWrapper& operator=(const TestNodeWrapper& other) = delete;

  ~TestNodeWrapper() { reset(); }

  NodeClass* operator->() const { return impl_.get(); }

  NodeClass* get() const { return impl_.get(); }

  void reset() {
    if (impl_) {
      impl_->graph()->RemoveNode(impl_.get());
      impl_.reset();
    }
  }

 private:
  std::unique_ptr<NodeClass> impl_;
};

template <class NodeClass>
struct TestNodeWrapper<NodeClass>::Factory {
  template <typename... Args>
  static std::unique_ptr<NodeClass> Create(Args&&... args) {
    return std::make_unique<NodeClass>(std::forward<Args>(args)...);
  }
};

// A specialized factory function for frame nodes that helps fill out some
// common values.
template <>
struct TestNodeWrapper<FrameNodeImpl>::Factory {
  static std::unique_ptr<FrameNodeImpl> Create(
      ProcessNodeImpl* process_node,
      PageNodeImpl* page_node,
      FrameNodeImpl* parent_frame_node,
      FrameNodeImpl* outer_document_for_fenced_frame,
      int render_frame_id,
      const blink::LocalFrameToken& frame_token = blink::LocalFrameToken(),
      content::BrowsingInstanceId browsing_instance_id =
          content::BrowsingInstanceId(0),
      content::SiteInstanceGroupId site_instance_group_id =
          content::SiteInstanceGroupId(0),
      bool is_current = true) {
    return std::make_unique<FrameNodeImpl>(
        process_node, page_node, parent_frame_node,
        outer_document_for_fenced_frame, render_frame_id, frame_token,
        browsing_instance_id, site_instance_group_id, is_current);
  }
};

// A specialized factory function for ProcessNodes that provides an
// autogenerated proxy as needed.
template <>
struct TestNodeWrapper<ProcessNodeImpl>::Factory {
  // Creates a ProcessNode for the browser process.
  static std::unique_ptr<ProcessNodeImpl> Create(BrowserProcessNodeTag tag) {
    return std::make_unique<ProcessNodeImpl>(tag);
  }

  // Creates a ProcessNode for a renderer process.
  //
  // Note that Create() with no arguments calls this, which can be confusing:
  // prefer GraphTestHarness::CreateRendererProcessNode(). The production
  // equivalent, PerformanceManager::CreateNodeImpl(), has no default argument
  // which makes it more clear that CreateNodeImpl(RenderProcessHostProxy(...))
  // creates a renderer node.
  static std::unique_ptr<ProcessNodeImpl> Create(
      RenderProcessHostProxy proxy = RenderProcessHostProxy()) {
    // Create a proxy if the caller didn't pass a valid one.
    if (!proxy.is_valid()) {
      proxy = RenderProcessHostProxy::CreateForTesting(
          NextTestRenderProcessHostId());
    }
    return std::make_unique<ProcessNodeImpl>(std::move(proxy),
                                             base::TaskPriority::HIGHEST);
  }

  // Creates a ProcessNode for a non-renderer child process.
  static std::unique_ptr<ProcessNodeImpl> Create(
      content::ProcessType process_type,
      BrowserChildProcessHostProxy proxy = BrowserChildProcessHostProxy()) {
    // To create a browser ProcessNode, use Create(BrowserProcessNodeTag{}) or
    // GraphTestHarness::CreateBrowserProcessNode().
    CHECK_NE(process_type, content::PROCESS_TYPE_BROWSER);
    // To create a renderer ProcessNode, use Create() or
    // GraphTestHarness::CreateRendererProcessNode().
    CHECK_NE(process_type, content::PROCESS_TYPE_RENDERER);
    // Create a proxy if the caller didn't pass a valid one.
    if (!proxy.is_valid()) {
      proxy = BrowserChildProcessHostProxy::CreateForTesting(
          NextTestBrowserChildProcessHostId());
    }
    return std::make_unique<ProcessNodeImpl>(process_type, std::move(proxy));
  }
};

// A specialized factory function for page nodes that helps fill out some
// common values.
template <>
struct TestNodeWrapper<PageNodeImpl>::Factory {
  static std::unique_ptr<PageNodeImpl> Create(
      base::WeakPtr<content::WebContents> web_contents = nullptr,
      const std::string& browser_context_id = std::string(),
      const GURL& url = GURL(),
      PagePropertyFlags initial_property_flags = {},
      base::TimeTicks visibility_change_time = base::TimeTicks::Now()) {
    return std::make_unique<PageNodeImpl>(
        std::move(web_contents), browser_context_id, url,
        initial_property_flags, visibility_change_time);
  }
};

// A specialized factory function for worker nodes that helps fill out some
// common values.
template <>
struct TestNodeWrapper<WorkerNodeImpl>::Factory {
  static std::unique_ptr<WorkerNodeImpl> Create(
      WorkerNode::WorkerType worker_type,
      ProcessNodeImpl* process_node,
      const std::string& browser_context_id = std::string(),
      const blink::WorkerToken& token = blink::WorkerToken(),
      const url::Origin& origin = url::Origin()) {
    return std::make_unique<WorkerNodeImpl>(browser_context_id, worker_type,
                                            process_node, token, origin);
  }
};

// static
template <typename NodeClass>
template <typename... Args>
TestNodeWrapper<NodeClass> TestNodeWrapper<NodeClass>::Create(GraphImpl* graph,
                                                              Args&&... args) {
  // Dispatch to a helper so that we can use partial specialization.
  std::unique_ptr<NodeClass> node =
      Factory::Create(std::forward<Args>(args)...);
  graph->AddNewNode(node.get());
  return TestNodeWrapper<NodeClass>(std::move(node));
}

// This specialization is necessary because the graph has ownership of the
// system node as it's a singleton. For the other node types the test wrapper
// manages the node lifetime.
template <>
class TestNodeWrapper<SystemNodeImpl> {
 public:
  static TestNodeWrapper<SystemNodeImpl> Create(GraphImpl* graph) {
    return TestNodeWrapper<SystemNodeImpl>(graph->GetSystemNodeImpl());
  }

  explicit TestNodeWrapper(SystemNodeImpl* impl) : impl_(impl) {}
  TestNodeWrapper(TestNodeWrapper&& other) : impl_(other.impl_) {}

  TestNodeWrapper(const TestNodeWrapper&) = delete;
  TestNodeWrapper& operator=(const TestNodeWrapper&) = delete;

  ~TestNodeWrapper() { reset(); }

  SystemNodeImpl* operator->() const { return impl_; }
  SystemNodeImpl* get() const { return impl_; }

  void reset() { impl_ = nullptr; }

 private:
  raw_ptr<SystemNodeImpl> impl_;
};

class TestGraphImpl : public GraphImpl {
 public:
  TestGraphImpl();
  ~TestGraphImpl() override;

  // Creates a frame node with an automatically generated routing id, different
  // from previously generated routing ids. Useful for tests that don't care
  // about the frame routing id but need to avoid collisions in
  // |GraphImpl::frames_by_id_|. Caveat: The generated routing id is not
  // guaranteed to be different from routing ids set explicitly by the test.
  TestNodeWrapper<FrameNodeImpl> CreateFrameNodeAutoId(
      ProcessNodeImpl* process_node,
      PageNodeImpl* page_node,
      FrameNodeImpl* parent_frame_node = nullptr,
      content::BrowsingInstanceId browsing_instance_id =
          content::BrowsingInstanceId());

  // Wrappers around Create<ProcessNodeImpl>(...) that make the type of process
  // more clear.
  TestNodeWrapper<ProcessNodeImpl> CreateBrowserProcessNode();
  TestNodeWrapper<ProcessNodeImpl> CreateRendererProcessNode(
      RenderProcessHostProxy proxy = RenderProcessHostProxy());
  TestNodeWrapper<ProcessNodeImpl> CreateBrowserChildProcessNode(
      content::ProcessType process_type = content::PROCESS_TYPE_UTILITY,
      BrowserChildProcessHostProxy proxy = BrowserChildProcessHostProxy());
};

// A test harness that initializes the graph without the rest of
// PerformanceManager. Allows for creating individual nodes without going
// through an embedder. The structs in mock_graphs.h are useful for this.
//
// This is intended for testing code that is entirely bound to the
// PerformanceManager sequence. Since the PerformanceManager itself is not
// initialized messages posted using CallOnGraph or
// PerformanceManager::GetTaskRunner will go into the void. To test code that
// posts to and from the PerformanceManager sequence use
// PerformanceManagerTestHarness.
//
// If you need to write tests that manipulate graph nodes and also use
// CallOnGraph, you probably want to split the code under test into a
// sequence-bound portion that deals with the graph (tested using
// GraphTestHarness) and an interface that marshals to the PerformanceManager
// sequence (tested using PerformanceManagerTestHarness).
class GraphTestHarness : public ::testing::Test {
 public:
  GraphTestHarness();
  ~GraphTestHarness() override;

  // Optional constructor for directly configuring the BrowserTaskEnvironment.
  template <class... ArgTypes>
  explicit GraphTestHarness(ArgTypes... args)
      : task_env_(args...), graph_(new TestGraphImpl()) {}

  template <class NodeClass, typename... Args>
  TestNodeWrapper<NodeClass> CreateNode(Args&&... args) {
    return TestNodeWrapper<NodeClass>::Create(graph(),
                                              std::forward<Args>(args)...);
  }

  TestNodeWrapper<FrameNodeImpl> CreateFrameNodeAutoId(
      ProcessNodeImpl* process_node,
      PageNodeImpl* page_node,
      FrameNodeImpl* parent_frame_node = nullptr,
      content::BrowsingInstanceId browsing_instance_id =
          content::BrowsingInstanceId()) {
    return graph()->CreateFrameNodeAutoId(
        process_node, page_node, parent_frame_node, browsing_instance_id);
  }

  TestNodeWrapper<ProcessNodeImpl> CreateBrowserProcessNode() {
    return graph()->CreateBrowserProcessNode();
  }

  TestNodeWrapper<ProcessNodeImpl> CreateRendererProcessNode(
      RenderProcessHostProxy proxy = RenderProcessHostProxy()) {
    return graph()->CreateRendererProcessNode(std::move(proxy));
  }

  TestNodeWrapper<ProcessNodeImpl> CreateBrowserChildProcessNode(
      content::ProcessType process_type = content::PROCESS_TYPE_UTILITY,
      BrowserChildProcessHostProxy proxy = BrowserChildProcessHostProxy()) {
    return graph()->CreateBrowserChildProcessNode(process_type,
                                                  std::move(proxy));
  }

  TestNodeWrapper<SystemNodeImpl> GetSystemNode() {
    return TestNodeWrapper<SystemNodeImpl>(graph()->GetSystemNodeImpl());
  }

  // testing::Test:
  void SetUp() override;
  void TearDown() override;

  // Allows configuring which Graph features are initialized during "SetUp".
  // This defaults to initializing no features. Features will be initialized
  // before "OnGraphCreated" is called.
  GraphFeatures& GetGraphFeatures() { return graph_features_; }

  // A callback that will be invoked as part of the graph initialization
  // during "SetUp". The same effect can be had by overriding "SetUp" in this
  // case, because the graph lives on the same sequence as this fixture.
  // However, to keep the various PM and Graph test fixtures similar in usage,
  // this seam has been exposed.
  virtual void OnGraphCreated(GraphImpl* graph) {}

 protected:
  void AdvanceClock(base::TimeDelta delta) { task_env_.FastForwardBy(delta); }

  content::BrowserTaskEnvironment& task_env() { return task_env_; }
  TestGraphImpl* graph() {
    DCHECK(graph_.get());
    return graph_.get();
  }

  // Manually tears down the graph. Useful for DEATH tests that deliberately
  // violate graph invariants.
  void TearDownAndDestroyGraph();

 private:
  GraphFeatures graph_features_;
  content::BrowserTaskEnvironment task_env_;
  std::unique_ptr<TestGraphImpl> graph_;

  // Detects when the test fixture is being misused.
  bool setup_called_ = false;
  bool teardown_called_ = false;
};

}  // namespace performance_manager

#endif  // COMPONENTS_PERFORMANCE_MANAGER_TEST_SUPPORT_GRAPH_TEST_HARNESS_H_