Commit 13091736 authored by chrisgao@chromium.org's avatar chrisgao@chromium.org

Convert HTML5 notification pyauto tests to browser_tests.

BUG=none


Review URL: https://chromiumcodereview.appspot.com/11359174

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170623 0039d316-1c4b-4281-b951-d872f2087c98
parent 24906547
...@@ -2,25 +2,408 @@ ...@@ -2,25 +2,408 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include <deque>
#include <string>
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/api/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/api/infobars/infobar_delegate.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/infobars/infobar_tab_helper.h" #include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/notifications/balloon_collection.h"
#include "chrome/browser/notifications/balloon_host.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/content_settings.h"
#include "chrome/common/content_settings_pattern.h"
#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h" #include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h" #include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h" #include "net/base/net_util.h"
#include "net/test/test_server.h" #include "net/test/test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/window_open_disposition.h"
namespace {
const char kExpectedIconUrl[] = "files/notifications/no_such_file.png";
class NotificationsPermissionTest : public InProcessBrowserTest { enum InfobarAction {
DISMISS = 0,
ALLOW,
DENY,
};
class NotificationBalloonChangeObserver : public content::NotificationObserver {
public: public:
NotificationsPermissionTest() {} NotificationBalloonChangeObserver()
: collection_(
g_browser_process->notification_ui_manager()->balloon_collection()),
collection_changed_(false),
notification_received_(false),
running_(false),
done_(false) {
registrar_.Add(this, chrome::NOTIFICATION_NOTIFY_BALLOON_CONNECTED,
content::NotificationService::AllSources());
registrar_.Add(this, chrome::NOTIFICATION_NOTIFY_BALLOON_DISCONNECTED,
content::NotificationService::AllSources());
collection_->set_on_collection_changed_callback(
base::Bind(&NotificationBalloonChangeObserver::OnCollectionChanged,
base::Unretained(this)));
}
virtual ~NotificationBalloonChangeObserver() {
collection_->set_on_collection_changed_callback(base::Closure());
}
bool Wait() {
if (!Check()) {
running_ = true;
message_loop_runner_ = new content::MessageLoopRunner;
message_loop_runner_->Run();
EXPECT_TRUE(done_);
}
return done_;
}
bool Check() {
if (done_)
return true;
if (collection_changed_ && notification_received_) {
done_ = true;
if (running_) {
message_loop_runner_->Quit();
running_ = false;
}
}
return done_;
}
void OnCollectionChanged() {
collection_changed_ = true;
Check();
}
// Overridden from content::NotificationObserver:
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE {
DCHECK(type == chrome::NOTIFICATION_NOTIFY_BALLOON_DISCONNECTED ||
type == chrome::NOTIFICATION_NOTIFY_BALLOON_CONNECTED);
notification_received_ = true;
Check();
}
private:
content::NotificationRegistrar registrar_;
BalloonCollection* collection_;
bool collection_changed_;
bool notification_received_;
bool running_;
bool done_;
scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
DISALLOW_COPY_AND_ASSIGN(NotificationBalloonChangeObserver);
}; };
// If this flakes, use http://crbug.com/62311 and http://crbug.com/74428. } // namespace
IN_PROC_BROWSER_TEST_F(NotificationsPermissionTest, TestUserGestureInfobar) {
class NotificationsTest : public InProcessBrowserTest {
public:
NotificationsTest() {}
protected:
// Overriden from InProcessBrowserTest:
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE;
const std::deque<Balloon*>& GetActiveBalloons();
int GetNotificationCount();
bool CloseNotificationAndWait(const Notification& notification);
void CloseBrowserWindow(Browser* browser);
void CrashTab(Browser* browser, int index);
void CrashNotification(Balloon* balloon);
void SetDefaultPermissionSetting(ContentSetting setting);
void DenyOrigin(const GURL& origin);
void AllowOrigin(const GURL& origin);
void AllowAllOrigins();
void VerifyInfobar(const Browser* browser, int index);
std::string CreateNotification(Browser* browser,
bool wait_for_new_balloon,
const char* icon,
const char* title,
const char* body,
const char* replace_id);
std::string CreateSimpleNotification(Browser* browser,
bool wait_for_new_balloon);
bool RequestPermissionAndWait(Browser* browser);
bool CancelNotification(const char* notification_id, Browser* browser);
bool PerformActionOnInfobar(Browser* browser,
InfobarAction action,
int infobar_index,
int tab_index);
void GetPrefsByContentSetting(ContentSetting setting,
ContentSettingsForOneType* settings);
bool CheckOriginInSetting(const ContentSettingsForOneType& settings,
const GURL& origin);
GURL empty_page_url_;
GURL test_page_url_;
private:
void DropOriginPreference(const GURL& origin);
DesktopNotificationService* GetDesktopNotificationService();
};
void NotificationsTest::SetUpInProcessBrowserTestFixture() {
InProcessBrowserTest::SetUpInProcessBrowserTestFixture();
ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(test_server()->Start());
empty_page_url_ = test_server()->GetURL("files/empty.html");
test_page_url_ = test_server()->GetURL(
"files/notifications/notification_tester.html");
}
const std::deque<Balloon*>& NotificationsTest::GetActiveBalloons() {
return g_browser_process->notification_ui_manager()->
balloon_collection()->GetActiveBalloons();
}
int NotificationsTest::GetNotificationCount() {
return g_browser_process->notification_ui_manager()->
balloon_collection()->GetActiveBalloons().size();
}
bool NotificationsTest::CloseNotificationAndWait(
const Notification& notification) {
NotificationBalloonChangeObserver observer;
bool success = g_browser_process->notification_ui_manager()->
CancelById(notification.notification_id());
if (success)
return observer.Wait();
return false;
}
void NotificationsTest::CloseBrowserWindow(Browser* browser) {
content::WindowedNotificationObserver observer(
chrome::NOTIFICATION_BROWSER_CLOSED,
content::Source<Browser>(browser));
browser->window()->Close();
observer.Wait();
}
void NotificationsTest::CrashTab(Browser* browser, int index) {
content::CrashTab(chrome::GetWebContentsAt(browser, index));
}
void NotificationsTest::CrashNotification(Balloon* balloon) {
content::CrashTab(balloon->balloon_view()->GetHost()->web_contents());
}
void NotificationsTest::SetDefaultPermissionSetting(ContentSetting setting) {
DesktopNotificationService* service = GetDesktopNotificationService();
service->SetDefaultContentSetting(setting);
}
void NotificationsTest::DenyOrigin(const GURL& origin) {
DropOriginPreference(origin);
GetDesktopNotificationService()->DenyPermission(origin);
}
void NotificationsTest::AllowOrigin(const GURL& origin) {
DropOriginPreference(origin);
GetDesktopNotificationService()->GrantPermission(origin);
}
void NotificationsTest::AllowAllOrigins() {
GetDesktopNotificationService()->ResetAllOrigins();
GetDesktopNotificationService()->SetDefaultContentSetting(
CONTENT_SETTING_ALLOW);
}
void NotificationsTest::VerifyInfobar(const Browser* browser, int index) {
InfoBarTabHelper* infobar_helper = InfoBarTabHelper::FromWebContents(
chrome::GetWebContentsAt(browser, index));
ASSERT_EQ(1U, infobar_helper->GetInfoBarCount());
InfoBarDelegate* infobar = infobar_helper->GetInfoBarDelegateAt(0);
ConfirmInfoBarDelegate* confirm_infobar = infobar->AsConfirmInfoBarDelegate();
ASSERT_TRUE(confirm_infobar);
int buttons = confirm_infobar->GetButtons();
EXPECT_TRUE(buttons & ConfirmInfoBarDelegate::BUTTON_OK);
EXPECT_TRUE(buttons & ConfirmInfoBarDelegate::BUTTON_CANCEL);
}
std::string NotificationsTest::CreateNotification(
Browser* browser,
bool wait_for_new_balloon,
const char* icon,
const char* title,
const char* body,
const char* replace_id) {
std::string script = base::StringPrintf(
"createNotification('%s', '%s', '%s', '%s');",
icon, title, body, replace_id);
NotificationBalloonChangeObserver observer;
std::string result;
bool success = content::ExecuteJavaScriptAndExtractString(
chrome::GetActiveWebContents(browser)->GetRenderViewHost(),
L"",
UTF8ToWide(script),
&result);
if (success && result != "-1" && wait_for_new_balloon)
success = observer.Wait();
EXPECT_TRUE(success);
return result;
}
std::string NotificationsTest::CreateSimpleNotification(
Browser* browser,
bool wait_for_new_balloon) {
return CreateNotification(
browser, wait_for_new_balloon,
"no_such_file.png", "My Title", "My Body", "");
}
bool NotificationsTest::RequestPermissionAndWait(Browser* browser) {
InfoBarTabHelper* infobar_helper = InfoBarTabHelper::FromWebContents(
chrome::GetActiveWebContents(browser));
content::WindowedNotificationObserver observer(
chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
content::Source<InfoBarTabHelper>(infobar_helper));
std::string result;
bool success = content::ExecuteJavaScriptAndExtractString(
chrome::GetActiveWebContents(browser)->GetRenderViewHost(),
L"",
L"requestPermission();",
&result);
if (!success || result != "1")
return false;
observer.Wait();
return true;
}
bool NotificationsTest::CancelNotification(
const char* notification_id,
Browser* browser) {
std::string script = base::StringPrintf(
"cancelNotification('%s');",
notification_id);
NotificationBalloonChangeObserver observer;
std::string result;
bool success = content::ExecuteJavaScriptAndExtractString(
chrome::GetActiveWebContents(browser)->GetRenderViewHost(),
L"",
UTF8ToWide(script),
&result);
if (!success || result != "1")
return false;
return observer.Wait();
}
bool NotificationsTest::PerformActionOnInfobar(
Browser* browser,
InfobarAction action,
int infobar_index,
int tab_index) {
InfoBarTabHelper* infobar_helper = InfoBarTabHelper::FromWebContents(
chrome::GetWebContentsAt(browser, tab_index));
InfoBarDelegate* infobar = infobar_helper->GetInfoBarDelegateAt(
infobar_index);
switch (action) {
case DISMISS: {
infobar->InfoBarDismissed();
infobar_helper->RemoveInfoBar(infobar);
return true;
}
case ALLOW: {
ConfirmInfoBarDelegate* confirm_bar = infobar->AsConfirmInfoBarDelegate();
if (confirm_bar->Accept()) {
infobar_helper->RemoveInfoBar(infobar);
return true;
}
}
case DENY: {
ConfirmInfoBarDelegate* confirm_bar = infobar->AsConfirmInfoBarDelegate();
if (confirm_bar->Cancel()) {
infobar_helper->RemoveInfoBar(infobar);
return true;
}
}
}
return false;
}
void NotificationsTest::GetPrefsByContentSetting(
ContentSetting setting,
ContentSettingsForOneType* settings) {
DesktopNotificationService* service = GetDesktopNotificationService();
service->GetNotificationsSettings(settings);
for (ContentSettingsForOneType::iterator it = settings->begin();
it != settings->end(); ) {
if (it->setting != setting || it->source.compare("preference") != 0)
it = settings->erase(it);
else
++it;
}
}
bool NotificationsTest::CheckOriginInSetting(
const ContentSettingsForOneType& settings,
const GURL& origin) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromURLNoWildcard(origin);
for (ContentSettingsForOneType::const_iterator it = settings.begin();
it != settings.end(); ++it) {
if (it->primary_pattern == pattern)
return true;
}
return false;
}
void NotificationsTest::DropOriginPreference(const GURL& origin) {
GetDesktopNotificationService()->ClearSetting(
ContentSettingsPattern::FromURLNoWildcard(origin));
}
DesktopNotificationService* NotificationsTest::GetDesktopNotificationService() {
Profile* profile = browser()->profile();
return DesktopNotificationServiceFactory::GetForProfile(profile);
}
// If this flakes, use http://crbug.com/62311 and http://crbug.com/74428.
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestUserGestureInfobar) {
ui_test_utils::NavigateToURL( ui_test_utils::NavigateToURL(
browser(), browser(),
test_server()->GetURL( test_server()->GetURL(
...@@ -41,9 +424,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsPermissionTest, TestUserGestureInfobar) { ...@@ -41,9 +424,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsPermissionTest, TestUserGestureInfobar) {
} }
// If this flakes, use http://crbug.com/62311. // If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(NotificationsPermissionTest, TestNoUserGestureInfobar) { IN_PROC_BROWSER_TEST_F(NotificationsTest, TestNoUserGestureInfobar) {
ASSERT_TRUE(test_server()->Start());
// Load a page which just does a request; no user gesture should result // Load a page which just does a request; no user gesture should result
// in no infobar. // in no infobar.
ui_test_utils::NavigateToURL( ui_test_utils::NavigateToURL(
...@@ -54,3 +435,359 @@ IN_PROC_BROWSER_TEST_F(NotificationsPermissionTest, TestNoUserGestureInfobar) { ...@@ -54,3 +435,359 @@ IN_PROC_BROWSER_TEST_F(NotificationsPermissionTest, TestNoUserGestureInfobar) {
EXPECT_EQ(0U, InfoBarTabHelper::FromWebContents( EXPECT_EQ(0U, InfoBarTabHelper::FromWebContents(
chrome::GetWebContentsAt(browser(), 0))->GetInfoBarCount()); chrome::GetWebContentsAt(browser(), 0))->GetInfoBarCount());
} }
// Disable new testcases on Chrome OS due to failure on creating notification.
#if !defined(OS_CHROMEOS)
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCreateSimpleNotification) {
// Creates a simple notification.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), true);
EXPECT_NE("-1", result);
const std::deque<Balloon*>& balloons = GetActiveBalloons();
ASSERT_EQ(1U, balloons.size());
Balloon* balloon = balloons[0];
const Notification& notification = balloon->notification();
GURL EXPECTED_ICON_URL = test_server()->GetURL(kExpectedIconUrl);
EXPECT_EQ(EXPECTED_ICON_URL, notification.icon_url());
EXPECT_EQ(ASCIIToUTF16("My Title"), notification.title());
EXPECT_EQ(ASCIIToUTF16("My Body"), notification.body());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCloseNotification) {
// Creates a notification and closes it.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), true);
EXPECT_NE("-1", result);
const std::deque<Balloon*>& balloons = GetActiveBalloons();
ASSERT_EQ(1U, balloons.size());
EXPECT_TRUE(CloseNotificationAndWait(balloons[0]->notification()));
ASSERT_EQ(0, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCancelNotification) {
// Creates a notification and cancels it in the origin page.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string note_id = CreateSimpleNotification(browser(), true);
EXPECT_NE(note_id, "-1");
ASSERT_EQ(1, GetNotificationCount());
ASSERT_TRUE(CancelNotification(note_id.c_str(), browser()));
ASSERT_EQ(0, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestPermissionInfobarAppears) {
// Requests notification privileges and verifies the infobar appears.
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
ASSERT_EQ(0, GetNotificationCount());
VerifyInfobar(browser(), 0);
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestAllowOnPermissionInfobar) {
// Tries to create a notification and clicks allow on the infobar.
ui_test_utils::NavigateToURL(browser(), test_page_url_);
// This notification should not be shown because we do not have permission.
CreateSimpleNotification(browser(), false);
ASSERT_EQ(0, GetNotificationCount());
ASSERT_TRUE(RequestPermissionAndWait(browser()));
ASSERT_TRUE(PerformActionOnInfobar(browser(), ALLOW, 0, 0));
CreateSimpleNotification(browser(), true);
EXPECT_EQ(1, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestDenyOnPermissionInfobar) {
// Test that no notification is created
// when Deny is chosen from permission infobar.
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
PerformActionOnInfobar(browser(), DENY, 0, 0);
CreateSimpleNotification(browser(), false);
ASSERT_EQ(0, GetNotificationCount());
ContentSettingsForOneType settings;
GetPrefsByContentSetting(CONTENT_SETTING_BLOCK, &settings);
EXPECT_TRUE(CheckOriginInSetting(settings, test_page_url_));
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestClosePermissionInfobar) {
// Test that no notification is created when permission infobar is dismissed.
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
PerformActionOnInfobar(browser(), DISMISS, 0, 0);
CreateSimpleNotification(browser(), false);
ASSERT_EQ(0, GetNotificationCount());
ContentSettingsForOneType settings;
GetPrefsByContentSetting(CONTENT_SETTING_BLOCK, &settings);
EXPECT_EQ(0U, settings.size());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestNotificationWithPropertyMissing) {
// Test that a notification can be created if one property is missing.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), true);
EXPECT_NE("-1", result);
const std::deque<Balloon*>& balloons = GetActiveBalloons();
ASSERT_EQ(1U, balloons.size());
Balloon* balloon = balloons[0];
const Notification& notification = balloon->notification();
GURL EXPECTED_ICON_URL = test_server()->GetURL(kExpectedIconUrl);
EXPECT_EQ(EXPECTED_ICON_URL, notification.icon_url());
EXPECT_EQ(ASCIIToUTF16("My Title"), notification.title());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestAllowNotificationsFromAllSites) {
// Verify that all domains can be allowed to show notifications.
SetDefaultPermissionSetting(CONTENT_SETTING_ALLOW);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), true);
EXPECT_NE("-1", result);
ASSERT_EQ(1, GetNotificationCount());
EXPECT_EQ(0U, InfoBarTabHelper::FromWebContents(
chrome::GetWebContentsAt(browser(), 0))->GetInfoBarCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestDenyNotificationsFromAllSites) {
// Verify that no domain can show notifications.
SetDefaultPermissionSetting(CONTENT_SETTING_BLOCK);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), false);
EXPECT_EQ("-1", result);
ASSERT_EQ(0, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestDenyDomainAndAllowAll) {
// Verify that denying a domain and allowing all shouldn't show
// notifications from the denied domain.
DenyOrigin(test_page_url_.GetOrigin());
SetDefaultPermissionSetting(CONTENT_SETTING_ALLOW);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), false);
EXPECT_EQ("-1", result);
ASSERT_EQ(0, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestAllowDomainAndDenyAll) {
// Verify that allowing a domain and denying all others should show
// notifications from the allowed domain.
AllowOrigin(test_page_url_.GetOrigin());
SetDefaultPermissionSetting(CONTENT_SETTING_BLOCK);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), true);
EXPECT_NE("-1", result);
ASSERT_EQ(1, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestDenyAndThenAllowDomain) {
// Verify that denying and again allowing should show notifications.
DenyOrigin(test_page_url_.GetOrigin());
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateSimpleNotification(browser(), false);
EXPECT_EQ("-1", result);
ASSERT_EQ(0, GetNotificationCount());
AllowOrigin(test_page_url_.GetOrigin());
result = CreateSimpleNotification(browser(), true);
EXPECT_NE("-1", result);
ASSERT_EQ(1, GetNotificationCount());
EXPECT_EQ(0U, InfoBarTabHelper::FromWebContents(
chrome::GetWebContentsAt(browser(), 0))->GetInfoBarCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCreateDenyCloseNotifications) {
// Verify able to create, deny, and close the notification.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
CreateSimpleNotification(browser(), true);
ASSERT_EQ(1, GetNotificationCount());
DenyOrigin(test_page_url_.GetOrigin());
ContentSettingsForOneType settings;
GetPrefsByContentSetting(CONTENT_SETTING_BLOCK, &settings);
ASSERT_TRUE(CheckOriginInSetting(settings, test_page_url_.GetOrigin()));
const std::deque<Balloon*>& balloons1 = GetActiveBalloons();
EXPECT_EQ(1U, balloons1.size());
ASSERT_TRUE(CloseNotificationAndWait(balloons1[0]->notification()));
ASSERT_EQ(0, GetNotificationCount());
}
// Crashes on Linux/Win. See http://crbug.com/160657.
IN_PROC_BROWSER_TEST_F(
NotificationsTest,
DISABLED_TestOriginPrefsNotSavedInIncognito) {
// Verify that allow/deny origin preferences are not saved in incognito.
Browser* incognito = CreateIncognitoBrowser();
ui_test_utils::NavigateToURL(incognito, test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(incognito));
PerformActionOnInfobar(incognito, DENY, 0, 0);
CloseBrowserWindow(incognito);
incognito = CreateIncognitoBrowser();
ui_test_utils::NavigateToURL(incognito, test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(incognito));
PerformActionOnInfobar(incognito, ALLOW, 0, 0);
CreateSimpleNotification(incognito, true);
ASSERT_EQ(1, GetNotificationCount());
CloseBrowserWindow(incognito);
incognito = CreateIncognitoBrowser();
ui_test_utils::NavigateToURL(incognito, test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(incognito));
ContentSettingsForOneType settings;
GetPrefsByContentSetting(CONTENT_SETTING_BLOCK, &settings);
EXPECT_EQ(0U, settings.size());
GetPrefsByContentSetting(CONTENT_SETTING_ALLOW, &settings);
EXPECT_EQ(0U, settings.size());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestExitBrowserWithInfobar) {
// Exit the browser window, when the infobar appears.
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCrashTabWithPermissionInfobar) {
// Test crashing the tab with permission infobar doesn't crash Chrome.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
empty_page_url_,
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
chrome::ActivateTabAt(browser(), 0, true);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
CrashTab(browser(), 0);
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestKillNotificationProcess) {
// Test killing a notification doesn't crash Chrome.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
CreateSimpleNotification(browser(), true);
ASSERT_EQ(1, GetNotificationCount());
const std::deque<Balloon*>& balloons = GetActiveBalloons();
ASSERT_EQ(1U, balloons.size());
CrashNotification(balloons[0]);
ASSERT_EQ(0, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestIncognitoNotification) {
// Test notifications in incognito window.
Browser* browser = CreateIncognitoBrowser();
ui_test_utils::NavigateToURL(browser, test_page_url_);
chrome::ActivateTabAt(browser, 0, true);
ASSERT_TRUE(RequestPermissionAndWait(browser));
PerformActionOnInfobar(browser, ALLOW, 0, 0);
CreateSimpleNotification(browser, true);
ASSERT_EQ(1, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCloseTabWithPermissionInfobar) {
// Test that user can close tab when infobar present.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
GURL("about:blank"),
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
chrome::ActivateTabAt(browser(), 0, true);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
content::WindowedNotificationObserver observer(
content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
content::NotificationService::AllSources());
chrome::CloseWebContents(browser(), chrome::GetWebContentsAt(browser(), 0));
observer.Wait();
}
IN_PROC_BROWSER_TEST_F(
NotificationsTest,
TestNavigateAwayWithPermissionInfobar) {
// Test navigating away when an infobar is present,
// then trying to create a notification from the same page.
ui_test_utils::NavigateToURLWithDisposition(
browser(),
GURL("about:blank"),
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
chrome::ActivateTabAt(browser(), 0, true);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
ui_test_utils::NavigateToURL(browser(), test_page_url_);
ASSERT_TRUE(RequestPermissionAndWait(browser()));
PerformActionOnInfobar(browser(), ALLOW, 0, 0);
CreateSimpleNotification(browser(), true);
ASSERT_EQ(1, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestCrashRendererNotificationRemain) {
// Test crashing renderer does not close or crash notification.
AllowAllOrigins();
ui_test_utils::NavigateToURLWithDisposition(
browser(),
GURL("about:blank"),
NEW_BACKGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
chrome::ActivateTabAt(browser(), 0, true);
ui_test_utils::NavigateToURL(browser(), test_page_url_);
CreateSimpleNotification(browser(), true);
ASSERT_EQ(1, GetNotificationCount());
CrashTab(browser(), 0);
ASSERT_EQ(1, GetNotificationCount());
}
IN_PROC_BROWSER_TEST_F(NotificationsTest, TestNotificationReplacement) {
// Test that we can replace a notification using the replaceId.
AllowAllOrigins();
ui_test_utils::NavigateToURL(browser(), test_page_url_);
std::string result = CreateNotification(
browser(), true, "abc.png", "Title1", "Body1", "chat");
EXPECT_NE("-1", result);
ASSERT_EQ(1, GetNotificationCount());
result = CreateNotification(
browser(), false, "no_such_file.png", "Title2", "Body2", "chat");
EXPECT_NE("-1", result);
const std::deque<Balloon*>& balloons = GetActiveBalloons();
EXPECT_EQ(1U, balloons.size());
const Notification& notification = balloons[0]->notification();
GURL EXPECTED_ICON_URL = test_server()->GetURL(kExpectedIconUrl);
EXPECT_EQ(EXPECTED_ICON_URL, notification.icon_url());
EXPECT_EQ(ASCIIToUTF16("Title2"), notification.title());
EXPECT_EQ(ASCIIToUTF16("Body2"), notification.body());
}
#endif // !defined(OS_CHROMEOS)
...@@ -26,23 +26,6 @@ function createNotification(iconUrl, title, text, replaceId) { ...@@ -26,23 +26,6 @@ function createNotification(iconUrl, title, text, replaceId) {
createNotificationHelper(note, replaceId, true); createNotificationHelper(note, replaceId, true);
} }
// Creates an HTML notification with a given content url.
// Returns an id for the notification, which can be used to cancel it with
// |cancelNotification|. If two notifications are created with the same
// replaceId, the second one should replace the first. If the notification
// cannot be created, this returns -1.
// If |waitForDisplay| is true, a response will not be sent until the
// notification is actually displayed.
function createHTMLNotification(contentUrl, replaceId, waitForDisplay) {
try {
var note = webkitNotifications.createHTMLNotification(contentUrl);
} catch (exception) {
sendResultToTest(-1);
return;
}
createNotificationHelper(note, replaceId, waitForDisplay);
}
// Cancels a notification with the given id. The notification must be showing, // Cancels a notification with the given id. The notification must be showing,
// as opposed to waiting to be shown in the display queue. // as opposed to waiting to be shown in the display queue.
// Returns '1' on success. // Returns '1' on success.
......
...@@ -48,7 +48,6 @@ ...@@ -48,7 +48,6 @@
'media.media_basic_playback', 'media.media_basic_playback',
'multiprofile', 'multiprofile',
'nacl_sdk', 'nacl_sdk',
'notifications',
'ntp', 'ntp',
'omnibox', 'omnibox',
'passwords', 'passwords',
...@@ -99,10 +98,6 @@ ...@@ -99,10 +98,6 @@
# Mysteriously broken? # Mysteriously broken?
# crbug.com/138857 # crbug.com/138857
'-multiprofile.MultiprofileTest.testMakeSearchEngineDefaultInMultiprofile', '-multiprofile.MultiprofileTest.testMakeSearchEngineDefaultInMultiprofile',
# crbug.com/105560
'-notifications',
# crbug.com/99506
'-notifications.NotificationsTest.testSpecialURLNotification',
# crbug.com/143308 # crbug.com/143308
'-omnibox.OmniboxLiveTest.testGoogleSearch', '-omnibox.OmniboxLiveTest.testGoogleSearch',
# crbug.com/71715 # crbug.com/71715
...@@ -154,8 +149,8 @@ ...@@ -154,8 +149,8 @@
# -imports.ImportsTest.testFirefoxImportFromPrefs # -imports.ImportsTest.testFirefoxImportFromPrefs
# Disabled on vista in the actual test. crbug.com/89767 # Disabled on vista in the actual test. crbug.com/89767
# -imports.ImportsTest.testImportFirefoxPasswordsFromPrefs # -imports.ImportsTest.testImportFirefoxPasswordsFromPrefs
# crbug.com/95031 # crbug.com/125424
'-notifications.NotificationsTest.testOriginPrefsNotSavedInIncognito', '-media.media_basic_playback.MediaBasicPlaybackTest.testBasicPlaybackMatrix',
# crbug.com/117569 # crbug.com/117569
'-passwords.PasswordTest.testSavedPasswordInTabsAndWindows', '-passwords.PasswordTest.testSavedPasswordInTabsAndWindows',
# crbug.com/98526 # crbug.com/98526
...@@ -197,10 +192,6 @@ ...@@ -197,10 +192,6 @@
# crbug.com/121484 # crbug.com/121484
'-multiprofile.MultiprofileTest.test20NewProfiles', '-multiprofile.MultiprofileTest.test20NewProfiles',
'-ntp.NTPTest.testLaunchAppNewWindow', # crbug.com/79812 '-ntp.NTPTest.testLaunchAppNewWindow', # crbug.com/79812
# Causes browser crash. crbug.com/93548
'-notifications.NotificationsTest.testIncognitoNotification',
'-notifications.NotificationsTest.testOriginPrefsNotSavedInIncognito',
'-notifications.NotificationsTest.testNotificationOrderAfterClosingOne',
# crbug.com/70437 # crbug.com/70437
'-omnibox.OmniboxTest.testHistoryResult', '-omnibox.OmniboxTest.testHistoryResult',
# crbug.com/91617 # crbug.com/91617
...@@ -222,8 +213,6 @@ ...@@ -222,8 +213,6 @@
# =========================== # ===========================
# Permanently-disabled tests. # Permanently-disabled tests.
# =========================== # ===========================
# crbug.com/104206
'-notifications.NotificationsTest.testKillNotificationProcess',
# System password manager obstructs password automation. # System password manager obstructs password automation.
'-passwords', '-passwords',
...@@ -234,8 +223,6 @@ ...@@ -234,8 +223,6 @@
'-autofill.AutofillTest.testDisplayLineItemForEntriesWithNoCCNum', '-autofill.AutofillTest.testDisplayLineItemForEntriesWithNoCCNum',
# crbug.com/111289 # crbug.com/111289
'-extensions.ExtensionsTest.testAllowAccessFileURLs', '-extensions.ExtensionsTest.testAllowAccessFileURLs',
# crbug.com/66072
'-notifications.NotificationsTest.testNotificationOrderAfterClosingOne',
# crbug.com/91033 # crbug.com/91033
'-omnibox.OmniboxTest.testOmniboxSearchHistory', '-omnibox.OmniboxTest.testOmniboxSearchHistory',
# Gnome / kwallet popups on linux break sync tests. crbug.com/80329 # Gnome / kwallet popups on linux break sync tests. crbug.com/80329
...@@ -318,8 +305,6 @@ ...@@ -318,8 +305,6 @@
'-chromeos_wifi_sanity.ChromeosWifiSanity.testConnectToHiddenWiFiNonExistent', '-chromeos_wifi_sanity.ChromeosWifiSanity.testConnectToHiddenWiFiNonExistent',
# crosbug.com/20025 # crosbug.com/20025
'-chromeos_browser.ChromeosBrowserTest.testFullScreen', '-chromeos_browser.ChromeosBrowserTest.testFullScreen',
# crbug.com/102549
'-notifications.NotificationsTest.testOriginPrefsNotSavedInIncognito',
# Chrome driver does not work in Chrome OS. # Chrome driver does not work in Chrome OS.
# crosbug.com/19556 # crosbug.com/19556
'-prefs_ui', '-prefs_ui',
......
#!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import urllib
import pyauto_functional
import pyauto
class NotificationsTest(pyauto.PyUITest):
"""Test of HTML5 desktop notifications."""
def __init__(self, methodName='runTest'):
super(NotificationsTest, self).__init__(methodName)
self.EMPTY_PAGE_URL = self.GetHttpURLForDataPath('empty.html')
# Content settings for default notification permission.
self.ALLOW_ALL_SETTING = 1
self.DENY_ALL_SETTING = 2
self.ASK_SETTING = 3
# HTML page used for notification testing.
self.TEST_PAGE_URL = self.GetFileURLForDataPath(
os.path.join('notifications', 'notification_tester.html'))
def Debug(self):
"""Test method for experimentation.
This method will not run automatically.
"""
while True:
raw_input('Interact with the browser and hit <enter> to dump notification'
'state...')
print '*' * 20
self.pprint(self.GetActiveNotifications())
self.pprint(self._GetDefaultPermissionSetting())
def _SetDefaultPermissionSetting(self, setting):
"""Sets the default setting for whether sites are allowed to create
notifications.
"""
self.SetPrefs(pyauto.kDefaultContentSettings, {u'notifications': setting})
def _GetDefaultPermissionSetting(self):
"""Gets the default setting for whether sites are allowed to create
notifications.
"""
return self.GetPrefsInfo().Prefs(
pyauto.kDefaultContentSettings)[u'notifications']
def _GetDeniedOrigins(self):
"""Gets the list of origins that are explicitly denied to create
notifications.
"""
return (self.GetPrefsInfo().Prefs(pyauto.kDesktopNotificationDeniedOrigins)
or [])
def _GetAllowedOrigins(self):
"""Gets the list of origins that are explicitly allowed to create
notifications.
"""
return (self.GetPrefsInfo().Prefs(pyauto.kDesktopNotificationAllowedOrigins)
or [])
def _SetAllowedOrigins(self, origins):
"""Sets the list of allowed origins to the given list.
None of the items in the list should be explicitly denied.
"""
return self.SetPrefs(pyauto.kDesktopNotificationAllowedOrigins, origins)
def _SetDeniedOrigins(self, origins):
"""Sets the list of denied origins to the given list.
None of the items in the list should be explicitly allowed.
"""
return self.SetPrefs(pyauto.kDesktopNotificationDeniedOrigins, origins)
def _DenyOrigin(self, new_origin):
"""Denies the given origin to create notifications.
If it was explicitly allowed, that preference is dropped.
"""
self._DropOriginPreference(new_origin)
denied = self._GetDeniedOrigins()
if new_origin not in denied:
self._SetDeniedOrigins(denied + [new_origin])
def _AllowOrigin(self, new_origin):
"""Allows the given origin to create notifications. If it was explicitly
denied, that preference is dropped.
"""
self._DropOriginPreference(new_origin)
allowed = self._GetAllowedOrigins()
if new_origin not in allowed:
self._SetAllowedOrigins(allowed + [new_origin])
def _DropOriginPreference(self, new_origin):
"""Drops the preference as to whether this origin should be allowed to
create notifications. If it was explicitly allowed or explicitly denied,
that preference is removed.
"""
allowed = self._GetAllowedOrigins()
if allowed and new_origin in allowed:
allowed.remove(new_origin)
self._SetAllowedOrigins(allowed)
denied = self._GetDeniedOrigins()
if denied and new_origin in denied:
denied.remove(new_origin)
self._SetDeniedOrigins(denied)
def _AllowAllOrigins(self):
"""Allows any origin to create notifications."""
self._SetDefaultPermissionSetting(self.ALLOW_ALL_SETTING)
self._SetDeniedOrigins([])
def _VerifyInfobar(self, origin, tab_index=0, windex=0):
"""Helper to verify the notification infobar contents are correct.
Defaults to first tab in first window.
Args:
origin: origin of the notification, e.g., www.gmail.com
tab_index: index of the tab within the given window
windex: index of the window
"""
tab_info = self.GetBrowserInfo()['windows'][windex]['tabs'][tab_index]
self.assertEquals(1, len(tab_info['infobars']))
infobar = tab_info['infobars'][0]
text = 'Allow %s to show desktop notifications?' % origin
self.assertEqual(text, infobar['text'])
self.assertEqual(2, len(infobar['buttons']))
self.assertEqual('Allow', infobar['buttons'][0])
self.assertEqual('Deny', infobar['buttons'][1])
def _CreateSimpleNotification(self, img_url, title, text,
replace_id='', tab_index=0, windex=0):
"""Creates a simple notification.
Returns the id of the notification, which can be used to cancel it later.
This executes a script in the page which shows a notification.
This will only work if the page is navigated to |TEST_PAGE_URL|.
The page must also have permission to show notifications.
Args:
img_url: url of a image to use; can be a data url
title: title of the notification
text: text in the notification
replace_id: id string to be used for this notification. If another
notification is shown with the same replace_id, the former
will be replaced.
tab_index: index of the tab within the given window
windex: index of the window
"""
return self.CallJavascriptFunc('createNotification',
[img_url, title, text, replace_id],
tab_index,
windex);
def _CreateHTMLNotification(self, content_url, replace_id='',
wait_for_display=True, tab_index=0, windex=0):
"""Creates an HTML notification.
Returns the id of the notification, which can be used to cancel it later.
This executes a script in the page which shows a notification.
This will only work if the page is navigated to |TEST_PAGE_URL|.
The page must also have permission to show notifications.
Args:
content_url: url of the page to show in the notification
replace_id: id string to be used for this notification. If another
notification is shown with the same replace_id, the former
will be replaced.
wait_for_display: whether we should wait for the notification to display
tab_index: index of the tab within the given window
windex: index of the window
"""
return self.CallJavascriptFunc('createHTMLNotification',
[content_url, replace_id, wait_for_display],
tab_index,
windex)
def _RequestPermission(self, tab_index=0, windex=0):
"""Requests permission to create notifications.
This will only work if the current page is navigated to |TEST_PAGE_URL|.
Args:
tab_index: index of the tab within the given window
windex: index of the window
"""
self.CallJavascriptFunc('requestPermission', [], tab_index, windex)
def _CancelNotification(self, notification_id, tab_index=0, windex=0):
"""Cancels a notification with the given id.
This canceling is done in the page that showed that notification and so
follows a different path than closing a notification via the UI.
This function should NOT be called until |WaitForNotificationCount| has been
used to verify the notification is showing. This function cannot be used to
cancel a notification that is in the display queue.
This will only work if the page is navigated to |TEST_PAGE_URL|.
Args:
notification_id: id of the notification to cancel
tab_index: index of the tab within the given window that created the
notification
windex: index of the window
"""
msg = self.CallJavascriptFunc(
'cancelNotification', [notification_id], tab_index, windex)
# '1' signifies success.
self.assertEquals('1', msg)
def testCreateSimpleNotification(self):
"""Creates a simple notification."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateSimpleNotification('no_such_file.png', 'My Title', 'My Body')
self.assertEquals(1, len(self.GetActiveNotifications()))
notification = self.GetActiveNotifications()[0]
html_data = urllib.unquote(notification['content_url'])
self.assertTrue('no_such_file.png' in html_data)
self.assertTrue('My Title' in html_data)
self.assertTrue('My Body' in html_data)
def testCreateHTMLNotification(self):
"""Creates an HTML notification using a fake url."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
notification = self.GetActiveNotifications()[0]
self.assertEquals(self.EMPTY_PAGE_URL, notification['content_url'])
self.assertEquals('', notification['display_source'])
self.assertEquals('file:///', notification['origin_url'])
def testCloseNotification(self):
"""Creates a notification and closes it."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.CloseNotification(0)
self.assertFalse(self.GetActiveNotifications())
def testCancelNotification(self):
"""Creates a notification and cancels it in the origin page."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
note_id = self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertNotEquals(-1, note_id)
self.WaitForNotificationCount(1)
self._CancelNotification(note_id)
self.assertFalse(self.GetActiveNotifications())
def testPermissionInfobarAppears(self):
"""Requests notification privileges and verifies the infobar appears."""
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.assertFalse(self.GetActiveNotifications())
self._VerifyInfobar('') # file:/// origins are blank
def testAllowOnPermissionInfobar(self):
"""Tries to create a notification and clicks allow on the infobar."""
self.NavigateToURL(self.TEST_PAGE_URL)
# This notification should not be shown because we do not have permission.
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertFalse(self.GetActiveNotifications())
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.PerformActionOnInfobar('accept', 0)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.WaitForNotificationCount(1)
def testOriginPreferencesBasic(self):
"""Tests that we can allow and deny origins."""
altavista = 'http://www.altavista.com'
gmail = 'http://www.gmail.com'
yahoo = 'http://www.yahoo.com'
self._SetDeniedOrigins([altavista, gmail])
self.assertEquals(altavista, self._GetDeniedOrigins()[0])
self.assertEquals(gmail, self._GetDeniedOrigins()[1])
self._DenyOrigin(yahoo)
self.assertEquals(yahoo, self._GetDeniedOrigins()[2])
self.assertEquals(3, len(self._GetDeniedOrigins()))
self._DropOriginPreference(gmail)
self.assertEquals(2, len(self._GetDeniedOrigins()))
self.assertFalse(gmail in self._GetDeniedOrigins())
self._AllowOrigin(yahoo)
self.assertEquals(1, len(self._GetDeniedOrigins()))
self.assertFalse(yahoo in self._GetDeniedOrigins())
self.assertTrue(yahoo in self._GetAllowedOrigins())
self._SetAllowedOrigins([altavista, gmail])
self._SetDeniedOrigins([])
self.assertEquals(altavista, self._GetAllowedOrigins()[0])
self.assertEquals(gmail, self._GetAllowedOrigins()[1])
self._AllowOrigin(yahoo)
self.assertEquals(yahoo, self._GetAllowedOrigins()[2])
self.assertEquals(3, len(self._GetAllowedOrigins()))
self._DropOriginPreference(gmail)
self.assertEquals(2, len(self._GetAllowedOrigins()))
self.assertFalse(gmail in self._GetAllowedOrigins())
self._DenyOrigin(yahoo)
self.assertEquals(1, len(self._GetAllowedOrigins()))
self.assertTrue(yahoo in self._GetDeniedOrigins())
self.assertFalse(yahoo in self._GetAllowedOrigins())
def testDenyOnPermissionInfobar (self):
"""Test that no notification is created when Deny is chosen
from permission infobar."""
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.PerformActionOnInfobar('cancel', 0)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertFalse(self.GetActiveNotifications())
self.assertEquals(['file:///'], self._GetDeniedOrigins())
def testClosePermissionInfobar(self):
"""Test that no notification is created when permission
infobar is dismissed."""
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.PerformActionOnInfobar('dismiss', 0)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertFalse(self.GetActiveNotifications())
self.assertFalse(self._GetDeniedOrigins())
def testNotificationWithPropertyMissing(self):
"""Test that a notification can be created if one property is missing."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateSimpleNotification('no_such_file.png', 'My Title', '')
self.assertEquals(1, len(self.GetActiveNotifications()))
html_data = urllib.unquote(self.GetActiveNotifications()[0]['content_url'])
self.assertTrue('no_such_file.png' in html_data)
self.assertTrue('My Title' in html_data)
def testAllowNotificationsFromAllSites(self):
"""Verify that all domains can be allowed to show notifications."""
self._SetDefaultPermissionSetting(self.ALLOW_ALL_SETTING)
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
self.assertFalse(self.GetBrowserInfo()['windows'][0]['tabs'][0]['infobars'])
def testDenyNotificationsFromAllSites(self):
"""Verify that no domain can show notifications."""
self._SetDefaultPermissionSetting(self.DENY_ALL_SETTING)
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertFalse(self.GetActiveNotifications())
def testDenyDomainAndAllowAll(self):
"""Verify that denying a domain and allowing all shouldn't show
notifications from the denied domain."""
self._DenyOrigin('file:///')
self._SetDefaultPermissionSetting(self.ALLOW_ALL_SETTING)
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertFalse(self.GetActiveNotifications())
def testAllowDomainAndDenyAll(self):
"""Verify that allowing a domain and denying all others should show
notifications from the allowed domain."""
self._AllowOrigin('file:///')
self._SetDefaultPermissionSetting(self.DENY_ALL_SETTING)
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
self.assertFalse(self.GetBrowserInfo()['windows'][0]['tabs'][0]['infobars'])
def testDenyAndThenAllowDomain(self):
"""Verify that denying and again allowing should show notifications."""
self._DenyOrigin('file:///')
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(len(self.GetActiveNotifications()), 0)
self._AllowOrigin('file:///')
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
self.assertFalse(self.GetBrowserInfo()['windows'][0]['tabs'][0]['infobars'])
def testCreateDenyCloseNotifications(self):
"""Verify able to create, deny, and close the notification."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
origin = 'file:///'
self._DenyOrigin(origin)
self.assertTrue(origin in self._GetDeniedOrigins())
self.CloseNotification(0)
self.assertEquals(0, len(self.GetActiveNotifications()))
def testOriginPrefsNotSavedInIncognito(self):
"""Verify that allow/deny origin preferences are not saved in incognito."""
self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
self.NavigateToURL(self.TEST_PAGE_URL, 1, 0)
self._RequestPermission(windex=1)
self.assertTrue(self.WaitForInfobarCount(1, windex=1))
self.PerformActionOnInfobar('cancel', 0, windex=1)
self.CloseBrowserWindow(1)
self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
self.NavigateToURL(self.TEST_PAGE_URL, 1, 0)
self._RequestPermission(windex=1)
self.assertTrue(self.WaitForInfobarCount(1, windex=1))
self.PerformActionOnInfobar('accept', 0, windex=1)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL, windex=1)
self.assertEquals(1, len(self.GetActiveNotifications()))
self.CloseBrowserWindow(1)
self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
self.NavigateToURL(self.TEST_PAGE_URL, 1, 0)
self._RequestPermission(windex=1)
self.assertTrue(self.WaitForInfobarCount(1, windex=1))
self.assertFalse(self._GetDeniedOrigins())
self.assertFalse(self._GetAllowedOrigins())
def testExitBrowserWithInfobar(self):
"""Exit the browser window, when the infobar appears."""
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
def testCrashTabWithPermissionInfobar(self):
"""Test crashing the tab with permission infobar doesn't crash Chrome."""
self.AppendTab(pyauto.GURL(self.EMPTY_PAGE_URL))
self.assertTrue(self.ActivateTab(0))
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.KillRendererProcess(
self.GetBrowserInfo()['windows'][0]['tabs'][0]['renderer_pid'])
def testKillNotificationProcess(self):
"""Test killing a notification doesn't crash Chrome."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.KillRendererProcess(self.GetActiveNotifications()[0]['pid'])
self.WaitForNotificationCount(0)
def testIncognitoNotification(self):
"""Test notifications in incognito window."""
self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
self.NavigateToURL(self.TEST_PAGE_URL, 1, 0)
self.assertTrue(self.ActivateTab(0, 1))
self._RequestPermission(windex=1)
self.assertTrue(self.WaitForInfobarCount(1, windex=1))
self.PerformActionOnInfobar('accept', infobar_index=0, windex=1)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL, windex=1)
self.assertEquals(1, len(self.GetActiveNotifications()))
def testSpecialURLNotification(self):
"""Test a page cannot create a notification to a chrome: url."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification('chrome://settings',
wait_for_display=False);
self.assertFalse(self.GetActiveNotifications())
def testCloseTabWithPermissionInfobar(self):
"""Test that user can close tab when infobar present."""
self.AppendTab(pyauto.GURL('about:blank'))
self.ActivateTab(0)
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.CloseTab()
def testNavigateAwayWithPermissionInfobar(self):
"""Test navigating away when an infobar is present, then trying to create a
notification from the same page."""
self.AppendTab(pyauto.GURL('about:blank'))
self.assertTrue(self.ActivateTab(0))
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.NavigateToURL(self.TEST_PAGE_URL)
self._RequestPermission()
self.assertTrue(self.WaitForInfobarCount(1))
self.PerformActionOnInfobar('accept', 0)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
def testCrashRendererNotificationRemain(self):
"""Test crashing renderer does not close or crash notification."""
self._AllowAllOrigins()
self.AppendTab(pyauto.GURL('about:blank'))
self.ActivateTab(0)
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateHTMLNotification(self.EMPTY_PAGE_URL)
self.assertEquals(1, len(self.GetActiveNotifications()))
self.KillRendererProcess(
self.GetBrowserInfo()['windows'][0]['tabs'][0]['renderer_pid'])
self.assertEquals(1, len(self.GetActiveNotifications()))
def testNotificationOrderAfterClosingOne(self):
"""Tests that closing a notification leaves the rest
of the notifications in the correct order.
"""
if self.IsWin7():
return # crbug.com/66072
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateSimpleNotification('', 'Title1', '')
self._CreateSimpleNotification('', 'Title2', '')
self._CreateSimpleNotification('', 'Title3', '')
old_notifications = self.GetAllNotifications()
self.assertEquals(3, len(old_notifications))
self.CloseNotification(1)
new_notifications = self.GetAllNotifications()
self.assertEquals(2, len(new_notifications))
self.assertEquals(old_notifications[0]['id'], new_notifications[0]['id'])
self.assertEquals(old_notifications[2]['id'], new_notifications[1]['id'])
def testNotificationReplacement(self):
"""Test that we can replace a notification using the replaceId."""
self._AllowAllOrigins()
self.NavigateToURL(self.TEST_PAGE_URL)
self._CreateSimpleNotification('', 'Title2', '', 'chat')
self.WaitForNotificationCount(1)
# Since this notification has the same replaceId, 'chat', it should replace
# the first notification.
self._CreateHTMLNotification(self.EMPTY_PAGE_URL, 'chat')
notifications = self.GetActiveNotifications()
self.assertEquals(1, len(notifications))
self.assertEquals(self.EMPTY_PAGE_URL, notifications[0]['content_url'])
if __name__ == '__main__':
pyauto_functional.Main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment