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. 4 5#ifndef CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_ 6#define CONTENT_PUBLIC_TEST_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 WebContents; 20 21// Base class for handling a stream of automation messages produced by a 22// JavascriptTestObserver. 23class TestMessageHandler { 24 public: 25 enum MessageResponse { 26 // Reset the timeout and keep running. 27 CONTINUE, 28 // Stop runnning. 29 DONE 30 }; 31 32 TestMessageHandler(); 33 virtual ~TestMessageHandler(); 34 35 // Called when a message is received from the DOM automation controller. 36 virtual MessageResponse HandleMessage(const std::string& json) = 0; 37 38 void SetError(const std::string& message); 39 40 bool ok() const { 41 return ok_; 42 } 43 44 const std::string& error_message() const { 45 return error_message_; 46 } 47 48 // Prepare the handler to be used or reused. 49 virtual void Reset(); 50 51 private: 52 bool ok_; 53 std::string error_message_; 54}; 55 56// This class captures a stream of automation messages coming from a Javascript 57// test and dispatches them to a message handler. 58class 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); 64 65 virtual ~JavascriptTestObserver(); 66 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(); 71 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(); 75 76 virtual void Observe( 77 int type, 78 const NotificationSource& source, 79 const NotificationDetails& details) OVERRIDE; 80 81 private: 82 // This message did not signal the end of a test, keep going. 83 void Continue(); 84 85 // This was the last message we care about, stop listening for more messages. 86 void EndTest(); 87 88 TestMessageHandler* handler_; 89 bool running_; 90 bool finished_; 91 NotificationRegistrar registrar_; 92 93 DISALLOW_COPY_AND_ASSIGN(JavascriptTestObserver); 94}; 95 96} // namespace content 97 98#endif // CONTENT_PUBLIC_TEST_JAVASCRIPT_TEST_OBSERVER_H_ 99