Home | History | Annotate | Download | only in extensions
      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 #include "chrome/browser/extensions/extension_test_message_listener.h"
      6 
      7 #include "base/strings/string_number_conversions.h"
      8 #include "chrome/browser/chrome_notification_types.h"
      9 #include "chrome/browser/chrome_notification_types.h"
     10 #include "chrome/browser/extensions/api/test/test_api.h"
     11 #include "chrome/test/base/ui_test_utils.h"
     12 #include "content/public/browser/notification_service.h"
     13 
     14 ExtensionTestMessageListener::ExtensionTestMessageListener(
     15     const std::string& expected_message,
     16     bool will_reply)
     17     : expected_message_(expected_message),
     18       satisfied_(false),
     19       waiting_(false),
     20       will_reply_(will_reply),
     21       failed_(false) {
     22   registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_TEST_MESSAGE,
     23                  content::NotificationService::AllSources());
     24 }
     25 
     26 ExtensionTestMessageListener::~ExtensionTestMessageListener() {}
     27 
     28 bool ExtensionTestMessageListener::WaitUntilSatisfied()  {
     29   if (satisfied_)
     30     return !failed_;
     31   waiting_ = true;
     32   content::RunMessageLoop();
     33   return !failed_;
     34 }
     35 
     36 void ExtensionTestMessageListener::Reply(const std::string& message) {
     37   DCHECK(satisfied_);
     38   DCHECK(will_reply_);
     39   function_->Reply(message);
     40   function_ = NULL;
     41   will_reply_ = false;
     42 }
     43 
     44 void ExtensionTestMessageListener::Reply(int message) {
     45   Reply(base::IntToString(message));
     46 }
     47 
     48 void ExtensionTestMessageListener::Observe(
     49     int type,
     50     const content::NotificationSource& source,
     51     const content::NotificationDetails& details) {
     52   const std::string& content = *content::Details<std::string>(details).ptr();
     53   if (!satisfied_ && (content == expected_message_ ||
     54       (!failure_message_.empty() && (content == failure_message_)))) {
     55     if (!failed_)
     56       failed_ = (content == failure_message_);
     57     function_ = content::Source<extensions::TestSendMessageFunction>(
     58         source).ptr();
     59     satisfied_ = true;
     60     registrar_.RemoveAll();  // Stop listening for more messages.
     61     if (!will_reply_) {
     62       function_->Reply(std::string());
     63       function_ = NULL;
     64     }
     65     if (waiting_) {
     66       waiting_ = false;
     67       base::MessageLoopForUI::current()->Quit();
     68     }
     69   }
     70 }
     71