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 #include "content/public/test/javascript_test_observer.h" 6 7 #include "content/public/browser/dom_operation_notification_details.h" 8 #include "content/public/browser/notification_types.h" 9 #include "content/public/browser/render_view_host.h" 10 #include "content/public/browser/web_contents.h" 11 #include "content/public/test/test_utils.h" 12 13 namespace content { 14 15 TestMessageHandler::TestMessageHandler() : ok_(true) { 16 } 17 18 TestMessageHandler::~TestMessageHandler() { 19 } 20 21 void TestMessageHandler::SetError(const std::string& message) { 22 ok_ = false; 23 error_message_ = message; 24 } 25 26 void TestMessageHandler::Reset() { 27 ok_ = true; 28 error_message_.clear(); 29 } 30 31 JavascriptTestObserver::JavascriptTestObserver( 32 WebContents* web_contents, TestMessageHandler* handler) 33 : handler_(handler), 34 running_(false), 35 finished_(false) { 36 Reset(); 37 registrar_.Add(this, 38 NOTIFICATION_DOM_OPERATION_RESPONSE, 39 Source<WebContents>(web_contents)); 40 } 41 42 JavascriptTestObserver::~JavascriptTestObserver() { 43 } 44 45 bool JavascriptTestObserver::Run() { 46 // Messages may have arrived before Run was called. 47 if (!finished_) { 48 CHECK(!running_); 49 running_ = true; 50 RunMessageLoop(); 51 running_ = false; 52 } 53 return handler_->ok(); 54 } 55 56 void JavascriptTestObserver::Reset() { 57 CHECK(!running_); 58 running_ = false; 59 finished_ = false; 60 handler_->Reset(); 61 } 62 63 void JavascriptTestObserver::Observe( 64 int type, 65 const NotificationSource& source, 66 const NotificationDetails& details) { 67 CHECK(type == NOTIFICATION_DOM_OPERATION_RESPONSE); 68 Details<DomOperationNotificationDetails> dom_op_details(details); 69 // We might receive responses for other script execution, but we only 70 // care about the test finished message. 71 TestMessageHandler::MessageResponse response = 72 handler_->HandleMessage(dom_op_details->json); 73 74 if (response == TestMessageHandler::DONE) { 75 EndTest(); 76 } else { 77 Continue(); 78 } 79 } 80 81 void JavascriptTestObserver::Continue() { 82 } 83 84 void JavascriptTestObserver::EndTest() { 85 finished_ = true; 86 if (running_) { 87 running_ = false; 88 base::MessageLoopForUI::current()->Quit(); 89 } 90 } 91 92 } // namespace content 93