1// Copyright (c) 2012 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.
4
5#ifndef CHROME_TEST_BASE_JAVASCRIPT_TEST_OBSERVER_H_
6#define CHROME_TEST_BASE_JAVASCRIPT_TEST_OBSERVER_H_
7
8#include <string>
9
10#include "base/compiler_specific.h"
11#include "content/public/browser/notification_observer.h"
12#include "content/public/browser/notification_registrar.h"
13
14namespace base {
15class DictionaryValue;
16}
17
18namespace content {
19class RenderViewHost;
20}
21
22// Base class for handling a stream of automation messages produced by a
23// JavascriptTestObserver.
24class TestMessageHandler {
25 public:
26  enum MessageResponse {
27    // Reset the timeout and keep running.
28    CONTINUE,
29    // Stop runnning.
30    DONE
31  };
32
33  TestMessageHandler();
34  virtual ~TestMessageHandler();
35
36  // Called when a message is received from the DOM automation controller.
37  virtual MessageResponse HandleMessage(const std::string& json) = 0;
38
39  void SetError(const std::string& message);
40
41  bool ok() const {
42    return ok_;
43  }
44
45  const std::string& error_message() const {
46    return error_message_;
47  }
48
49  // Prepare the handler to be used or reused.
50  virtual void Reset();
51
52 private:
53  bool ok_;
54  std::string error_message_;
55};
56
57// This class captures a stream of automation messages coming from a Javascript
58// test and dispatches them to a message handler.
59class JavascriptTestObserver : public content::NotificationObserver {
60 public:
61  // The observer does not own any arguments passed to it.  It is assumed that
62  // the arguments will outlive all uses of the observer.
63  JavascriptTestObserver(
64      content::RenderViewHost* render_view_host,
65      TestMessageHandler* handler);
66
67  virtual ~JavascriptTestObserver();
68
69  // Pump the message loop until the message handler indicates the Javascript
70  // test is done running.  Return true if the test jig functioned correctly and
71  // nothing timed out.
72  bool Run();
73
74  // Prepare the observer to be used again.  This method should NOT be called
75  // while Run() is pumping the message loop.
76  void Reset();
77
78  virtual void Observe(
79      int type,
80      const content::NotificationSource& source,
81      const content::NotificationDetails& details) OVERRIDE;
82
83 private:
84  // This message did not signal the end of a test, keep going.
85  void Continue();
86
87  // This was the last message we care about, stop listening for more messages.
88  void EndTest();
89
90  TestMessageHandler* handler_;
91  bool running_;
92  bool finished_;
93  content::NotificationRegistrar registrar_;
94
95  DISALLOW_COPY_AND_ASSIGN(JavascriptTestObserver);
96};
97
98#endif  // CHROME_TEST_BASE_JAVASCRIPT_TEST_OBSERVER_H_
99