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.
5 #include "extensions/test/extension_test_message_listener.h"
7 #include "base/strings/string_number_conversions.h"
8 #include "base/strings/string_util.h"
9 #include "content/public/browser/notification_service.h"
10 #include "content/public/browser/notification_source.h"
11 #include "content/public/test/test_utils.h"
12 #include "extensions/browser/api/test/test_api.h"
13 #include "extensions/browser/notification_types.h"
15 ExtensionTestMessageListener::ExtensionTestMessageListener(
16 const std::string
& expected_message
,
18 : expected_message_(expected_message
),
21 wait_for_any_message_(false),
22 will_reply_(will_reply
),
26 extensions::NOTIFICATION_EXTENSION_TEST_MESSAGE
,
27 content::NotificationService::AllSources());
30 ExtensionTestMessageListener::ExtensionTestMessageListener(bool will_reply
)
33 wait_for_any_message_(true),
34 will_reply_(will_reply
),
38 extensions::NOTIFICATION_EXTENSION_TEST_MESSAGE
,
39 content::NotificationService::AllSources());
42 ExtensionTestMessageListener::~ExtensionTestMessageListener() {}
44 bool ExtensionTestMessageListener::WaitUntilSatisfied() {
48 content::RunMessageLoop();
52 void ExtensionTestMessageListener::Reply(const std::string
& message
) {
57 function_
->Reply(message
);
61 void ExtensionTestMessageListener::Reply(int message
) {
62 Reply(base::IntToString(message
));
65 void ExtensionTestMessageListener::ReplyWithError(const std::string
& error
) {
70 function_
->ReplyWithError(error
);
74 void ExtensionTestMessageListener::Reset() {
81 void ExtensionTestMessageListener::Observe(
83 const content::NotificationSource
& source
,
84 const content::NotificationDetails
& details
) {
85 DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_TEST_MESSAGE
, type
);
87 // Return immediately if we're already satisfied or it's not the right
89 extensions::TestSendMessageFunction
* function
=
90 content::Source
<extensions::TestSendMessageFunction
>(source
).ptr();
92 (!extension_id_
.empty() && function
->extension_id() != extension_id_
)) {
96 // We should have an empty message if we're not already satisfied.
97 CHECK(message_
.empty());
99 const std::string
& message
= *content::Details
<std::string
>(details
).ptr();
100 if (message
== expected_message_
|| wait_for_any_message_
||
101 (!failure_message_
.empty() && message
== failure_message_
)) {
104 failed_
= (message_
== failure_message_
);
106 // Reply immediately, or save the function for future use.
107 function_
= function
;
109 Reply(std::string());
113 base::MessageLoopForUI::current()->Quit();