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