Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / content / public / test / javascript_test_observer.h
blob979d920ff61b418f0c41f5166ada7db55c51f1eb
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_
6 #define CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_
8 #include <string>
10 #include "base/compiler_specific.h"
11 #include "content/public/browser/notification_observer.h"
12 #include "content/public/browser/notification_registrar.h"
14 namespace base {
15 class DictionaryValue;
18 namespace content {
19 class WebContents;
21 // Base class for handling a stream of automation messages produced by a
22 // JavascriptTestObserver.
23 class TestMessageHandler {
24 public:
25 enum MessageResponse {
26 // Reset the timeout and keep running.
27 CONTINUE,
28 // Stop runnning.
29 DONE
32 TestMessageHandler();
33 virtual ~TestMessageHandler();
35 // Called when a message is received from the DOM automation controller.
36 virtual MessageResponse HandleMessage(const std::string& json) = 0;
38 void SetError(const std::string& message);
40 bool ok() const {
41 return ok_;
44 const std::string& error_message() const {
45 return error_message_;
48 // Prepare the handler to be used or reused.
49 virtual void Reset();
51 private:
52 bool ok_;
53 std::string error_message_;
56 // This class captures a stream of automation messages coming from a Javascript
57 // test and dispatches them to a message handler.
58 class JavascriptTestObserver : public NotificationObserver {
59 public:
60 // The observer does not own any arguments passed to it. It is assumed that
61 // the arguments will outlive all uses of the observer.
62 JavascriptTestObserver(WebContents* web_contents,
63 TestMessageHandler* handler);
65 ~JavascriptTestObserver() override;
67 // Pump the message loop until the message handler indicates the Javascript
68 // test is done running. Return true if the test jig functioned correctly and
69 // nothing timed out.
70 bool Run();
72 // Prepare the observer to be used again. This method should NOT be called
73 // while Run() is pumping the message loop.
74 void Reset();
76 void Observe(int type,
77 const NotificationSource& source,
78 const NotificationDetails& details) override;
80 private:
81 // This message did not signal the end of a test, keep going.
82 void Continue();
84 // This was the last message we care about, stop listening for more messages.
85 void EndTest();
87 TestMessageHandler* handler_;
88 bool running_;
89 bool finished_;
90 NotificationRegistrar registrar_;
92 DISALLOW_COPY_AND_ASSIGN(JavascriptTestObserver);
95 } // namespace content
97 #endif // CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_