diff options
author | Torne (Richard Coles) <torne@google.com> | 2013-12-18 16:25:09 +0000 |
---|---|---|
committer | Torne (Richard Coles) <torne@google.com> | 2013-12-18 16:25:09 +0000 |
commit | a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7 (patch) | |
tree | dafc1c6417406a7fbd422ad0bb890e96909ef564 /chrome/test | |
parent | d5f893c0bc79db3066bb5ae5d3d972ba1be7dd5f (diff) | |
download | chromium_org-a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7.tar.gz |
Merge from Chromium at DEPS revision 240154
This commit was generated by merge_to_master.py.
Change-Id: I8f2ba858cf0e7f413dddedc2ae91dc37f7136c2e
Diffstat (limited to 'chrome/test')
74 files changed, 877 insertions, 1449 deletions
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarTestAnimationListener.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarTestAnimationListener.java index 97b39a3800..0133f42efd 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarTestAnimationListener.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarTestAnimationListener.java @@ -5,11 +5,11 @@ package org.chromium.chrome.test.util; import android.os.SystemClock; -import java.util.concurrent.TimeUnit; - import org.chromium.chrome.browser.infobar.AnimationHelper; import org.chromium.chrome.browser.infobar.InfoBarContainer; +import java.util.concurrent.TimeUnit; + /** * Allow tests to register for animation finished notifications. */ diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarUtil.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarUtil.java index 70a9f740dc..128af87c20 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarUtil.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/InfoBarUtil.java @@ -5,11 +5,9 @@ package org.chromium.chrome.test.util; import android.test.ActivityInstrumentationTestCase2; -import android.test.TouchUtils; import android.view.View; import org.chromium.chrome.R; - import org.chromium.chrome.browser.infobar.InfoBar; import org.chromium.content.browser.test.util.TestTouchUtils; diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TabBaseTabUtils.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TabBaseTabUtils.java new file mode 100644 index 0000000000..abc74c6390 --- /dev/null +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TabBaseTabUtils.java @@ -0,0 +1,87 @@ +// Copyright 2013 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. + +package org.chromium.chrome.test.util; + +import android.view.ContextMenu; + +import org.chromium.chrome.browser.EmptyTabObserver; +import org.chromium.chrome.browser.TabBase; +import org.chromium.content.browser.ContentViewClient; +import org.chromium.content.browser.test.util.CallbackHelper; +import org.chromium.content.browser.test.util.TestCallbackHelperContainer; +import org.chromium.content.browser.test.util.TestContentViewClient; +import org.chromium.content.browser.test.util.TestContentViewClientWrapper; +import org.chromium.content.browser.test.util.TestWebContentsObserver; + +import java.lang.ref.WeakReference; + +/** + * A utility class that contains methods generic to all Tabs tests. + */ +public class TabBaseTabUtils { + private static TestContentViewClient createTestContentViewClientForTab(TabBase tab) { + ContentViewClient client = tab.getContentView().getContentViewClient(); + if (client instanceof TestContentViewClient) return (TestContentViewClient) client; + + TestContentViewClient testClient = new TestContentViewClientWrapper(client); + tab.getContentView().setContentViewClient(testClient); + return testClient; + } + + public static class TestCallbackHelperContainerForTab extends TestCallbackHelperContainer { + private final OnCloseTabHelper mOnCloseTabHelper; + private final OnContextMenuShownHelper mOnContextMenuShownHelper; + + public TestCallbackHelperContainerForTab(TabBase tab) { + super(createTestContentViewClientForTab(tab), + new TestWebContentsObserver(tab.getContentView().getContentViewCore())); + mOnCloseTabHelper = new OnCloseTabHelper(); + mOnContextMenuShownHelper = new OnContextMenuShownHelper(); + tab.addObserver(new EmptyTabObserver() { + @Override + public void onDestroyed(TabBase tab) { + mOnCloseTabHelper.notifyCalled(); + } + + @Override + public void onContextMenuShown(TabBase tab, ContextMenu menu) { + mOnContextMenuShownHelper.notifyCalled(menu); + } + }); + } + + public static class OnCloseTabHelper extends CallbackHelper { + } + + public static class OnContextMenuShownHelper extends CallbackHelper { + private WeakReference<ContextMenu> mContextMenu; + + public void notifyCalled(ContextMenu menu) { + mContextMenu = new WeakReference<ContextMenu>(menu); + notifyCalled(); + } + + public ContextMenu getContextMenu() { + assert getCallCount() > 0; + return mContextMenu.get(); + } + } + + public OnCloseTabHelper getOnCloseTabHelper() { + return mOnCloseTabHelper; + } + + public OnContextMenuShownHelper getOnContextMenuShownHelper() { + return mOnContextMenuShownHelper; + } + } + + /** + * Creates, binds and returns a TestCallbackHelperContainer for a given Tab. + */ + public static TestCallbackHelperContainerForTab getTestCallbackHelperContainer(TabBase tab) { + return tab == null ? null : new TestCallbackHelperContainerForTab(tab); + } +} diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TranslateUtil.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TranslateUtil.java index 7abc29f9eb..1e4bcddcc5 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TranslateUtil.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/TranslateUtil.java @@ -4,17 +4,13 @@ package org.chromium.chrome.test.util; -import android.content.Context; import android.test.ActivityInstrumentationTestCase2; -import android.test.TouchUtils; import android.text.SpannableString; import android.text.style.ClickableSpan; import android.view.View; -import android.view.ViewGroup; import android.widget.TextView; import org.chromium.chrome.R; - import org.chromium.chrome.browser.infobar.InfoBar; import org.chromium.content.browser.test.util.TestTouchUtils; diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/contextmenu/ContextMenuUtils.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/contextmenu/ContextMenuUtils.java new file mode 100644 index 0000000000..2365a28468 --- /dev/null +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/contextmenu/ContextMenuUtils.java @@ -0,0 +1,127 @@ +// Copyright 2013 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. + +package org.chromium.chrome.test.util.browser.contextmenu; + +import android.test.ActivityInstrumentationTestCase2; +import android.text.TextUtils; +import android.view.ContextMenu; +import android.view.MenuItem; + +import junit.framework.Assert; + +import org.chromium.chrome.browser.TabBase; +import org.chromium.chrome.test.util.TabBaseTabUtils; +import org.chromium.chrome.test.util.TabBaseTabUtils.TestCallbackHelperContainerForTab; +import org.chromium.content.browser.test.util.Criteria; +import org.chromium.content.browser.test.util.CriteriaHelper; +import org.chromium.content.browser.test.util.DOMUtils; + +import java.util.concurrent.TimeoutException; + +/** + * A utility class to help open and interact with context menus triggered by a WebContents. + */ +public class ContextMenuUtils { + /** + * Opens a context menu. + * @param testCase The test harness. + * @param tab The tab to open a context menu for. + * @param client The helper client for {@code tab} that can wait for events. If + * this is {@code null} one will be built automatically. + * @param openerDOMNodeId The DOM node to long press to open the context menu for. + * @return The {@link ContextMenu} that was opened. + * @throws InterruptedException + * @throws TimeoutException + */ + public static ContextMenu openContextMenu(ActivityInstrumentationTestCase2 testCase, + TabBase tab, TestCallbackHelperContainerForTab client, String openerDOMNodeId) + throws InterruptedException, TimeoutException { + if (client == null) client = TabBaseTabUtils.getTestCallbackHelperContainer(tab); + + TestCallbackHelperContainerForTab.OnContextMenuShownHelper helper = + client.getOnContextMenuShownHelper(); + + int callCount = helper.getCallCount(); + DOMUtils.longPressNode(testCase, tab.getContentView(), client, openerDOMNodeId); + + helper.waitForCallback(callCount); + return helper.getContextMenu(); + } + + /** + * Opens and selects an item from a context menu. + * @param testCase The test harness. + * @param tab The tab to open a context menu for. + * @param client The helper client for {@code tab} that can wait for events. If + * this is {@code null} one will be built automatically. + * @param openerDOMNodeId The DOM node to long press to open the context menu for. + * @param itemId The context menu item ID to select. + * @throws InterruptedException + * @throws TimeoutException + */ + public static void selectContextMenuItem(ActivityInstrumentationTestCase2 testCase, + TabBase tab, TestCallbackHelperContainerForTab client, String openerDOMNodeId, + final int itemId) throws InterruptedException, TimeoutException { + ContextMenu menu = openContextMenu(testCase, tab, client, openerDOMNodeId); + Assert.assertNotNull("Failed to open context menu", menu); + + selectOpenContextMenuItem(testCase, menu, itemId); + } + + /** + * Opens and selects an item from a context menu. + * @param testCase The test harness. + * @param tab The tab to open a context menu for. + * @param client The helper client for {@code tab} that can wait for events. If + * this is {@code null} one will be built automatically. + * @param openerDOMNodeId The DOM node to long press to open the context menu for. + * @param itemTitle The title of the context menu item to select. + * @throws InterruptedException + * @throws TimeoutException + */ + public static void selectContextMenuItemByTitle(ActivityInstrumentationTestCase2 testCase, + TabBase tab, TestCallbackHelperContainerForTab client, String openerDOMNodeId, + String itemTitle) throws InterruptedException, TimeoutException { + + ContextMenu menu = openContextMenu(testCase, tab, client, openerDOMNodeId); + Assert.assertNotNull("Failed to open context menu", menu); + + Integer itemId = null; + for (int i = 0; i < menu.size(); i++) { + MenuItem item = menu.getItem(i); + if (TextUtils.equals(item.getTitle(), itemTitle)) { + itemId = item.getItemId(); + break; + } + } + Assert.assertNotNull("Couldn't find context menu item for '" + itemTitle + "'", itemId); + + selectOpenContextMenuItem(testCase, menu, itemId); + } + + private static void selectOpenContextMenuItem(final ActivityInstrumentationTestCase2 testCase, + final ContextMenu menu, final int itemId) throws InterruptedException { + MenuItem item = menu.findItem(itemId); + Assert.assertNotNull("Could not find '" + itemId + "' in menu", item); + Assert.assertTrue("'" + itemId + "' is not visible", item.isVisible()); + Assert.assertTrue("'" + itemId + "' is not enabled", item.isEnabled()); + + testCase.getInstrumentation().runOnMainSync(new Runnable() { + @Override + public void run() { + boolean activated = menu.performIdentifierAction(itemId, 0); + Assert.assertTrue("Failed to activate '" + itemId + "' in menu", activated); + } + }); + + Assert.assertTrue("Activity did not regain focus.", + CriteriaHelper.pollForCriteria(new Criteria() { + @Override + public boolean isSatisfied() { + return testCase.getActivity().hasWindowFocus(); + } + })); + } +}
\ No newline at end of file diff --git a/chrome/test/automation/automation_proxy.cc b/chrome/test/automation/automation_proxy.cc index 1c8cdb233b..aae6691b5b 100644 --- a/chrome/test/automation/automation_proxy.cc +++ b/chrome/test/automation/automation_proxy.cc @@ -7,7 +7,7 @@ #include <sstream> #include "base/basictypes.h" -#include "base/debug/trace_event.h" +#include "base/file_util.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/synchronization/waitable_event.h" @@ -410,31 +410,13 @@ bool AutomationProxy::BeginTracing(const std::string& category_patterns) { bool AutomationProxy::EndTracing(std::string* json_trace_output) { bool success = false; - size_t num_trace_chunks = 0; - if (!Send(new AutomationMsg_EndTracing(&num_trace_chunks, &success)) || - !success) + base::FilePath path; + if (!Send(new AutomationMsg_EndTracing(&path, &success)) || !success) return false; - std::string chunk; - base::debug::TraceResultBuffer buffer; - base::debug::TraceResultBuffer::SimpleOutput output; - buffer.SetOutputCallback(output.GetCallback()); - - // TODO(jbates): See bug 100255, IPC send fails if message is too big. This - // code can be simplified if that limitation is fixed. - // Workaround IPC payload size limitation by getting chunks. - buffer.Start(); - for (size_t i = 0; i < num_trace_chunks; ++i) { - // The broswer side AutomationProvider resets state at BeginTracing, - // so it can recover even after this fails mid-way. - if (!Send(new AutomationMsg_GetTracingOutput(&chunk, &success)) || - !success) - return false; - buffer.AddFragment(chunk); - } - buffer.Finish(); - - *json_trace_output = output.json_output; + bool ok = base::ReadFileToString(path, json_trace_output); + DCHECK(ok); + base::DeleteFile(path, false); return true; } diff --git a/chrome/test/base/browser_with_test_window_test.cc b/chrome/test/base/browser_with_test_window_test.cc index 16f22df321..bf97a7914e 100644 --- a/chrome/test/base/browser_with_test_window_test.cc +++ b/chrome/test/base/browser_with_test_window_test.cc @@ -65,9 +65,7 @@ void BrowserWithTestWindowTest::SetUp() { // is responsible for cleaning it up (usually by NativeWidget destruction). window_.reset(CreateBrowserWindow()); - Browser::CreateParams params(profile(), host_desktop_type_); - params.window = window_.get(); - browser_.reset(new Browser(params)); + browser_.reset(CreateBrowser(profile(), host_desktop_type_, window_.get())); } void BrowserWithTestWindowTest::TearDown() { @@ -195,3 +193,12 @@ void BrowserWithTestWindowTest::DestroyProfile(TestingProfile* profile) { BrowserWindow* BrowserWithTestWindowTest::CreateBrowserWindow() { return new TestBrowserWindow(); } + +Browser* BrowserWithTestWindowTest::CreateBrowser( + Profile* profile, + chrome::HostDesktopType host_desktop_type, + BrowserWindow* browser_window) { + Browser::CreateParams params(profile, host_desktop_type); + params.window = browser_window; + return new Browser(params); +} diff --git a/chrome/test/base/browser_with_test_window_test.h b/chrome/test/base/browser_with_test_window_test.h index 91bb325460..dfe88ebf0a 100644 --- a/chrome/test/base/browser_with_test_window_test.h +++ b/chrome/test/base/browser_with_test_window_test.h @@ -141,6 +141,12 @@ class BrowserWithTestWindowTest : public testing::Test { // value. Can return NULL to use the default window created by Browser. virtual BrowserWindow* CreateBrowserWindow(); + // Creates the browser given |profile|, |host_desktop_type| and + // |browser_window|. The caller owns the return value. + virtual Browser* CreateBrowser(Profile* profile, + chrome::HostDesktopType host_desktop_type, + BrowserWindow* browser_window); + private: // We need to create a MessageLoop, otherwise a bunch of things fails. content::TestBrowserThreadBundle thread_bundle_; diff --git a/chrome/test/base/chrome_test_launcher.cc b/chrome/test/base/chrome_test_launcher.cc index f14ace3810..adb7747248 100644 --- a/chrome/test/base/chrome_test_launcher.cc +++ b/chrome/test/base/chrome_test_launcher.cc @@ -19,7 +19,6 @@ #include "chrome/app/chrome_main_delegate.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" -#include "chrome/common/chrome_switches.h" #include "chrome/test/base/chrome_test_suite.h" #include "content/public/app/content_main.h" #include "content/public/browser/browser_thread.h" diff --git a/chrome/test/base/chrome_test_launcher.h b/chrome/test/base/chrome_test_launcher.h index b9254d3176..12521d15f0 100644 --- a/chrome/test/base/chrome_test_launcher.h +++ b/chrome/test/base/chrome_test_launcher.h @@ -5,9 +5,8 @@ #ifndef CHROME_TEST_BASE_CHROME_TEST_LAUNCHER_H_ #define CHROME_TEST_BASE_CHROME_TEST_LAUNCHER_H_ -// Launches Chrome tests using |launcher_delegate|. |default_jobs| is number -// of test jobs to be run in parallel, unless overridden from the command line. -// Returns exit code. +// Launches Chrome browser tests. |default_jobs| is number of test jobs to be +// run in parallel, unless overridden from the command line. Returns exit code. int LaunchChromeTests(int default_jobs, int argc, char** argv); #endif // CHROME_TEST_BASE_CHROME_TEST_LAUNCHER_H_ diff --git a/chrome/test/base/chrome_test_suite.cc b/chrome/test/base/chrome_test_suite.cc index 8fb1ff7f45..d259336d79 100644 --- a/chrome/test/base/chrome_test_suite.cc +++ b/chrome/test/base/chrome_test_suite.cc @@ -17,14 +17,12 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_content_browser_client.h" -#include "chrome/browser/extensions/chrome_extensions_browser_client.h" #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/chrome_extensions_client.h" #include "chrome/common/url_constants.h" -#include "chrome/test/base/testing_browser_process.h" #include "chrome/utility/chrome_content_utility_client.h" #include "content/public/test/test_launcher.h" #include "extensions/common/extension_paths.h" @@ -84,33 +82,14 @@ bool IsCrosPythonProcess() { #endif // defined(OS_CHROMEOS) } +// Initializes services needed by both unit tests and browser tests. +// See also ChromeUnitTestSuite for additional services created for unit tests. class ChromeTestSuiteInitializer : public testing::EmptyTestEventListener { public: ChromeTestSuiteInitializer() { } virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE { - DCHECK(!g_browser_process); - g_browser_process = new TestingBrowserProcess; - - SetUpContentClients(); - SetUpExtensionsClients(); - } - - virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE { - TearDownExtensionsClients(); - TearDownContentClients(); - - if (g_browser_process) { - BrowserProcess* browser_process = g_browser_process; - // g_browser_process must be NULL during its own destruction. - g_browser_process = NULL; - delete browser_process; - } - } - - private: - void SetUpContentClients() { content_client_.reset(new ChromeContentClient); content::SetContentClient(content_client_.get()); // TODO(ios): Bring this back once ChromeContentBrowserClient is building. @@ -122,7 +101,7 @@ class ChromeTestSuiteInitializer : public testing::EmptyTestEventListener { #endif } - void TearDownContentClients() { + virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE { // TODO(ios): Bring this back once ChromeContentBrowserClient is building. #if !defined(OS_IOS) browser_content_client_.reset(); @@ -130,19 +109,9 @@ class ChromeTestSuiteInitializer : public testing::EmptyTestEventListener { #endif content_client_.reset(); content::SetContentClient(NULL); - } - - void SetUpExtensionsClients() { - extensions_browser_client_.reset( - new extensions::ChromeExtensionsBrowserClient); - extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); - } - - void TearDownExtensionsClients() { - extensions_browser_client_.reset(); - extensions::ExtensionsBrowserClient::Set(NULL); - } + } + private: // Client implementations for the content module. scoped_ptr<ChromeContentClient> content_client_; // TODO(ios): Bring this back once ChromeContentBrowserClient is building. @@ -151,10 +120,6 @@ class ChromeTestSuiteInitializer : public testing::EmptyTestEventListener { scoped_ptr<chrome::ChromeContentUtilityClient> utility_content_client_; #endif - // Client implementations for the extensions module. - scoped_ptr<extensions::ChromeExtensionsBrowserClient> - extensions_browser_client_; - DISALLOW_COPY_AND_ASSIGN(ChromeTestSuiteInitializer); }; diff --git a/chrome/test/base/chrome_test_suite.h b/chrome/test/base/chrome_test_suite.h index 9186f28e2f..62f97b300c 100644 --- a/chrome/test/base/chrome_test_suite.h +++ b/chrome/test/base/chrome_test_suite.h @@ -15,12 +15,15 @@ namespace base { class StatsTable; } +// Test suite for unit and browser tests. Creates services needed by both. +// See also ChromeUnitTestSuite for additional services created for unit tests. class ChromeTestSuite : public content::ContentTestSuiteBase { public: ChromeTestSuite(int argc, char** argv); virtual ~ChromeTestSuite(); protected: + // base::TestSuite overrides: virtual void Initialize() OVERRIDE; virtual void Shutdown() OVERRIDE; @@ -35,6 +38,8 @@ class ChromeTestSuite : public content::ContentTestSuiteBase { std::string stats_filename_; scoped_ptr<base::StatsTable> stats_table_; + + DISALLOW_COPY_AND_ASSIGN(ChromeTestSuite); }; #endif // CHROME_TEST_BASE_CHROME_TEST_SUITE_H_ diff --git a/chrome/test/base/chrome_unit_test_suite.cc b/chrome/test/base/chrome_unit_test_suite.cc new file mode 100644 index 0000000000..e7fcbde270 --- /dev/null +++ b/chrome/test/base/chrome_unit_test_suite.cc @@ -0,0 +1,46 @@ +// Copyright 2013 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. + +#include "chrome/test/base/chrome_unit_test_suite.h" + +#include "chrome/test/base/testing_browser_process.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +// Creates a TestingBrowserProcess for each test. +class ChromeUnitTestSuiteInitializer : public testing::EmptyTestEventListener { + public: + ChromeUnitTestSuiteInitializer() {} + virtual ~ChromeUnitTestSuiteInitializer() {} + + virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE { + TestingBrowserProcess::CreateInstance(); + } + + virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE { + TestingBrowserProcess::DeleteInstance(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(ChromeUnitTestSuiteInitializer); +}; + +} // namespace + +ChromeUnitTestSuite::ChromeUnitTestSuite(int argc, char** argv) + : ChromeTestSuite(argc, argv) {} + +ChromeUnitTestSuite::~ChromeUnitTestSuite() {} + +void ChromeUnitTestSuite::Initialize() { + // Add an additional listener to do the extra initialization for unit tests. + // It will be started before the base class listeners and ended after the + // base class listeners. + testing::TestEventListeners& listeners = + testing::UnitTest::GetInstance()->listeners(); + listeners.Append(new ChromeUnitTestSuiteInitializer); + + ChromeTestSuite::Initialize(); +} diff --git a/chrome/test/base/chrome_unit_test_suite.h b/chrome/test/base/chrome_unit_test_suite.h new file mode 100644 index 0000000000..4367d2122c --- /dev/null +++ b/chrome/test/base/chrome_unit_test_suite.h @@ -0,0 +1,26 @@ +// Copyright 2013 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. + +#ifndef CHROME_TEST_BASE_CHROME_UNIT_TEST_SUITE_H_ +#define CHROME_TEST_BASE_CHROME_UNIT_TEST_SUITE_H_ + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "chrome/test/base/chrome_test_suite.h" + +// Test suite for unit tests. Creates additional stub services that are not +// needed for browser tests (e.g. a TestingBrowserProcess). +class ChromeUnitTestSuite : public ChromeTestSuite { + public: + ChromeUnitTestSuite(int argc, char** argv); + virtual ~ChromeUnitTestSuite(); + + // base::TestSuite overrides: + virtual void Initialize() OVERRIDE; + + private: + DISALLOW_COPY_AND_ASSIGN(ChromeUnitTestSuite); +}; + +#endif // CHROME_TEST_BASE_CHROME_UNIT_TEST_SUITE_H_ diff --git a/chrome/test/base/in_process_browser_test.cc b/chrome/test/base/in_process_browser_test.cc index 946b5895c6..b5acd26a95 100644 --- a/chrome/test/base/in_process_browser_test.cc +++ b/chrome/test/base/in_process_browser_test.cc @@ -145,13 +145,8 @@ InProcessBrowserTest::~InProcessBrowserTest() { } void InProcessBrowserTest::SetUp() { - // Undo TestingBrowserProcess creation in ChromeTestSuite. - // TODO(phajdan.jr): Extract a smaller test suite so we don't need this. - DCHECK(g_browser_process); - BrowserProcess* old_browser_process = g_browser_process; - // g_browser_process must be NULL during its own destruction. - g_browser_process = NULL; - delete old_browser_process; + // Browser tests will create their own g_browser_process later. + DCHECK(!g_browser_process); CommandLine* command_line = CommandLine::ForCurrentProcess(); // Allow subclasses to change the command line before running any tests. @@ -178,7 +173,7 @@ void InProcessBrowserTest::SetUp() { #if defined(OS_CHROMEOS) // Make sure that the log directory exists. base::FilePath log_dir = logging::GetSessionLogFile(*command_line).DirName(); - file_util::CreateDirectory(log_dir); + base::CreateDirectory(log_dir); #endif // defined(OS_CHROMEOS) #if defined(OS_MACOSX) diff --git a/chrome/test/base/module_system_test.cc b/chrome/test/base/module_system_test.cc index f4aa6455ed..dd4ca2a8cd 100644 --- a/chrome/test/base/module_system_test.cc +++ b/chrome/test/base/module_system_test.cc @@ -99,10 +99,11 @@ class ModuleSystemTest::StringSourceMap : public ModuleSystem::SourceMap { StringSourceMap() {} virtual ~StringSourceMap() {} - virtual v8::Handle<v8::Value> GetSource(const std::string& name) OVERRIDE { + virtual v8::Handle<v8::Value> GetSource(v8::Isolate* isolate, + const std::string& name) OVERRIDE { if (source_map_.count(name) == 0) - return v8::Undefined(); - return v8::String::New(source_map_[name].c_str()); + return v8::Undefined(isolate); + return v8::String::NewFromUtf8(isolate, source_map_[name].c_str()); } virtual bool Contains(const std::string& name) OVERRIDE { @@ -188,9 +189,10 @@ void ModuleSystemTest::ExpectNoAssertionsMade() { } v8::Handle<v8::Object> ModuleSystemTest::CreateGlobal(const std::string& name) { - v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); - v8::Handle<v8::Object> object = v8::Object::New(); - v8::Context::GetCurrent()->Global()->Set(v8::String::New(name.c_str()), - object); - return handle_scope.Close(object); + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope handle_scope(isolate); + v8::Local<v8::Object> object = v8::Object::New(isolate); + isolate->GetCurrentContext()->Global()->Set( + v8::String::NewFromUtf8(isolate, name.c_str()), object); + return handle_scope.Escape(object); } diff --git a/chrome/test/base/run_all_unittests.cc b/chrome/test/base/run_all_unittests.cc index 9ac8d73087..ae5b60067b 100644 --- a/chrome/test/base/run_all_unittests.cc +++ b/chrome/test/base/run_all_unittests.cc @@ -4,11 +4,11 @@ #include "base/bind.h" #include "base/test/launcher/unit_test_launcher.h" -#include "chrome/test/base/chrome_test_suite.h" +#include "chrome/test/base/chrome_unit_test_suite.h" #include "content/public/test/unittest_test_suite.h" int main(int argc, char **argv) { - content::UnitTestTestSuite test_suite(new ChromeTestSuite(argc, argv)); + content::UnitTestTestSuite test_suite(new ChromeUnitTestSuite(argc, argv)); return base::LaunchUnitTests( argc, argv, base::Bind(&content::UnitTestTestSuite::Run, diff --git a/chrome/test/base/test_browser_window.h b/chrome/test/base/test_browser_window.h index 917e32d7cd..6144eb642f 100644 --- a/chrome/test/base/test_browser_window.h +++ b/chrome/test/base/test_browser_window.h @@ -104,7 +104,8 @@ class TestBrowserWindow : public BrowserWindow { bool already_bookmarked) OVERRIDE {} virtual void ShowTranslateBubble( content::WebContents* contents, - TranslateBubbleModel::ViewState view_state) OVERRIDE {} + TranslateBubbleModel::ViewState view_state, + TranslateErrors::Type error_type) OVERRIDE {} #if defined(ENABLE_ONE_CLICK_SIGNIN) virtual void ShowOneClickSigninBubble( OneClickSigninBubbleType type, diff --git a/chrome/test/base/testing_browser_process.cc b/chrome/test/base/testing_browser_process.cc index c119e07be4..7e19e98888 100644 --- a/chrome/test/base/testing_browser_process.cc +++ b/chrome/test/base/testing_browser_process.cc @@ -10,6 +10,7 @@ #include "chrome/browser/background/background_mode_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_impl.h" +#include "chrome/browser/extensions/chrome_extensions_browser_client.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/bookmarks/bookmark_prompt_controller.h" @@ -35,7 +36,7 @@ #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/browser_policy_connector.h" #else -#include "chrome/browser/policy/policy_service_stub.h" +#include "components/policy/core/common/policy_service_stub.h" #endif // defined(ENABLE_CONFIGURATION_POLICY) #if defined(ENABLE_FULL_PRINTING) @@ -48,6 +49,20 @@ TestingBrowserProcess* TestingBrowserProcess::GetGlobal() { return static_cast<TestingBrowserProcess*>(g_browser_process); } +// static +void TestingBrowserProcess::CreateInstance() { + DCHECK(!g_browser_process); + g_browser_process = new TestingBrowserProcess; +} + +// static +void TestingBrowserProcess::DeleteInstance() { + // g_browser_process must be NULL during its own destruction. + BrowserProcess* browser_process = g_browser_process; + g_browser_process = NULL; + delete browser_process; +} + TestingBrowserProcess::TestingBrowserProcess() : notification_service_(content::NotificationService::Create()), module_ref_count_(0), @@ -58,7 +73,10 @@ TestingBrowserProcess::TestingBrowserProcess() local_state_(NULL), io_thread_(NULL), system_request_context_(NULL), - platform_part_(new TestingBrowserProcessPlatformPart()) { + platform_part_(new TestingBrowserProcessPlatformPart()), + extensions_browser_client_( + new extensions::ChromeExtensionsBrowserClient) { + extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); } TestingBrowserProcess::~TestingBrowserProcess() { @@ -66,6 +84,7 @@ TestingBrowserProcess::~TestingBrowserProcess() { #if defined(ENABLE_CONFIGURATION_POLICY) SetBrowserPolicyConnector(NULL); #endif + extensions::ExtensionsBrowserClient::Set(NULL); // Destructors for some objects owned by TestingBrowserProcess will use // g_browser_process if it is not NULL, so it must be NULL before proceeding. @@ -428,3 +447,13 @@ void TestingBrowserProcess::SetStorageMonitor( storage_monitor_ = storage_monitor.Pass(); #endif } + +/////////////////////////////////////////////////////////////////////////////// + +TestingBrowserProcessInitializer::TestingBrowserProcessInitializer() { + TestingBrowserProcess::CreateInstance(); +} + +TestingBrowserProcessInitializer::~TestingBrowserProcessInitializer() { + TestingBrowserProcess::DeleteInstance(); +} diff --git a/chrome/test/base/testing_browser_process.h b/chrome/test/base/testing_browser_process.h index 76129ddb68..51e4986854 100644 --- a/chrome/test/base/testing_browser_process.h +++ b/chrome/test/base/testing_browser_process.h @@ -30,6 +30,10 @@ namespace content { class NotificationService; } +namespace extensions { +class ExtensionsBrowserClient; +} + namespace policy { class BrowserPolicyConnector; class PolicyService; @@ -41,8 +45,11 @@ class PrerenderTracker; class TestingBrowserProcess : public BrowserProcess { public: - TestingBrowserProcess(); - virtual ~TestingBrowserProcess(); + // Initializes |g_browser_process| with a new TestingBrowserProcess. + static void CreateInstance(); + + // Cleanly destroys |g_browser_process|, which has special deletion semantics. + static void DeleteInstance(); // Convenience method to get g_browser_process as a TestingBrowserProcess*. static TestingBrowserProcess* GetGlobal(); @@ -125,6 +132,10 @@ class TestingBrowserProcess : public BrowserProcess { void SetStorageMonitor(scoped_ptr<StorageMonitor> storage_monitor); private: + // See CreateInstance() and DestoryInstance() above. + TestingBrowserProcess(); + virtual ~TestingBrowserProcess(); + scoped_ptr<content::NotificationService> notification_service_; unsigned int module_ref_count_; std::string app_locale_; @@ -164,7 +175,32 @@ class TestingBrowserProcess : public BrowserProcess { scoped_ptr<BrowserProcessPlatformPart> platform_part_; + scoped_ptr<extensions::ExtensionsBrowserClient> extensions_browser_client_; + DISALLOW_COPY_AND_ASSIGN(TestingBrowserProcess); }; +// RAII (resource acquisition is initialization) for TestingBrowserProcess. +// Allows you to initialize TestingBrowserProcess/NotificationService before +// other member variables. +// +// This can be helpful if you are running a unit test inside the browser_tests +// suite because browser_tests do not make a TestingBrowserProcess for you. +// +// class MyUnitTestRunningAsBrowserTest : public testing::Test { +// ...stuff... +// private: +// TestingBrowserProcessInitializer initializer_; +// LocalState local_state_; // Needs a BrowserProcess to initialize. +// NotificationRegistrar registar_; // Needs NotificationService. +// }; +class TestingBrowserProcessInitializer { + public: + TestingBrowserProcessInitializer(); + ~TestingBrowserProcessInitializer(); + + private: + DISALLOW_COPY_AND_ASSIGN(TestingBrowserProcessInitializer); +}; + #endif // CHROME_TEST_BASE_TESTING_BROWSER_PROCESS_H_ diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index 3fa3ef91dc..816e6bc82d 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc @@ -60,6 +60,7 @@ #include "chrome/test/base/testing_pref_service_syncable.h" #include "chrome/test/base/ui_test_utils.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" +#include "components/policy/core/common/policy_service.h" #include "components/user_prefs/user_prefs.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" @@ -75,13 +76,13 @@ #include "testing/gmock/include/gmock/gmock.h" #if defined(ENABLE_CONFIGURATION_POLICY) -#include "chrome/browser/policy/configuration_policy_provider.h" -#include "chrome/browser/policy/policy_service_impl.h" #include "chrome/browser/policy/schema_registry_service.h" #include "chrome/browser/policy/schema_registry_service_factory.h" +#include "components/policy/core/common/configuration_policy_provider.h" +#include "components/policy/core/common/policy_service_impl.h" #include "components/policy/core/common/schema.h" #else -#include "chrome/browser/policy/policy_service_stub.h" +#include "components/policy/core/common/policy_service_stub.h" #endif // defined(ENABLE_CONFIGURATION_POLICY) #if defined(ENABLE_MANAGED_USERS) @@ -175,6 +176,7 @@ TestingProfile::TestingProfile() incognito_(false), force_incognito_(false), original_profile_(NULL), + guest_session_(false), last_session_exited_cleanly_(true), browser_context_dependency_manager_( BrowserContextDependencyManager::GetInstance()), @@ -193,6 +195,7 @@ TestingProfile::TestingProfile(const base::FilePath& path) incognito_(false), force_incognito_(false), original_profile_(NULL), + guest_session_(false), last_session_exited_cleanly_(true), profile_path_(path), browser_context_dependency_manager_( @@ -210,6 +213,7 @@ TestingProfile::TestingProfile(const base::FilePath& path, incognito_(false), force_incognito_(false), original_profile_(NULL), + guest_session_(false), last_session_exited_cleanly_(true), profile_path_(path), browser_context_dependency_manager_( @@ -232,7 +236,9 @@ TestingProfile::TestingProfile( scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy, scoped_ptr<PrefServiceSyncable> prefs, bool incognito, + bool guest_session, const std::string& managed_user_id, + scoped_ptr<policy::PolicyService> policy_service, const TestingFactories& factories) : start_time_(Time::Now()), prefs_(prefs.release()), @@ -240,6 +246,7 @@ TestingProfile::TestingProfile( incognito_(incognito), force_incognito_(false), original_profile_(NULL), + guest_session_(guest_session), managed_user_id_(managed_user_id), last_session_exited_cleanly_(true), extension_special_storage_policy_(extension_policy), @@ -247,7 +254,8 @@ TestingProfile::TestingProfile( browser_context_dependency_manager_( BrowserContextDependencyManager::GetInstance()), resource_context_(NULL), - delegate_(delegate) { + delegate_(delegate), + policy_service_(policy_service.release()) { // If no profile path was supplied, create one. if (profile_path_.empty()) { @@ -291,7 +299,7 @@ void TestingProfile::CreateTempProfileDir() { base::FilePath fallback_dir( system_tmp_dir.AppendASCII("TestingProfilePath")); base::DeleteFile(fallback_dir, true); - file_util::CreateDirectory(fallback_dir); + base::CreateDirectory(fallback_dir); if (!temp_dir_.Set(fallback_dir)) { // That shouldn't happen, but if it does, try to recover. LOG(ERROR) << "Failed to use a fallback temporary directory."; @@ -319,7 +327,7 @@ void TestingProfile::Init() { CreateTestingPrefService(); if (!base::PathExists(profile_path_)) - file_util::CreateDirectory(profile_path_); + base::CreateDirectory(profile_path_); // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl // anymore, after converting the PrefService to a PKS. Until then it must @@ -330,11 +338,19 @@ void TestingProfile::Init() { extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory( this, extensions::TestExtensionSystem::Build); - // If there is no separate original profile specified for this profile, then - // force preferences to be registered - this allows tests to create a + // If no original profile was specified for this profile: register preferences + // even if this is an incognito profile - this allows tests to create a // standalone incognito profile while still having prefs registered. + if (!IsOffTheRecord() || !original_profile_) { + user_prefs::PrefRegistrySyncable* pref_registry = + static_cast<user_prefs::PrefRegistrySyncable*>( + prefs_->DeprecatedGetPrefRegistry()); + browser_context_dependency_manager_-> + RegisterProfilePrefsForServices(this, pref_registry); + } + browser_context_dependency_manager_->CreateBrowserContextServicesForTest( - this, !original_profile_); + this); #if defined(ENABLE_NOTIFICATIONS) // Install profile keyed service factory hooks for dummy/test services @@ -628,22 +644,25 @@ void TestingProfile::CreateTestingPrefService() { } void TestingProfile::CreateProfilePolicyConnector() { - scoped_ptr<policy::PolicyService> service; #if defined(ENABLE_CONFIGURATION_POLICY) schema_registry_service_ = policy::SchemaRegistryServiceFactory::CreateForContext( this, policy::Schema(), NULL); CHECK_EQ(schema_registry_service_.get(), policy::SchemaRegistryServiceFactory::GetForContext(this)); +#endif // defined(ENABLE_CONFIGURATION_POLICY) - std::vector<policy::ConfigurationPolicyProvider*> providers; - service.reset(new policy::PolicyServiceImpl( - providers, policy::PolicyServiceImpl::PreprocessCallback())); +if (!policy_service_) { +#if defined(ENABLE_CONFIGURATION_POLICY) + std::vector<policy::ConfigurationPolicyProvider*> providers; + policy_service_.reset(new policy::PolicyServiceImpl( + providers, policy::PolicyServiceImpl::PreprocessCallback())); #else - service.reset(new policy::PolicyServiceStub()); + policy_service_.reset(new policy::PolicyServiceStub()); #endif + } profile_policy_connector_.reset(new policy::ProfilePolicyConnector()); - profile_policy_connector_->InitForTesting(service.Pass()); + profile_policy_connector_->InitForTesting(policy_service_.Pass()); policy::ProfilePolicyConnectorFactory::GetInstance()->SetServiceForTesting( this, profile_policy_connector_.get()); CHECK_EQ(profile_policy_connector_.get(), @@ -843,7 +862,7 @@ bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) { } bool TestingProfile::IsGuestSession() const { - return false; + return guest_session_; } Profile::ExitType TestingProfile::GetLastSessionExitType() { @@ -853,7 +872,8 @@ Profile::ExitType TestingProfile::GetLastSessionExitType() { TestingProfile::Builder::Builder() : build_called_(false), delegate_(NULL), - incognito_(false) { + incognito_(false), + guest_session_(false) { } TestingProfile::Builder::~Builder() { @@ -881,14 +901,23 @@ void TestingProfile::Builder::SetIncognito() { incognito_ = true; } +void TestingProfile::Builder::SetGuestSession() { + guest_session_ = true; +} + void TestingProfile::Builder::SetManagedUserId( const std::string& managed_user_id) { managed_user_id_ = managed_user_id; } +void TestingProfile::Builder::SetPolicyService( + scoped_ptr<policy::PolicyService> policy_service) { + policy_service_ = policy_service.Pass(); +} + void TestingProfile::Builder::AddTestingFactory( BrowserContextKeyedServiceFactory* service_factory, - BrowserContextKeyedServiceFactory::FactoryFunction callback) { + BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) { testing_factories_.push_back(std::make_pair(service_factory, callback)); } @@ -902,6 +931,8 @@ scoped_ptr<TestingProfile> TestingProfile::Builder::Build() { extension_policy_, pref_service_.Pass(), incognito_, + guest_session_, managed_user_id_, + policy_service_.Pass(), testing_factories_)); } diff --git a/chrome/test/base/testing_profile.h b/chrome/test/base/testing_profile.h index 48b0962b59..a74d91951f 100644 --- a/chrome/test/base/testing_profile.h +++ b/chrome/test/base/testing_profile.h @@ -31,6 +31,7 @@ class URLRequestContextGetter; } namespace policy { +class PolicyService; class ProfilePolicyConnector; class SchemaRegistryService; } @@ -62,8 +63,9 @@ class TestingProfile : public Profile { TestingProfile(); typedef std::vector<std::pair< - BrowserContextKeyedServiceFactory*, - BrowserContextKeyedServiceFactory::FactoryFunction> > TestingFactories; + BrowserContextKeyedServiceFactory*, + BrowserContextKeyedServiceFactory::TestingFactoryFunction> > + TestingFactories; // Helper class for building an instance of TestingProfile (allows injecting // mocks for various services prior to profile initialization). @@ -85,7 +87,7 @@ class TestingProfile : public Profile { // are applied before the ProfileKeyedServices are created. void AddTestingFactory( BrowserContextKeyedServiceFactory* service_factory, - BrowserContextKeyedServiceFactory::FactoryFunction callback); + BrowserContextKeyedServiceFactory::TestingFactoryFunction callback); // Sets the ExtensionSpecialStoragePolicy to be returned by // GetExtensionSpecialStoragePolicy(). @@ -101,10 +103,16 @@ class TestingProfile : public Profile { // Makes the Profile being built an incognito profile. void SetIncognito(); + // Makes the Profile being built a guest profile. + void SetGuestSession(); + // Sets the managed user ID (which is empty by default). If it is set to a // non-empty string, the profile is managed. void SetManagedUserId(const std::string& managed_user_id); + // Sets the PolicyService to be used by this profile. + void SetPolicyService(scoped_ptr<policy::PolicyService> policy_service); + // Creates the TestingProfile using previously-set settings. scoped_ptr<TestingProfile> Build(); @@ -118,7 +126,9 @@ class TestingProfile : public Profile { base::FilePath path_; Delegate* delegate_; bool incognito_; + bool guest_session_; std::string managed_user_id_; + scoped_ptr<policy::PolicyService> policy_service_; TestingFactories testing_factories_; DISALLOW_COPY_AND_ASSIGN(Builder); @@ -144,7 +154,9 @@ class TestingProfile : public Profile { scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy, scoped_ptr<PrefServiceSyncable> prefs, bool incognito, + bool guest_session, const std::string& managed_user_id, + scoped_ptr<policy::PolicyService> policy_service, const TestingFactories& factories); virtual ~TestingProfile(); @@ -360,6 +372,8 @@ class TestingProfile : public Profile { scoped_ptr<Profile> incognito_profile_; Profile* original_profile_; + bool guest_session_; + std::string managed_user_id_; // Did the last session exit cleanly? Default is true. @@ -402,6 +416,8 @@ class TestingProfile : public Profile { Delegate* delegate_; std::string profile_name_; + + scoped_ptr<policy::PolicyService> policy_service_; }; #endif // CHROME_TEST_BASE_TESTING_PROFILE_H_ diff --git a/chrome/test/base/tracing.cc b/chrome/test/base/tracing.cc index 7060b9b6c9..5aa07e7e4d 100644 --- a/chrome/test/base/tracing.cc +++ b/chrome/test/base/tracing.cc @@ -4,19 +4,21 @@ #include "chrome/test/base/tracing.h" -#include "base/debug/trace_event.h" +#include "base/file_util.h" +#include "base/files/file_path.h" #include "base/memory/singleton.h" #include "base/message_loop/message_loop.h" +#include "base/strings/string_util.h" +#include "base/timer/timer.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/trace_controller.h" -#include "content/public/browser/trace_subscriber.h" +#include "content/public/browser/tracing_controller.h" #include "content/public/test/test_utils.h" namespace { using content::BrowserThread; -class InProcessTraceController : public content::TraceSubscriber { +class InProcessTraceController { public: static InProcessTraceController* GetInstance() { return Singleton<InProcessTraceController>::get(); @@ -29,8 +31,10 @@ class InProcessTraceController : public content::TraceSubscriber { bool BeginTracing(const std::string& category_patterns) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - return content::TraceController::GetInstance()->BeginTracing( - this, category_patterns, base::debug::TraceLog::RECORD_UNTIL_FULL); + return content::TracingController::GetInstance()->EnableRecording( + category_patterns, content::TracingController::DEFAULT_OPTIONS, + content::TracingController::EnableRecordingDoneCallback()); + return true; } bool BeginTracingWithWatch(const std::string& category_patterns, @@ -40,9 +44,11 @@ class InProcessTraceController : public content::TraceSubscriber { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(num_occurrences > 0); watch_notification_count_ = num_occurrences; - return BeginTracing(category_patterns) && - content::TraceController::GetInstance()->SetWatchEvent( - this, category_name, event_name); + return content::TracingController::GetInstance()->SetWatchEvent( + category_name, event_name, + base::Bind(&InProcessTraceController::OnWatchEventMatched, + base::Unretained(this))) && + BeginTracing(category_patterns); } bool WaitForWatchEvent(base::TimeDelta timeout) { @@ -67,20 +73,16 @@ class InProcessTraceController : public content::TraceSubscriber { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); using namespace base::debug; - TraceResultBuffer::SimpleOutput output; - trace_buffer_.SetOutputCallback(output.GetCallback()); - - trace_buffer_.Start(); - if (!content::TraceController::GetInstance()->EndTracingAsync(this)) + if (!content::TracingController::GetInstance()->DisableRecording( + base::FilePath(), + base::Bind(&InProcessTraceController::OnTraceDataCollected, + base::Unretained(this), + base::Unretained(json_trace_output)))) return false; + // Wait for OnEndTracingComplete() to quit the message loop. - // OnTraceDataCollected may be called multiple times while blocking here. message_loop_runner_ = new content::MessageLoopRunner; message_loop_runner_->Run(); - trace_buffer_.Finish(); - trace_buffer_.SetOutputCallback(TraceResultBuffer::OutputCallback()); - - *json_trace_output = output.json_output; // Watch notifications can occur during this method's message loop run, but // not after, so clear them here. @@ -91,19 +93,40 @@ class InProcessTraceController : public content::TraceSubscriber { private: friend struct DefaultSingletonTraits<InProcessTraceController>; - // TraceSubscriber implementation - virtual void OnEndTracingComplete() OVERRIDE { + void OnEndTracingComplete() { message_loop_runner_->Quit(); } - // TraceSubscriber implementation - virtual void OnTraceDataCollected( - const scoped_refptr<base::RefCountedString>& trace_fragment) OVERRIDE { - trace_buffer_.AddFragment(trace_fragment->data()); + void OnTraceDataCollected(std::string* json_trace_output, + const base::FilePath& path) { + BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, + base::Bind(&InProcessTraceController::ReadTraceData, + base::Unretained(this), + base::Unretained(json_trace_output), + path)); } - // TraceSubscriber implementation - virtual void OnEventWatchNotification() OVERRIDE { + void ReadTraceData(std::string* json_trace_output, + const base::FilePath& path) { + json_trace_output->clear(); + bool ok = base::ReadFileToString(path, json_trace_output); + DCHECK(ok); + base::DeleteFile(path, false); + + // The callers expect an array of trace events. + const char* preamble = "{\"traceEvents\": "; + const char* trailout = "}"; + DCHECK(StartsWithASCII(*json_trace_output, preamble, true)); + DCHECK(EndsWith(*json_trace_output, trailout, true)); + json_trace_output->erase(0, strlen(preamble)); + json_trace_output->erase(json_trace_output->end() - 1); + + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, + base::Bind(&InProcessTraceController::OnEndTracingComplete, + base::Unretained(this))); + } + + void OnWatchEventMatched() { if (watch_notification_count_ == 0) return; if (--watch_notification_count_ == 0) { @@ -118,9 +141,6 @@ class InProcessTraceController : public content::TraceSubscriber { message_loop_runner_->Quit(); } - // For collecting trace data asynchronously. - base::debug::TraceResultBuffer trace_buffer_; - scoped_refptr<content::MessageLoopRunner> message_loop_runner_; base::OneShotTimer<InProcessTraceController> timer_; diff --git a/chrome/test/base/ui_test_utils.cc b/chrome/test/base/ui_test_utils.cc index 59f4560828..e60fe0e250 100644 --- a/chrome/test/base/ui_test_utils.cc +++ b/chrome/test/base/ui_test_utils.cc @@ -36,6 +36,7 @@ #include "chrome/browser/search_engines/template_url_service_test_util.h" #include "chrome/browser/thumbnails/render_widget_snapshot_taker.h" #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog.h" +#include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" @@ -321,6 +322,10 @@ bool GetRelativeBuildDirectory(base::FilePath* build_dir) { } AppModalDialog* WaitForAppModalDialog() { + AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance(); + if (dialog_queue->HasActiveDialog()) + return dialog_queue->active_dialog(); + content::WindowedNotificationObserver observer( chrome::NOTIFICATION_APP_MODAL_DIALOG_SHOWN, content::NotificationService::AllSources()); diff --git a/chrome/test/base/v8_unit_test.cc b/chrome/test/base/v8_unit_test.cc index 92a9b4222d..623f815a8f 100644 --- a/chrome/test/base/v8_unit_test.cc +++ b/chrome/test/base/v8_unit_test.cc @@ -90,13 +90,13 @@ bool V8UnitTest::RunJavascriptTestF( if (!ExecuteJavascriptLibraries()) return false; - v8::Context::Scope context_scope(isolate_, context_); v8::HandleScope handle_scope(isolate_); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate_, context_); + v8::Context::Scope context_scope(context); v8::Handle<v8::Value> functionProperty = - context->Global()->Get(v8::String::New("runTest")); + context->Global()->Get(v8::String::NewFromUtf8(isolate_, "runTest")); EXPECT_FALSE(functionProperty.IsEmpty()); if (::testing::Test::HasNonfatalFailure()) return false; @@ -106,12 +106,20 @@ bool V8UnitTest::RunJavascriptTestF( v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionProperty); - v8::Local<v8::Array> params = v8::Array::New(); - params->Set(0, v8::String::New(testFixture.data(), testFixture.size())); - params->Set(1, v8::String::New(testName.data(), testName.size())); + v8::Local<v8::Array> params = v8::Array::New(isolate_); + params->Set(0, + v8::String::NewFromUtf8(isolate_, + testFixture.data(), + v8::String::kNormalString, + testFixture.size())); + params->Set(1, + v8::String::NewFromUtf8(isolate_, + testName.data(), + v8::String::kNormalString, + testName.size())); v8::Handle<v8::Value> args[] = { - v8::Boolean::New(false), - v8::String::New("RUN_TEST_F"), + v8::Boolean::New(isolate_, false), + v8::String::NewFromUtf8(isolate_, "RUN_TEST_F"), params }; @@ -156,46 +164,60 @@ void V8UnitTest::InitPathsAndLibraries() { } void V8UnitTest::SetUp() { - v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(); - v8::Handle<v8::String> logString = v8::String::New("log"); + v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate_); + v8::Handle<v8::String> logString = v8::String::NewFromUtf8(isolate_, "log"); v8::Handle<v8::FunctionTemplate> logFunction = v8::FunctionTemplate::New(&V8UnitTest::Log); global->Set(logString, logFunction); // Set up chrome object for chrome.send(). - v8::Handle<v8::ObjectTemplate> chrome = v8::ObjectTemplate::New(); - global->Set(v8::String::New("chrome"), chrome); - chrome->Set(v8::String::New("send"), - v8::FunctionTemplate::New(&V8UnitTest::ChromeSend)); + v8::Handle<v8::ObjectTemplate> chrome = v8::ObjectTemplate::New(isolate_); + global->Set(v8::String::NewFromUtf8(isolate_, "chrome"), chrome); + chrome->Set(v8::String::NewFromUtf8(isolate_, "send"), + v8::FunctionTemplate::New(isolate_, &V8UnitTest::ChromeSend)); // Set up console object for console.log(), etc. - v8::Handle<v8::ObjectTemplate> console = v8::ObjectTemplate::New(); - global->Set(v8::String::New("console"), console); + v8::Handle<v8::ObjectTemplate> console = v8::ObjectTemplate::New(isolate_); + global->Set(v8::String::NewFromUtf8(isolate_, "console"), console); console->Set(logString, logFunction); - console->Set(v8::String::New("info"), logFunction); - console->Set(v8::String::New("warn"), logFunction); - console->Set(v8::String::New("error"), - v8::FunctionTemplate::New(&V8UnitTest::Error)); + console->Set(v8::String::NewFromUtf8(isolate_, "info"), logFunction); + console->Set(v8::String::NewFromUtf8(isolate_, "warn"), logFunction); + console->Set(v8::String::NewFromUtf8(isolate_, "error"), + v8::FunctionTemplate::New(isolate_, &V8UnitTest::Error)); context_.Reset(isolate_, v8::Context::New(isolate_, NULL, global)); } void V8UnitTest::SetGlobalStringVar(const std::string& var_name, const std::string& value) { - v8::Context::Scope context_scope(isolate_, context_); - v8::Local<v8::Context>::New(isolate_, context_)->Global() - ->Set(v8::String::New(var_name.c_str(), var_name.length()), - v8::String::New(value.c_str(), value.length())); + v8::Local<v8::Context> context = + v8::Local<v8::Context>::New(isolate_, context_); + v8::Context::Scope context_scope(context); + context->Global()->Set( + v8::String::NewFromUtf8(isolate_, + var_name.c_str(), + v8::String::kNormalString, + var_name.length()), + v8::String::NewFromUtf8( + isolate_, value.c_str(), v8::String::kNormalString, value.length())); } void V8UnitTest::ExecuteScriptInContext(const base::StringPiece& script_source, const base::StringPiece& script_name) { - v8::Context::Scope context_scope(isolate_, context_); v8::HandleScope handle_scope(isolate_); - v8::Handle<v8::String> source = v8::String::New(script_source.data(), - script_source.size()); - v8::Handle<v8::String> name = v8::String::New(script_name.data(), - script_name.size()); + v8::Local<v8::Context> context = + v8::Local<v8::Context>::New(isolate_, context_); + v8::Context::Scope context_scope(context); + v8::Handle<v8::String> source = + v8::String::NewFromUtf8(isolate_, + script_source.data(), + v8::String::kNormalString, + script_source.size()); + v8::Handle<v8::String> name = + v8::String::NewFromUtf8(isolate_, + script_name.data(), + v8::String::kNormalString, + script_name.size()); v8::TryCatch try_catch; v8::Handle<v8::Script> script = v8::Script::Compile(source, name); @@ -229,13 +251,13 @@ std::string V8UnitTest::ExceptionToString(const v8::TryCatch& try_catch) { } void V8UnitTest::TestFunction(const std::string& function_name) { - v8::Context::Scope context_scope(isolate_, context_); v8::HandleScope handle_scope(isolate_); v8::Local<v8::Context> context = v8::Local<v8::Context>::New(isolate_, context_); + v8::Context::Scope context_scope(context); - v8::Handle<v8::Value> functionProperty = - context->Global()->Get(v8::String::New(function_name.c_str())); + v8::Handle<v8::Value> functionProperty = context->Global()->Get( + v8::String::NewFromUtf8(isolate_, function_name.c_str())); ASSERT_FALSE(functionProperty.IsEmpty()); ASSERT_TRUE(functionProperty->IsFunction()); v8::Handle<v8::Function> function = diff --git a/chrome/test/base/view_event_test_base.cc b/chrome/test/base/view_event_test_base.cc index ac4d8acd71..d88bf9cb21 100644 --- a/chrome/test/base/view_event_test_base.cc +++ b/chrome/test/base/view_event_test_base.cc @@ -9,6 +9,7 @@ #include "base/message_loop/message_loop.h" #include "base/strings/string_number_conversions.h" #include "chrome/test/base/interactive_test_utils.h" +#include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" #include "ui/base/ime/input_method_initializer.h" @@ -74,6 +75,9 @@ const int kMouseMoveDelayMS = 200; ViewEventTestBase::ViewEventTestBase() : window_(NULL), content_view_(NULL) { + // The TestingBrowserProcess must be created in the constructor because there + // are tests that require it before SetUp() is called. + TestingBrowserProcess::CreateInstance(); } void ViewEventTestBase::Done() { @@ -194,6 +198,7 @@ views::Widget* ViewEventTestBase::GetWidget() { } ViewEventTestBase::~ViewEventTestBase() { + TestingBrowserProcess::DeleteInstance(); } void ViewEventTestBase::StartMessageLoopAndRunTest() { diff --git a/chrome/test/chromedriver/OWNERS b/chrome/test/chromedriver/OWNERS index 3c04aef485..a3cb147a59 100644 --- a/chrome/test/chromedriver/OWNERS +++ b/chrome/test/chromedriver/OWNERS @@ -1,4 +1,3 @@ chrisgao@chromium.org craigdh@chromium.org frankf@chromium.org -kkania@chromium.org diff --git a/chrome/test/chromedriver/capabilities.cc b/chrome/test/chromedriver/capabilities.cc index 6e884c907d..8479a844c5 100644 --- a/chrome/test/chromedriver/capabilities.cc +++ b/chrome/test/chromedriver/capabilities.cc @@ -262,6 +262,8 @@ Status ParseChromeOptions( base::Bind(&ParseString, &capabilities->android_package); parser_map["androidProcess"] = base::Bind(&ParseString, &capabilities->android_process); + parser_map["androidUseRunningApp"] = + base::Bind(&ParseBoolean, &capabilities->android_use_running_app); parser_map["args"] = base::Bind(&ParseSwitches); } else if (is_existing) { parser_map["debuggerAddress"] = base::Bind(&ParseUseExistingBrowser); @@ -405,7 +407,8 @@ std::string Switches::ToString() const { } Capabilities::Capabilities() - : detach(false), + : android_use_running_app(false), + detach(false), force_devtools_screenshot(false) {} Capabilities::~Capabilities() {} diff --git a/chrome/test/chromedriver/capabilities.h b/chrome/test/chromedriver/capabilities.h index c5f52cd461..fceb06c8b5 100644 --- a/chrome/test/chromedriver/capabilities.h +++ b/chrome/test/chromedriver/capabilities.h @@ -79,6 +79,8 @@ struct Capabilities { std::string android_process; + bool android_use_running_app; + base::FilePath binary; // If provided, the remote debugging address to connect to. diff --git a/chrome/test/chromedriver/chrome/chrome_android_impl.cc b/chrome/test/chromedriver/chrome/chrome_android_impl.cc index 41da0a045b..9cbbe55783 100644 --- a/chrome/test/chromedriver/chrome/chrome_android_impl.cc +++ b/chrome/test/chromedriver/chrome/chrome_android_impl.cc @@ -26,6 +26,6 @@ std::string ChromeAndroidImpl::GetOperatingSystemName() { } Status ChromeAndroidImpl::QuitImpl() { - return device_->StopApp(); + return device_->TearDown(); } diff --git a/chrome/test/chromedriver/chrome/device_manager.cc b/chrome/test/chromedriver/chrome/device_manager.cc index fa217ad9c2..bd62a2f310 100644 --- a/chrome/test/chromedriver/chrome/device_manager.cc +++ b/chrome/test/chromedriver/chrome/device_manager.cc @@ -27,11 +27,12 @@ Device::~Device() { release_callback_.Run(); } -Status Device::StartApp(const std::string& package, - const std::string& activity, - const std::string& process, - const std::string& args, - int port) { +Status Device::SetUp(const std::string& package, + const std::string& activity, + const std::string& process, + const std::string& args, + bool use_running_app, + int port) { if (!active_package_.empty()) return Status(kUnknownError, active_package_ + " was launched and has not been quit"); @@ -40,13 +41,9 @@ Status Device::StartApp(const std::string& package, if (!status.IsOk()) return status; - status = adb_->ClearAppData(serial_, package); - if (!status.IsOk()) - return status; - std::string known_activity; - std::string device_socket; std::string command_line_file; + std::string device_socket; std::string exec_name; if (package.compare("org.chromium.content_shell_apk") == 0) { known_activity = ".ContentShellActivity"; @@ -66,32 +63,49 @@ Status Device::StartApp(const std::string& package, exec_name = "chrome"; } - if (!known_activity.empty()) { - if (!activity.empty() || !process.empty()) - return Status(kUnknownError, "known package " + package + - " does not accept activity/process"); - } else if (activity.empty()) { - return Status(kUnknownError, "WebView apps require activity name"); - } + if (!use_running_app) { + status = adb_->ClearAppData(serial_, package); + if (!status.IsOk()) + return status; - if (!command_line_file.empty()) { - status = adb_->SetCommandLineFile(serial_, command_line_file, exec_name, - args); + if (!known_activity.empty()) { + if (!activity.empty() || + !process.empty()) + return Status(kUnknownError, "known package " + package + + " does not accept activity/process"); + } else if (activity.empty()) { + return Status(kUnknownError, "WebView apps require activity name"); + } + + if (!command_line_file.empty()) { + status = adb_->SetCommandLineFile(serial_, command_line_file, exec_name, + args); + if (!status.IsOk()) + return status; + } + + status = adb_->Launch(serial_, package, + known_activity.empty() ? activity : known_activity); if (!status.IsOk()) return status; + + active_package_ = package; } + this->ForwardDevtoolsPort(package, process, device_socket, port); - status = adb_->Launch(serial_, package, - known_activity.empty() ? activity : known_activity); - if (!status.IsOk()) - return status; - active_package_ = package; + return status; +} +Status Device::ForwardDevtoolsPort(const std::string& package, + const std::string& process, + std::string& device_socket, + int port) { if (device_socket.empty()) { // Assume this is a WebView app. int pid; - status = adb_->GetPidByName(serial_, process.empty() ? package : process, - &pid); + Status status = adb_->GetPidByName(serial_, + process.empty() ? package : process, + &pid); if (!status.IsOk()) { if (process.empty()) status.AddDetails( @@ -104,7 +118,7 @@ Status Device::StartApp(const std::string& package, return adb_->ForwardPort(serial_, port, device_socket); } -Status Device::StopApp() { +Status Device::TearDown() { if (!active_package_.empty()) { std::string response; Status status = adb_->ForceStop(serial_, active_package_); diff --git a/chrome/test/chromedriver/chrome/device_manager.h b/chrome/test/chromedriver/chrome/device_manager.h index 5c56c2e3a9..6b812c545b 100644 --- a/chrome/test/chromedriver/chrome/device_manager.h +++ b/chrome/test/chromedriver/chrome/device_manager.h @@ -22,12 +22,14 @@ class Device { public: ~Device(); - Status StartApp(const std::string& package, - const std::string& activity, - const std::string& process, - const std::string& args, - int port); - Status StopApp(); + Status SetUp(const std::string& package, + const std::string& activity, + const std::string& process, + const std::string& args, + bool use_running_app, + int port); + + Status TearDown(); private: friend class DeviceManager; @@ -36,6 +38,11 @@ class Device { Adb* adb, base::Callback<void()> release_callback); + Status ForwardDevtoolsPort(const std::string& package, + const std::string& process, + std::string& device_socket, + int port); + const std::string serial_; std::string active_package_; Adb* adb_; diff --git a/chrome/test/chromedriver/chrome/device_manager_unittest.cc b/chrome/test/chromedriver/chrome/device_manager_unittest.cc index 2f78db685b..4894b53ea2 100644 --- a/chrome/test/chromedriver/chrome/device_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/device_manager_unittest.cc @@ -102,17 +102,18 @@ TEST(Device, StartStopApp) { DeviceManager device_manager(&adb); scoped_ptr<Device> device1; ASSERT_TRUE(device_manager.AcquireDevice(&device1).IsOk()); - ASSERT_TRUE(device1->StopApp().IsOk()); - ASSERT_TRUE(device1->StartApp("a.chrome.package", "", "", "", 0).IsOk()); - ASSERT_FALSE(device1->StartApp("a.chrome.package", "", "", "", 0).IsOk()); - ASSERT_TRUE(device1->StopApp().IsOk()); - ASSERT_FALSE(device1->StartApp( - "a.chrome.package", "an.activity", "", "", 0).IsOk()); - ASSERT_FALSE(device1->StartApp("a.package", "", "", "", 0).IsOk()); - ASSERT_TRUE(device1->StartApp("a.package", "an.activity", "", "", 0).IsOk()); - ASSERT_TRUE(device1->StopApp().IsOk()); - ASSERT_TRUE(device1->StopApp().IsOk()); - ASSERT_TRUE(device1->StartApp( - "a.package", "an.activity", "a.process", "", 0).IsOk()); - ASSERT_TRUE(device1->StopApp().IsOk()); + ASSERT_TRUE(device1->TearDown().IsOk()); + ASSERT_TRUE(device1->SetUp("a.chrome.package", "", "", "", false, 0).IsOk()); + ASSERT_FALSE(device1->SetUp("a.chrome.package", "", "", "", false, 0).IsOk()); + ASSERT_TRUE(device1->TearDown().IsOk()); + ASSERT_FALSE(device1->SetUp( + "a.chrome.package", "an.activity", "", "", false, 0).IsOk()); + ASSERT_FALSE(device1->SetUp("a.package", "", "", "", false, 0).IsOk()); + ASSERT_TRUE(device1->SetUp( + "a.package", "an.activity", "", "", false, 0).IsOk()); + ASSERT_TRUE(device1->TearDown().IsOk()); + ASSERT_TRUE(device1->TearDown().IsOk()); + ASSERT_TRUE(device1->SetUp( + "a.package", "an.activity", "a.process", "", false, 0).IsOk()); + ASSERT_TRUE(device1->TearDown().IsOk()); } diff --git a/chrome/test/chromedriver/chrome/log.cc b/chrome/test/chromedriver/chrome/log.cc index 62be86dc87..75ed25b0b1 100644 --- a/chrome/test/chromedriver/chrome/log.cc +++ b/chrome/test/chromedriver/chrome/log.cc @@ -87,7 +87,7 @@ std::string PrettyPrintValue(const base::Value& value) { base::JSONWriter::WriteWithOptions( &value, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json); #if defined(OS_WIN) - RemoveChars(json, "\r", &json); + base::RemoveChars(json, "\r", &json); #endif // Remove the trailing newline. if (json.length()) diff --git a/chrome/test/chromedriver/chrome/zip_reader.cc b/chrome/test/chromedriver/chrome/zip_reader.cc index 25aee0cf1d..218c8d7e77 100644 --- a/chrome/test/chromedriver/chrome/zip_reader.cc +++ b/chrome/test/chromedriver/chrome/zip_reader.cc @@ -192,7 +192,7 @@ bool ZipReader::ExtractCurrentEntryToFilePath( // If this is a directory, just create it and return. if (current_entry_info()->is_directory()) - return file_util::CreateDirectory(output_file_path); + return base::CreateDirectory(output_file_path); const int open_result = unzOpenCurrentFile(zip_file_); if (open_result != UNZ_OK) @@ -201,7 +201,7 @@ bool ZipReader::ExtractCurrentEntryToFilePath( // We can't rely on parent directory entries being specified in the // zip, so we make sure they are created. base::FilePath output_dir_path = output_file_path.DirName(); - if (!file_util::CreateDirectory(output_dir_path)) + if (!base::CreateDirectory(output_dir_path)) return false; net::FileStream stream(NULL); diff --git a/chrome/test/chromedriver/chrome_launcher.cc b/chrome/test/chromedriver/chrome_launcher.cc index a501143e13..d293d43da5 100644 --- a/chrome/test/chromedriver/chrome_launcher.cc +++ b/chrome/test/chromedriver/chrome_launcher.cc @@ -360,12 +360,14 @@ Status LaunchAndroidChrome( switches.SetSwitch(kCommonSwitches[i]); switches.SetSwitch("disable-fre"); switches.SetSwitch("enable-remote-debugging"); - status = device->StartApp(capabilities.android_package, - capabilities.android_activity, - capabilities.android_process, - switches.ToString(), port); + status = device->SetUp(capabilities.android_package, + capabilities.android_activity, + capabilities.android_process, + switches.ToString(), + capabilities.android_use_running_app, + port); if (!status.IsOk()) { - device->StopApp(); + device->TearDown(); return status; } @@ -480,7 +482,7 @@ Status ProcessExtension(const std::string& extension, // 'encoded lines be no more than 76 characters long'. Just remove any // newlines. std::string extension_base64; - RemoveChars(extension, "\n", &extension_base64); + base::RemoveChars(extension, "\n", &extension_base64); std::string decoded_extension; if (!base::Base64Decode(extension_base64, &decoded_extension)) return Status(kUnknownError, "cannot base64 decode"); @@ -495,8 +497,7 @@ Status ProcessExtension(const std::string& extension, if (key_len != public_key.size()) return Status(kUnknownError, "invalid public key length"); std::string public_key_base64; - if (!base::Base64Encode(public_key, &public_key_base64)) - return Status(kUnknownError, "cannot base64 encode public key"); + base::Base64Encode(public_key, &public_key_base64); std::string id = GenerateExtensionId(public_key); // Unzip the crx file. @@ -522,7 +523,27 @@ Status ProcessExtension(const std::string& extension, base::DictionaryValue* manifest; if (!manifest_value || !manifest_value->GetAsDictionary(&manifest)) return Status(kUnknownError, "invalid manifest"); - if (!manifest->HasKey("key")) { + + std::string manifest_key_base64; + if (manifest->GetString("key", &manifest_key_base64)) { + // If there is a key in both the header and the manifest, use the key in the + // manifest. This allows chromedriver users users who generate dummy crxs + // to set the manifest key and have a consistent ID. + std::string manifest_key; + if (!base::Base64Decode(manifest_key_base64, &manifest_key)) + return Status(kUnknownError, "'key' in manifest is not base64 encoded"); + std::string manifest_id = GenerateExtensionId(manifest_key); + if (id != manifest_id) { + LOG(WARNING) + << "Public key in crx header is different from key in manifest" + << std::endl << "key from header: " << public_key_base64 + << std::endl << "key from manifest: " << manifest_key_base64 + << std::endl << "generated extension id from header key: " << id + << std::endl << "generated extension id from manifest key: " + << manifest_id; + id = manifest_id; + } + } else { manifest->SetString("key", public_key_base64); base::JSONWriter::Write(manifest, &manifest_data); if (file_util::WriteFile( @@ -635,7 +656,7 @@ Status PrepareUserDataDir( const base::DictionaryValue* custom_prefs, const base::DictionaryValue* custom_local_state) { base::FilePath default_dir = user_data_dir.AppendASCII("Default"); - if (!file_util::CreateDirectory(default_dir)) + if (!base::CreateDirectory(default_dir)) return Status(kUnknownError, "cannot create default profile directory"); Status status = WritePrefsFile( diff --git a/chrome/test/chromedriver/chrome_launcher_unittest.cc b/chrome/test/chromedriver/chrome_launcher_unittest.cc index ff4ce711df..e75051b773 100644 --- a/chrome/test/chromedriver/chrome_launcher_unittest.cc +++ b/chrome/test/chromedriver/chrome_launcher_unittest.cc @@ -40,12 +40,36 @@ bool AddExtensionForInstall(const std::string& relative_path, return false; std::string crx_encoded; - if (!base::Base64Encode(crx_contents, &crx_encoded)) - return false; + base::Base64Encode(crx_contents, &crx_encoded); extensions->push_back(crx_encoded); return true; } +TEST(ProcessExtensions, GenerateIds) { + std::vector<std::string> extensions; + base::ScopedTempDir extension_dir; + Switches switches; + std::vector<std::string> bg_pages; + + ASSERT_TRUE(AddExtensionForInstall("no_key_in_manifest.crx", &extensions)); + ASSERT_TRUE(AddExtensionForInstall("same_key_as_header.crx", &extensions)); + ASSERT_TRUE(AddExtensionForInstall("diff_key_from_header.crx", &extensions)); + + ASSERT_TRUE(extension_dir.CreateUniqueTempDir()); + + Status status = internal::ProcessExtensions(extensions, extension_dir.path(), + false, &switches, &bg_pages); + + ASSERT_EQ(kOk, status.code()) << status.message(); + ASSERT_EQ(3u, bg_pages.size()); + ASSERT_EQ("chrome-extension://llphabdmknikmpmkioimgdfbohinlekl/" + "_generated_background_page.html", bg_pages[0]); + ASSERT_EQ("chrome-extension://dfdeoklpcichfcnoaomfpagfiibhomnh/" + "_generated_background_page.html", bg_pages[1]); + ASSERT_EQ("chrome-extension://ioccpomhcpklobebcbeohnmffkmcokbm/" + "_generated_background_page.html", bg_pages[2]); +} + TEST(ProcessExtensions, SingleExtensionWithBgPage) { std::vector<std::string> extensions; ASSERT_TRUE(AddExtensionForInstall("ext_slow_loader.crx", &extensions)); diff --git a/chrome/test/chromedriver/client/chromedriver.py b/chrome/test/chromedriver/client/chromedriver.py index 8f84d0b9db..dccfde469e 100644 --- a/chrome/test/chromedriver/client/chromedriver.py +++ b/chrome/test/chromedriver/client/chromedriver.py @@ -62,9 +62,9 @@ class ChromeDriver(object): def __init__(self, server_url, chrome_binary=None, android_package=None, android_activity=None, android_process=None, - chrome_switches=None, chrome_extensions=None, - chrome_log_path=None, debugger_address=None, - browser_log_level=None): + android_use_running_app=None, chrome_switches=None, + chrome_extensions=None, chrome_log_path=None, + debugger_address=None, browser_log_level=None): self._executor = command_executor.CommandExecutor(server_url) options = {} @@ -74,6 +74,8 @@ class ChromeDriver(object): options['androidActivity'] = android_activity if android_process: options['androidProcess'] = android_process + if android_use_running_app: + options['androidUseRunningApp'] = android_use_running_app elif chrome_binary: options['binary'] = chrome_binary diff --git a/chrome/test/chromedriver/js/add_cookie.js b/chrome/test/chromedriver/js/add_cookie.js index f79946e42e..385e79c09c 100644 --- a/chrome/test/chromedriver/js/add_cookie.js +++ b/chrome/test/chromedriver/js/add_cookie.js @@ -82,7 +82,8 @@ function addCookie(cookie) { var newCookie = name + '=' + value; newCookie += '; path=' + (path || '/'); - newCookie += '; domain=' + (domain || document.domain); + if (domain) + newCookie += '; domain=' + domain; if (cookie['expiry']) { var expiredDate = new Date(cookie['expiry'] * 1000); newCookie += '; expires=' + expiredDate.toUTCString(); diff --git a/chrome/test/chromedriver/net/websocket.cc b/chrome/test/chromedriver/net/websocket.cc index 76d17dac75..2c214f9c14 100644 --- a/chrome/test/chromedriver/net/websocket.cc +++ b/chrome/test/chromedriver/net/websocket.cc @@ -121,7 +121,7 @@ void WebSocket::OnSocketConnect(int code) { return; } - CHECK(base::Base64Encode(base::RandBytesAsString(16), &sec_key_)); + base::Base64Encode(base::RandBytesAsString(16), &sec_key_); std::string handshake = base::StringPrintf( "GET %s HTTP/1.1\r\n" "Host: %s\r\n" @@ -210,8 +210,8 @@ void WebSocket::OnReadDuringHandshake(const char* data, int len) { const char kMagicKey[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string websocket_accept; - CHECK(base::Base64Encode(base::SHA1HashString(sec_key_ + kMagicKey), - &websocket_accept)); + base::Base64Encode(base::SHA1HashString(sec_key_ + kMagicKey), + &websocket_accept); scoped_refptr<net::HttpResponseHeaders> headers( new net::HttpResponseHeaders( net::HttpUtil::AssembleRawHeaders( @@ -262,5 +262,3 @@ void WebSocket::Close(int code) { state_ = CLOSED; } - - diff --git a/chrome/test/chromedriver/session_commands.cc b/chrome/test/chromedriver/session_commands.cc index 85809f6e04..8e0ef6b9ad 100644 --- a/chrome/test/chromedriver/session_commands.cc +++ b/chrome/test/chromedriver/session_commands.cc @@ -592,8 +592,9 @@ Status ExecuteUploadFile( return Status(kUnknownError, "unable to create temp dir"); } base::FilePath upload_dir; - if (!file_util::CreateTemporaryDirInDir( - session->temp_dir.path(), FILE_PATH_LITERAL("upload"), &upload_dir)) { + if (!base::CreateTemporaryDirInDir(session->temp_dir.path(), + FILE_PATH_LITERAL("upload"), + &upload_dir)) { return Status(kUnknownError, "unable to create temp dir"); } std::string error_msg; diff --git a/chrome/test/chromedriver/test/run_java_tests.py b/chrome/test/chromedriver/test/run_java_tests.py index 6161e90ccf..6c13766a5a 100755 --- a/chrome/test/chromedriver/test/run_java_tests.py +++ b/chrome/test/chromedriver/test/run_java_tests.py @@ -274,7 +274,8 @@ def main(): parser.error('Invalid --android-package') if options.chrome_version != 'HEAD': parser.error('Android does not support the --chrome-version argument.') - environment = test_environment.AndroidTestEnvironment() + environment = test_environment.AndroidTestEnvironment( + options.android_package) else: environment = test_environment.DesktopTestEnvironment( options.chrome_version) diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 433ea64767..660ac7ee1d 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py @@ -466,7 +466,7 @@ class ChromeDriverTest(ChromeDriverBaseTest): self.assertEquals('0123456789+-*/ Hi, there!', value) def testGetCurrentUrl(self): - self.assertTrue('data:,' in self._driver.GetCurrentUrl()) + self.assertEquals('data:,', self._driver.GetCurrentUrl()) def testGoBackAndGoForward(self): self._driver.Load(self.GetHttpUrlForFile('/chromedriver/empty.html')) diff --git a/chrome/test/chromedriver/test/test_environment.py b/chrome/test/chromedriver/test/test_environment.py index de8753ba51..166c86f0e1 100644 --- a/chrome/test/chromedriver/test/test_environment.py +++ b/chrome/test/chromedriver/test/test_environment.py @@ -84,8 +84,9 @@ class DesktopTestEnvironment(BaseTestEnvironment): class AndroidTestEnvironment(DesktopTestEnvironment): """Manages the environment java tests require to run on Android.""" - def __init__(self, chrome_version='HEAD'): + def __init__(self, package, chrome_version='HEAD'): super(AndroidTestEnvironment, self).__init__(chrome_version) + self._package = package self._adb = None self._forwarder = None @@ -105,4 +106,4 @@ class AndroidTestEnvironment(DesktopTestEnvironment): # override def GetOS(self): - return 'android' + return 'android:%s' % self._package diff --git a/chrome/test/chromedriver/test/test_expectations b/chrome/test/chromedriver/test/test_expectations index faa7b0543b..9cd51c5a47 100644 --- a/chrome/test/chromedriver/test/test_expectations +++ b/chrome/test/chromedriver/test/test_expectations @@ -117,7 +117,7 @@ _OS_NEGATIVE_FILTER['mac'] = [ # Flaky: https://code.google.com/p/chromedriver/issues/detail?id=375 'PageLoadingTest.testShouldBeAbleToNavigateBackInTheBrowserHistoryInPresenceOfIframes', ] -_OS_NEGATIVE_FILTER['android'] = [ +_OS_NEGATIVE_FILTER['android:chrome'] = [ 'ChromeOptionsFunctionalTest.canStartChromeWithCustomOptions', 'ClickScrollingTest.testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrame', 'ClickScrollingTest.testShouldBeAbleToClickElementThatIsOutOfViewInANestedFrameThatIsOutOfView', @@ -185,6 +185,25 @@ _OS_NEGATIVE_FILTER['android'] = [ # https://code.google.com/p/chromedriver/issues/detail?id=604 'I18nTest.*', ] +_OS_NEGATIVE_FILTER['android:chrome_stable'] = ( + _OS_NEGATIVE_FILTER['android:chrome']) +_OS_NEGATIVE_FILTER['android:chrome_beta'] = ( + _OS_NEGATIVE_FILTER['android:chrome']) +_OS_NEGATIVE_FILTER['android:chromium_test_shell'] = ( + _OS_NEGATIVE_FILTER['android:chrome']) +_OS_NEGATIVE_FILTER['android:chromedriver_webview_shell'] = ( + _OS_NEGATIVE_FILTER['android:chrome'] + [ + # https://code.google.com/p/chromedriver/issues/detail?id=645 + 'ClickScrollingTest.testShouldBeAbleToClickElementInAFrameThatIsOutOfView', + 'ClickScrollingTest.testShouldBeAbleToClickElementThatIsOutOfViewInAFrameThatIsOutOfView', + 'FormHandlingTest.handleFormWithJavascriptAction', + 'TypingTest.testShouldReportKeyCodeOfArrowKeysUpDownEvents', + 'TypingTest.testShouldReportKeyCodeOfArrowKeys', + 'CombinedInputActionsTest.testCanClickOnLinks', + 'CombinedInputActionsTest.testCanClickOnLinksWithAnOffset', + 'CombinedInputActionsTest.testMouseMovementWorksWhenNavigatingToAnotherPage', + ] +) def _GetRevisionNegativeFilter(chrome_version): diff --git a/chrome/test/chromedriver/util.cc b/chrome/test/chromedriver/util.cc index 454949e79e..911de01bae 100644 --- a/chrome/test/chromedriver/util.cc +++ b/chrome/test/chromedriver/util.cc @@ -76,7 +76,7 @@ bool Base64Decode(const std::string& base64, // Some WebDriver client base64 encoders follow RFC 1521, which require that // 'encoded lines be no more than 76 characters long'. Just remove any // newlines. - RemoveChars(copy, "\n", ©); + base::RemoveChars(copy, "\n", ©); return base::Base64Decode(copy, bytes); } diff --git a/chrome/test/functional/OWNERS b/chrome/test/functional/OWNERS index fb45b77e52..43e031bd07 100644 --- a/chrome/test/functional/OWNERS +++ b/chrome/test/functional/OWNERS @@ -1,5 +1,4 @@ craigdh@chromium.org -kkania@chromium.org # for media stuff dalecurtis@chromium.org diff --git a/chrome/test/functional/ispy/common/image_tools.py b/chrome/test/functional/ispy/common/image_tools.py index 25d05882ee..aaa0748c70 100644 --- a/chrome/test/functional/ispy/common/image_tools.py +++ b/chrome/test/functional/ispy/common/image_tools.py @@ -87,7 +87,7 @@ def CreateMask(images): everywhere else. Args: - images: the images to compute the mask from. + images: list of images to compute the mask from. Returns: an image of only black and white pixels where white pixels represent @@ -95,10 +95,10 @@ def CreateMask(images): Raises: Exception: if the images passed in are not of the same size. - Exception: if fewer than two images are passed in. + Exception: if fewer than one image is passed in. """ - if len(images) < 2: - raise Exception('mask must be created from two or more images.') + if not images: + raise Exception('mask must be created from one or more images.') mask = Image.new('RGBA', images[0].size, (0, 0, 0, 255)) image = images[0] for other_image in images[1:]: diff --git a/chrome/test/functional/ispy/common/ispy_utils.py b/chrome/test/functional/ispy/common/ispy_utils.py index 6fa7d08fe3..a5d140af58 100644 --- a/chrome/test/functional/ispy/common/ispy_utils.py +++ b/chrome/test/functional/ispy/common/ispy_utils.py @@ -13,6 +13,13 @@ import sys import image_tools +_INVALID_EXPECTATION_CHARS = ['/', '\\', ' ', '"', '\''] + + +def IsValidExpectationName(expectation_name): + return not any(c in _INVALID_EXPECTATION_CHARS for c in expectation_name) + + def GetExpectationPath(expectation, file_name=''): """Get the path to a test file in the given test run and expectation. @@ -96,7 +103,14 @@ class ISpyUtils(object): expectation: name for this expectation, any existing expectation with the name will be replaced. images: a list of RGB encoded PIL.Images + + Raises: + ValueError: if the expectation name is invalid. """ + if not IsValidExpectationName(expectation): + raise ValueError("Expectation name contains an illegal character: %s." % + str(_INVALID_EXPECTATION_CHARS)) + mask = image_tools.InflateMask(image_tools.CreateMask(images), 7) self.UploadImage( GetExpectationPath(expectation, 'expected.png'), images[0]) @@ -112,7 +126,12 @@ class ISpyUtils(object): Raises: cloud_bucket.NotFoundError: if the given expectation is not found. + ValueError: if the expectation name is invalid. """ + if not IsValidExpectationName(expectation): + raise ValueError("Expectation name contains an illegal character: %s." % + str(_INVALID_EXPECTATION_CHARS)) + expectation_tuple = self.GetExpectation(expectation) if not image_tools.SameImage( actual, expectation_tuple.expected, mask=expectation_tuple.mask): @@ -198,7 +217,14 @@ class ISpyUtils(object): images: a json encoded list of base64 encoded png images. pink_out: an image. RGB: a json list representing the RGB values of a color to mask out. + + Raises: + ValueError: if expectation name is invalid. """ + if not IsValidExpectationName(expectation): + raise ValueError("Expectation name contains an illegal character: %s." % + str(_INVALID_EXPECTATION_CHARS)) + # convert the pink_out into a mask black = (0, 0, 0, 255) white = (255, 255, 255, 255) diff --git a/chrome/test/functional/ispy/common/ispy_utils_unittest.py b/chrome/test/functional/ispy/common/ispy_utils_unittest.py index 96dcb1feeb..2b55c2c012 100644 --- a/chrome/test/functional/ispy/common/ispy_utils_unittest.py +++ b/chrome/test/functional/ispy/common/ispy_utils_unittest.py @@ -79,6 +79,7 @@ class ISpyUtilsUnitTest(unittest.TestCase): # Upload some tests to the datastore. self.ispy_utils.GenerateExpectation('test', [self.white, self.black]) self.ispy_utils.GenerateExpectation('test1', [self.black, self.black]) + self.ispy_utils.GenerateExpectation('test2', [self.black]) # Confirm that the tests were successfully uploaded. self.assertEquals(self.bucket.datastore[ ispy_utils.GetExpectationPath('test', 'expected.png')], @@ -92,6 +93,12 @@ class ISpyUtilsUnitTest(unittest.TestCase): self.assertEquals(self.bucket.datastore[ ispy_utils.GetExpectationPath('test1', 'mask.png')], image_tools.EncodePNG(self.black)) + self.assertEquals(self.bucket.datastore[ + ispy_utils.GetExpectationPath('test2', 'expected.png')], + image_tools.EncodePNG(self.black)) + self.assertEquals(self.bucket.datastore[ + ispy_utils.GetExpectationPath('test2', 'mask.png')], + image_tools.EncodePNG(self.black)) def testPerformComparison(self): self.bucket.Reset() diff --git a/chrome/test/gpu/gpu_feature_browsertest.cc b/chrome/test/gpu/gpu_feature_browsertest.cc index ac0b590eee..d20357eea1 100644 --- a/chrome/test/gpu/gpu_feature_browsertest.cc +++ b/chrome/test/gpu/gpu_feature_browsertest.cc @@ -169,11 +169,13 @@ class GpuFeatureTest : public InProcessBrowserTest { std::string trace_events_json_; }; -#if defined(OS_WIN) || defined(ADDRESS_SANITIZER) || defined(USE_AURA) +#if defined(OS_WIN) || defined(ADDRESS_SANITIZER) || defined(USE_AURA) || \ + defined(OS_MACOSX) // This test is flaky on Windows. http://crbug.com/177113 // Also fails under AddressSanitizer. http://crbug.com/185178 // It fundamentally doesn't test the right thing on Aura. // http://crbug.com/280675 +// This does not work with software compositing on Mac. http://crbug.com/286038 #define MAYBE_AcceleratedCompositingAllowed DISABLED_AcceleratedCompositingAllowed #else #define MAYBE_AcceleratedCompositingAllowed AcceleratedCompositingAllowed @@ -298,8 +300,13 @@ IN_PROC_BROWSER_TEST_F(WebGLTest, WebGLDisabled) { #define MultisamplingAllowed DISABLED_MultisamplingAllowed #endif IN_PROC_BROWSER_TEST_F(GpuFeatureTest, MultisamplingAllowed) { - EXPECT_FALSE(GpuDataManager::GetInstance()->IsFeatureBlacklisted( - gpu::GPU_FEATURE_TYPE_MULTISAMPLING)); + bool expect_blacklisted = false; + if (gpu::GPUTestBotConfig::GpuBlacklistedOnBot()) + expect_blacklisted = true; + + EXPECT_EQ(expect_blacklisted, + GpuDataManager::GetInstance()->IsFeatureBlacklisted( + gpu::GPU_FEATURE_TYPE_MULTISAMPLING)); // Multisampling is not supported if running on top of osmesa. if (gfx::GetGLImplementation() != gfx::kGLImplementationOSMesaGL) @@ -380,6 +387,9 @@ IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) { expected_state = BLACKLISTED; #endif + if (gpu::GPUTestBotConfig::GpuBlacklistedOnBot()) + expected_state = BLACKLISTED; + #if defined(USE_AURA) // Canvas 2D is always disabled in software compositing mode, make sure it is // marked as such if it wasn't blacklisted already. @@ -434,6 +444,9 @@ IN_PROC_BROWSER_TEST_F(Canvas2DDisabledTest, Canvas2DDisabled) { IN_PROC_BROWSER_TEST_F(GpuFeatureTest, CanOpenPopupAndRenderWithWebGLCanvas) { + if (gpu::GPUTestBotConfig::GpuBlacklistedOnBot()) + return; + const base::FilePath url(FILE_PATH_LITERAL("webgl_popup.html")); RunTest(url, "\"SUCCESS\"", false); } @@ -508,6 +521,9 @@ IN_PROC_BROWSER_TEST_F(GpuFeatureTest, IOSurfaceReuse) { if (!IOSurfaceSupport::Initialize()) return; + if (gpu::GPUTestBotConfig::GpuBlacklistedOnBot()) + return; + const base::FilePath url( FILE_PATH_LITERAL("feature_compositing_static.html")); base::FilePath test_path = gpu_test_dir_.Append(url); diff --git a/chrome/test/gpu/webgl_infobar_browsertest.cc b/chrome/test/gpu/webgl_infobar_browsertest.cc index 5fc907627b..bbe9f45230 100644 --- a/chrome/test/gpu/webgl_infobar_browsertest.cc +++ b/chrome/test/gpu/webgl_infobar_browsertest.cc @@ -7,6 +7,7 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/infobars/confirm_infobar_delegate.h" +#include "chrome/browser/infobars/infobar.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -59,7 +60,9 @@ class WebGLInfoBarTest : public InProcessBrowserTest { base::FilePath gpu_test_dir_; }; -IN_PROC_BROWSER_TEST_F(WebGLInfoBarTest, ContextLossRaisesInfoBar) { +// This test is flaky. http://crbug.com/324555 +IN_PROC_BROWSER_TEST_F(WebGLInfoBarTest, DISABLED_ContextLossRaisesInfoBar) { +#undef MAYBE_ContextLossRaisesInfoBard #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) @@ -90,7 +93,8 @@ IN_PROC_BROWSER_TEST_F(WebGLInfoBarTest, ContextLossRaisesInfoBar) { infobar_count()); } -IN_PROC_BROWSER_TEST_F(WebGLInfoBarTest, ContextLossInfoBarReload) { +// This test is flaky. http://crbug.com/324555 +IN_PROC_BROWSER_TEST_F(WebGLInfoBarTest, DISABLED_ContextLossInfoBarReload) { #if defined(OS_WIN) && defined(USE_ASH) // Disable this test in Metro+Ash for now (http://crbug.com/262796). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) @@ -127,7 +131,7 @@ IN_PROC_BROWSER_TEST_F(WebGLInfoBarTest, ContextLossInfoBarReload) { InfoBarService* infobar_service = InfoBarService::FromWebContents( browser()->tab_strip_model()->GetActiveWebContents()); ASSERT_EQ(1u, infobar_service->infobar_count()); - InfoBarDelegate* delegate = infobar_service->infobar_at(0); + InfoBarDelegate* delegate = infobar_service->infobar_at(0)->delegate(); ASSERT_TRUE(delegate->AsThreeDAPIInfoBarDelegate()); delegate->AsConfirmInfoBarDelegate()->Cancel(); diff --git a/chrome/test/install_test/OWNERS b/chrome/test/install_test/OWNERS deleted file mode 100644 index abd7b0c184..0000000000 --- a/chrome/test/install_test/OWNERS +++ /dev/null @@ -1 +0,0 @@ -kkania@chromium.org diff --git a/chrome/test/install_test/chrome.py b/chrome/test/install_test/chrome.py deleted file mode 100644 index 414442911b..0000000000 --- a/chrome/test/install_test/chrome.py +++ /dev/null @@ -1,97 +0,0 @@ -# Copyright (c) 2012 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. - -"""Extended WebDriver interface that uses helper extension. - -This file is makeshift and should eventually be switched over to -using the new ChromeDriver python interface. However, as that is -not quite ready, this class simply installs a helper extension -and executes scripts in the background page to access extension -APIs. - -This may end up being merged with chrome/test/ext_auto, if they -accomplish similar enough purposes. For now, integration with that -is a bit premature. -""" - -import os - -from selenium import webdriver - - -_CHROME_GET_VIEW_HANDLES = 'chrome.getViewHandles' -_EXTENSION = os.path.join( - os.path.dirname(os.path.abspath(__file__)), 'ext_auto') - - -class Chrome(webdriver.Remote): - """Extended WebDriver interface that uses helper extension.""" - - def __init__(self, url, desired_capabilities, options=None): - """Initializes Chrome object. - - If both desired_capabilities and options have the same settings, the - settings from options will be used. - - Args: - url: The URL of the ChromeDriver Service. - desired_capabilities: Chrome capabilities dictionary. - options: chrome_options.ChromeOptions object. Settings in options will - overwrite settings in desired_capabilities. - - Raises: - RuntimeError: Unable to find helper extension. - """ - if options is not None: - desired_capabilities.update(options.GetCapabilities()) - switches = desired_capabilities.get('chrome.switches', []) - switches += ['--load-extension=' + _EXTENSION] - desired_capabilities['chrome.switches'] = switches - super(Chrome, self).__init__(url, desired_capabilities) - - custom_commands = { - _CHROME_GET_VIEW_HANDLES: - ('GET', '/session/$sessionId/chrome/views'), - } - self.command_executor._commands.update(custom_commands) - views = self.execute(_CHROME_GET_VIEW_HANDLES)['value'] - self.set_script_timeout(30) # TODO(kkania): Make this configurable. - for view in views: - if view.get('extension_id') == 'aapnijgdinlhnhlmodcfapnahmbfebeb': - self._extension = view['handle'] - break - else: - raise RuntimeError('Unable to find helper extension') - - def _execute_extension_command(self, name, params={}): - """Executes an extension command. - - When Chrome is started, a helper extension is loaded which provides - a simple synchronous API for manipulating Chrome via the extension - APIs. Communication with the extension is accomplished by executing - a script in the background page of the extension which calls the - 'executeCommand' function with the name of the command, a parameter - dictionary, and a callback function that can be used to signal - when the command is finished and potentially send a return value. - """ - old_window = self.current_window_handle - self.switch_to_window(self._extension) - self.execute_async_script( - 'executeCommand.apply(null, arguments)', name, params) - self.switch_to_window(old_window) - - def create_tab(self, url=None): - """Creates a new tab with the given URL and switches to it. - - If no URL is provided, the homepage will be used. - """ - params = {} - if url is not None: - params['url'] = url - self._execute_extension_command('createTab', params) - self.switch_to_window(self.window_handles[-1]) - - def create_blank_tab(self): - """Creates a new blank tab and switches to it.""" - self.create_tab('about:blank') diff --git a/chrome/test/install_test/chrome_installer_win.py b/chrome/test/install_test/chrome_installer_win.py deleted file mode 100644 index ac5e34a009..0000000000 --- a/chrome/test/install_test/chrome_installer_win.py +++ /dev/null @@ -1,296 +0,0 @@ -# Copyright (c) 2012 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. - -"""Provides an interface for installing Chrome. - -At present the only platform it supports is Windows. -""" - -import _winreg -import ctypes -from ctypes import wintypes, windll -import httplib -import logging -import os -import shutil -import socket -import subprocess -import tempfile -import urllib - - -class InstallationType(object): - """Defines the Chrome installation types.""" - SYSTEM = 1 - USER = 2 - - -def IsVersionNewer(cur_version, new_version): - """Determines if new Chrome version is higher than the installed one. - - Args: - cur_version: Current version of Chrome. - new_version: New version that will be installed. - - Returns: - True, if new version is higher, otherwise False. - """ - if cur_version == new_version: - return False - cur = cur_version.split('.') - new = new_version.split('.') - if len(cur) != 4 or len(new) != 4: - raise RuntimeError('One or both of the versions are invalid.') - for x in range(len(cur)): - if int(cur[x]) > int(new[x]): - return False - return True - - -def Install(installer_path, install_type, build, options): - """Installs the specified Chrome version. - - Args: - installer_path: Path to the Chrome installer. - install_type: Type of installation (i.e., system or user). - build: Chrome build number. - options: Additional installation options. - - Returns: - An instance of ChromeInstallation. - """ - current = ChromeInstallation.GetCurrent() - if current: - # Make sure new build can be installed over existing Chrome build. - if (current.GetType() == InstallationType.SYSTEM and - install_type == InstallationType.USER): - raise RuntimeError('System level Chrome exists, aborting user level ' - 'installation.') - # Confirm the new Chrome build is higher than the installed build. - if not IsVersionNewer(current.GetVersion(), build): - raise RuntimeError('Installation failed because a newer version is ' - 'already installed.') - options.append('--install') - options.append('--do-not-launch-chrome') - logging.info('Installing Chrome build %s...' % build) - args = [installer_path] - args.extend(options) - if subprocess.Popen(args).wait() != 0: - raise RuntimeError('Chrome installation for build %s failed.' % build) - logging.info('Installation complete.') - return ChromeInstallation.GetCurrent() - - -class ChromeRegistryValues(object): - """Defines the Chrome registry key values.""" - PRODUCT_VERSION = 'pv' - UNINSTALL_STRING = 'UninstallString' - UNINSTALL_ARGUMENTS = 'UninstallArguments' - - -class ChromeRegistryKeys(object): - """An interface for accessing and manipulating Chrome registry keys.""" - - _HKEY_LOCAL = r'SOFTWARE\Wow6432Node\Google\Update' - _HKEY_USER = _HKEY_LOCAL.replace(r'\Wow6432Node', '') - _chrome_version = r'Clients\{8A69D345-D564-463C-AFF1-A69D9E530F96}' - _chrome_args = r'ClientState\{8A69D345-D564-463C-AFF1-A69D9E530F96}' - - def _GetKeyName(self, install_type, value): - """Gets the registry key name for the specified value. - - Args: - install_type: Type of installation, must be InstallationType type. - value: ChromeRegistryValues type for which the key name is required. - - Returns: - A string representing the full key name of the specified key value. - """ - key_name = None - if install_type == InstallationType.USER: - key_name = self._HKEY_USER - elif install_type == InstallationType.SYSTEM: - key_name = self._HKEY_LOCAL - if value == ChromeRegistryValues.PRODUCT_VERSION: - return r'%s\%s' % (key_name, self._chrome_version) - elif value == ChromeRegistryValues.UNINSTALL_ARGUMENTS: - return r'%s\%s' % (key_name, self._chrome_args) - elif value == ChromeRegistryValues.UNINSTALL_STRING: - return r'%s\%s' % (key_name, self._chrome_args) - raise RuntimeError('Invalid registry value.') - - def _GetRegistryType(self, install_type): - """Determines the registry key to use based on installation type. - - Args: - install_type: Type of installation, must be InstallationType type. - - Returns: - A long representing HKLM or HKCU, depending on installation type. - """ - if install_type == InstallationType.SYSTEM: - return _winreg.HKEY_LOCAL_MACHINE - elif install_type == InstallationType.USER: - return _winreg.HKEY_CURRENT_USER - raise RuntimeError('Invalid installation type.') - - def DoesKeyExist(self, install_type, subkey): - """Determines if a particular key exists in the registry. - - Args: - install_type: Type of installation, must be InstallationType type. - subkey: Subkey to look up. It must be a ChromeRegistryValues type. - - Returns: - True if the key exists, otherwise False. - """ - key = self._GetRegistryType(install_type) - key_name = self._GetKeyName(install_type, subkey) - try: - hkey = _winreg.OpenKey(key, key_name) - except _winreg.error: - return False - if not hkey.handle: - return False - hkey.Close() - return True - - def GetKeyValue(self, install_type, subkey): - """Gets value of the specified subkey from the registry. - - Args: - install_type: Type of installation, must be InstallationType type. - subkey: ChromeRegistryValue type representing the value to be returned. - - Returns: - A string representing the subkey value. - """ - key = self._GetRegistryType(install_type) - key_name = self._GetKeyName(install_type, subkey) - hkey = _winreg.OpenKey(key, key_name) - reg_value = str(_winreg.QueryValueEx(hkey, subkey)[0]) - hkey.Close() - return reg_value - - def DeleteRegistryEntries(self, install_type): - """Deletes chrome registry settings. - - Args: - install_type: Type of installation, must be InstallationType type. - """ - reg_type = self._GetRegistryType(install_type) - key_name = self._GetKeyName(install_type, - ChromeRegistryValues.UNINSTALL_ARGUMENTS) - root = key_name[:key_name.rfind('\\')] - child = key_name[key_name.rfind('\\') + 1:] - key = _winreg.OpenKey(reg_type, root, 0, _winreg.KEY_ALL_ACCESS) - _winreg.DeleteKey(key, child) - key.Close() - - -class ChromeInstallation(object): - """Provides pertinent information about the installed Chrome version. - - The type of Chrome version must be passed as an argument to the constructor, - (i.e. - user or system level). - """ - - _CSIDL_COMMON_APPDATA = 0x1C - _CSIDL_PROGRAM_FILESX86 = 0x2A - - def __init__(self, install_type): - assert(install_type == InstallationType.SYSTEM or - install_type == InstallationType.USER) - self._type = install_type - self._regedit = ChromeRegistryKeys() - - def GetType(self): - """Returns the current installation type.""" - return self._type - - def GetVersion(self): - """Returns the installed version of Chrome.""" - return self._regedit.GetKeyValue(self._type, - ChromeRegistryValues.PRODUCT_VERSION) - - def _GetWinLocalFolder(self, ftype=_CSIDL_COMMON_APPDATA): - """Returns full path of the 'Local' folder on Windows. - - Args: - ftype: Location to look up, which could vary based on installation type. - - Returns: - A String representing the folder path if successful, otherwise an empty - string. - """ - SHGetFolderPathW = windll.shell32.SHGetFolderPathW - SHGetFolderPathW.argtypes = [wintypes.HWND, - ctypes.c_int, - wintypes.HANDLE, - wintypes.DWORD, - wintypes.LPCWSTR] - path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH) - result = SHGetFolderPathW(0, ftype, 0, 0, path_buf) - return str(path_buf.value) - - def _GetUninstallString(self): - """Returns the Chrome uninstall string from the registry.""" - return self._regedit.GetKeyValue(self._type, - ChromeRegistryValues.UNINSTALL_STRING) - - def _GetUninstallArguments(self): - """Returns the Chrome uninstall arguments from the registry.""" - return self._regedit.GetKeyValue(self._type, - ChromeRegistryValues.UNINSTALL_ARGUMENTS) - - def GetExePath(self): - """Returns Chrome binary location based on installation type. - - Currently this method only returns the location of the Chrome binary. - It does not support Chromium. - """ - if self._type == InstallationType.USER: - folder_id = self._CSIDL_COMMON_APPDATA - elif self._type == InstallationType.SYSTEM: - folder_id = self._CSIDL_PROGRAM_FILESX86 - chrome_path = os.path.join(self._GetWinLocalFolder(folder_id), 'Google', - 'Chrome', 'Application', 'chrome.exe') - return (chrome_path if os.path.exists(chrome_path) else '') - - @staticmethod - def GetCurrent(): - """Determines Chrome installation type. - - Returns: - ChromeInstallation object if Chrome is present, otherwise None. - """ - registry = ChromeRegistryKeys() - if registry.DoesKeyExist(InstallationType.SYSTEM, - ChromeRegistryValues.PRODUCT_VERSION): - return ChromeInstallation(InstallationType.SYSTEM) - elif registry.DoesKeyExist(InstallationType.USER, - ChromeRegistryValues.PRODUCT_VERSION): - return ChromeInstallation(InstallationType.USER) - return None - - def Uninstall(self): - """Uninstalls Chrome.""" - chrome_path = self.GetExePath() - reg_opts = self._GetUninstallArguments() - uninstall_str = self._GetUninstallString() - options = '%s --force-uninstall' % (reg_opts) - if self._type == InstallationType.SYSTEM: - options += ' --system-level' - if not os.path.exists(chrome_path): - raise RuntimeError('Could not find chrome, aborting uninstall.') - logging.info('Launching Chrome installer...') - cmd = '"%s" %s' % (uninstall_str, options) - subprocess.call(cmd) - if not os.path.exists(chrome_path): - logging.info('Chrome was uninstalled successfully...') - logging.info('Deleting registry entries...') - self._regedit.DeleteRegistryEntries(self._type) - logging.info('Uninstall complete.') - else: - raise RuntimeError('Uninstall failed.') diff --git a/chrome/test/install_test/chrome_options.py b/chrome/test/install_test/chrome_options.py deleted file mode 100644 index 48b67687e1..0000000000 --- a/chrome/test/install_test/chrome_options.py +++ /dev/null @@ -1,45 +0,0 @@ -# Copyright (c) 2012 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. - -"""Chrome-specific options for configuring a ChromeDriver instance.""" - -import base64 - - -class ChromeOptions(object): - """Chrome-specific options for configuring a ChromeDriver instance.""" - - def __init__(self): - """Initialize ChromeOptions object.""" - self._capabilities = {'chrome.switches': [], 'chrome.extensions': []} - - def AddSwitch(self, switch): - """Add a switch to be passed to Chrome. - - Args: - switch: String switch to be passed to Chrome. - """ - self._capabilities['chrome.switches'].append(switch) - - def AddExtension(self, extension): - """Add an extension to be loaded onto Chrome. - - Args: - extension: String path to the extension to be loaded onto Chrome. - """ - with open(extension, 'rb') as ext_file: - self._capabilities['chrome.extensions'].append( - base64.b64encode(ext_file.read())) - - def SetUserDataDir(self, user_data_dir): - """Set the Chrome user data dir. - - Args: - user_data_dir: String path to the profile directory. - """ - self.AddSwitch('user-data-dir=%s' % user_data_dir) - - def GetCapabilities(self): - """Returns a capabilities object suitable for using with ChromeDriver.""" - return self._capabilities diff --git a/chrome/test/install_test/chrome_proxy_server.py b/chrome/test/install_test/chrome_proxy_server.py deleted file mode 100644 index b9d7ec9a55..0000000000 --- a/chrome/test/install_test/chrome_proxy_server.py +++ /dev/null @@ -1,188 +0,0 @@ -# Copyright (c) 2013 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. - -"""A simple HTTP proxy server.""" - -import BaseHTTPServer -import copy -import os -import socket -import SocketServer -import threading -import urllib -import urllib2 -from urlparse import urlparse - -_HOST = '127.0.0.1' - - -class _ProxyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): - """Request handler for the proxy server.""" - - # Disables buffering, which causes problems with certain sites. - rbufsize = 0 - - def __init__(self, request, client_addr, server): - BaseHTTPServer.BaseHTTPRequestHandler.__init__( - self, request, client_addr, server) - - def _GetHandler(self): - """GET handler for requests that will be processed by the server.""" - try: - url = urllib.urlopen(self.path, proxies={'http:' : '127.0.0.1'}) - except IOError, err: - self.wfile.write(err) - return - data = url.read() - self.wfile.write(data) - url.close() - - def do_GET(self): - """Handles GET requests.""" - if self._ShouldHandleRequest(): - self._LogRequest() - self._GetHandler() - else: - self._GenericResponseHandler() - - def do_CONNECT(self): - """Handles CONNECT requests.""" - self._GenericResponseHandler() - - def do_HEAD(self): - """Handles HEAD requests.""" - self.do_GET() - - def do_POST(self): - """Handles POST requests.""" - self.do_GET() - - def do_PUT(self): - """Handles PUT requests.""" - self.do_GET() - - def _GenericResponseHandler(self): - """Sends a dummy reponse for HTTP requests not handled by the server.""" - # Handle dropped connections. - try: - self.send_response(200) - except (socket.error, socket.gaierror): - return - contents = 'Default response given for path: %s' % self.path - self.send_header('Content-Type', 'text/html') - self.send_header('Content-Length', len(contents)) - self.end_headers() - if (self.command != 'HEAD'): - self.wfile.write(contents) - - def _ShouldHandleRequest(self): - """Determines if a request should be processed by the server.""" - if self.server.ShouldHandleAllRequests(): - return True - (scheme, netloc, path, params, query, flag) = urlparse(self.path, 'http') - paths = self.server.GetPaths() - if(any([netloc.find(url) >= 0 for url in paths]) or - any([self.path.find(url) >= 0 for url in paths])): - return True - return False - - def _LogRequest(self): - """Logs requests handled by the server to a buffer.""" - self.server.AddHandledRequest(self.requestline) - - def log_request(self, *args, **kwargs): - """Overridden base class method that disables request logging.""" - pass - - -class ProxyServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): - """Creates a threaded proxy server.""" - - def __init__(self, port=0, paths=[], handle_all=True): - """Initializes proxy server settings. - - Args: - port: Server port number. If zero, the server will select a free port. - paths: A list containing urls the server will process. If |handle_all| is - False, the server will only process urls in this list. URLs should be - passed as follows: ['http://www.google.com', '...',]. - handle_all: Flag that determines if the server will process all requests. - """ - BaseHTTPServer.HTTPServer.__init__( - self, (_HOST, port), _ProxyRequestHandler, True) - self._stopped = False - self._serving = False - self._lock = threading.RLock() - self._paths = list(paths) - self._handle_all = handle_all - self._handled_requests = [] - self.StartServer() - - def GetPort(self): - """Returns the port number the server is serving on.""" - return self.server_port - - def StartServer(self): - """Starts the proxy server in a new thread.""" - if self._stopped: - raise RuntimeError('Cannot restart server.') - if not self._serving: - self._serving = True - thread = WorkerThread(self) - thread.start() - - def Shutdown(self): - """Shuts down the server.""" - if not self._serving: - raise RuntimeError('Server is currently inactive.') - self._serving = False - self._stopped = True - try: - urllib2.urlopen('http://%s:%s' % (self.server_name, self.server_port)) - except urllib2.URLError: - pass - self.server_close() - - def handle_request(self): - """Handles requests while the |_serving| flag is True.""" - while self._serving: - BaseHTTPServer.HTTPServer.handle_request(self) - - def ShouldHandleAllRequests(self): - """Determines if server should handle all requests.""" - return self._handle_all - - def AddHandledRequest(self, request): - """Appends requests handled by the server to |_handled_requests|.""" - try: - self._lock.acquire() - self._handled_requests.append(request) - finally: - self._lock.release() - - def GetHandledRequests(self): - """Returns requests handled by the server.""" - try: - self._lock.acquire() - return copy.deepcopy(self._handled_requests) - finally: - self._lock.release() - - def GetPaths(self): - """Returns list of urls that will be handled by the server.""" - return self._paths - - -class WorkerThread(threading.Thread): - """Creates a worker thread.""" - - def __init__(self, server): - threading.Thread.__init__(self) - self._server = server - - def run(self): - """Overridden base class method.""" - print 'Serving on port: %s' % self._server.server_port - self._server.daemon_threads = True - self._server.handle_request() diff --git a/chrome/test/install_test/ext_auto/background.js b/chrome/test/install_test/ext_auto/background.js deleted file mode 100644 index f6b1a0c64f..0000000000 --- a/chrome/test/install_test/ext_auto/background.js +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2012 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. - -var g_commands = { - createTab: executeCreateTab -}; - -function executeCommand(name, params, callback) { - g_commands[name](params, callback); -} - -function executeCreateTab(params, callback) { - chrome.tabs.create(params, function() { - callback(params); - }); -} diff --git a/chrome/test/install_test/ext_auto/manifest.json b/chrome/test/install_test/ext_auto/manifest.json deleted file mode 100644 index 60c75dbf3e..0000000000 --- a/chrome/test/install_test/ext_auto/manifest.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDr+Q7QFcTr4Wmn9sSICKWbxnYLhIM0ERbcapZCDmpAkiBUhOPt+KkYnTdUFl4Kx2xv02MwIowh36Fho9Dhqh7cPWGIPsLHUaJosO6t6oaHxQsMQS/K4MlnP5pNJykExo82DcajSXGV+mIQH3RslxL+XhtmIh2BQLwbizVG0bA+mwIDAQAB", - "name": "Test Automation Provider Extension", - "version": "1", - "manifest_version": 2, - "description": "Test Automation Provider Extension", - "background": { - "scripts": ["background.js"] - }, - "permissions": [ - "background", - "tabs" - ] -} diff --git a/chrome/test/install_test/install_test.py b/chrome/test/install_test/install_test.py deleted file mode 100644 index bef878bb38..0000000000 --- a/chrome/test/install_test/install_test.py +++ /dev/null @@ -1,207 +0,0 @@ -# Copyright (c) 2012 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. - -"""Test fixture for tests involving installing/updating Chrome. - -Provides an interface to install or update chrome from within a testcase, and -allows users to run tests using installed version of Chrome. User and system -level installations are supported, and either one can be used for running the -tests. Currently the only platform it supports is Windows. -""" - -import os -import sys -import unittest -import urllib - -import chrome_installer_win - -_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) -sys.path.append(os.path.join(_DIRECTORY, os.path.pardir, os.path.pardir, - os.path.pardir, 'third_party', 'webdriver', - 'pylib')) -sys.path.append(os.path.join(_DIRECTORY, os.path.pardir, os.path.pardir, - os.path.pardir, 'build', 'util', 'lib')) - -# This import should go after sys.path is set appropriately. -from chrome import Chrome -from selenium import webdriver -import selenium.webdriver.chrome.service as service -from selenium.webdriver.chrome.service import WebDriverException - -from common import util - - -class InstallTest(unittest.TestCase): - """Base updater test class. - - All dependencies, like Chrome installers and ChromeDriver, are downloaded at - the beginning of the test. Dependencies are downloaded in the temp directory. - This download occurs only once, before the first test is executed. Each test - case starts an instance of ChromeDriver and terminates it upon completion. - All updater tests should derive from this class. - - Example: - - class SampleUpdater(InstallTest): - - def testCanOpenGoogle(self): - self.Install(self.GetUpdateBuilds()[0]) - self.StartChrome() - self._driver.get('http://www.google.com/') - self.Install(self.GetUpdateBuilds()[1]) - self.StartChrome() - self._driver.get('http://www.google.org/') - - Include the following in your updater test script to make it run standalone. - - from install_test import Main - - if __name__ == '__main__': - Main() - - To fire off an updater test, use the command below. - python test_script.py --url=<URL> --update-builds=24.0.1299.0,24.0.1300.0 - """ - - _installer_paths = {} - _chrome_driver = '' - _installer_options = [] - _install_type = chrome_installer_win.InstallationType.USER - - def __init__(self, methodName='runTest'): - unittest.TestCase.__init__(self, methodName) - self._driver = None - current_version = chrome_installer_win.ChromeInstallation.GetCurrent() - if current_version: - current_version.Uninstall() - - def setUp(self): - """Called before each unittest to prepare the test fixture.""" - self._StartService() - - def tearDown(self): - """Called at the end of each unittest to do any test related cleanup.""" - # Confirm ChromeDriver was instantiated, before attempting to quit. - if self._driver is not None: - try: - self._driver.quit() - except WebDriverException: - pass - self._service.stop() - self._installation.Uninstall() - - def _StartService(self): - """Starts ChromeDriver service.""" - self._service = service.Service(InstallTest._chrome_driver) - self._service.start() - - def StartChrome(self, caps={}, options=None): - """Creates a ChromeDriver instance. - - If both caps and options have the same settings, the settings from options - will be used. - - Args: - caps: Capabilities that will be passed to ChromeDriver. - options: ChromeOptions object that will be passed to ChromeDriver. - """ - self._driver = Chrome(self._service.service_url, caps, options) - - def Install(self, build, master_pref=None): - """Helper method that installs the specified Chrome build. - - Args: - build: Chrome version number that will be used for installation. - master_pref: Location of the master preferences file. - """ - if self._driver: - try: - self._driver.quit() - except WebDriverException: - pass - options = [] - options.extend(self._installer_options) - if self._install_type == chrome_installer_win.InstallationType.SYSTEM: - options.append('--system-level') - if master_pref: - options.append('--installerdata=%s' % master_pref) - self._installation = chrome_installer_win.Install( - self._installer_paths[build], - self._install_type, - build, - options) - - def GetInstallBuild(self): - """Returns Chorme build to be used for install test scenarios.""" - return self._install_build - - def GetUpdateBuilds(self): - """Returns Chrome builds to be used for update test scenarios.""" - return self._update_builds - - @staticmethod - def _Download(url, path): - """Downloads a file from the specified URL. - - Args: - url: URL where the file is located. - path: Location where file will be downloaded. - - Raises: - RuntimeError: URL or file name is invalid. - """ - if not util.DoesUrlExist(url): - raise RuntimeError('Either the URL or the file name is invalid.') - urllib.urlretrieve(url, path) - - @staticmethod - def SetInstallType(install_type): - """Sets Chrome installation type. - - Args: - install_type: Type of installation(i.e., user or system). - """ - InstallTest._install_type = install_type - - @staticmethod - def InitTestFixture(install_build, update_builds, base_url, options): - """Static method for passing command options to InstallTest. - - We do not instantiate InstallTest. Therefore, command arguments cannot be - passed to its constructor. Since InstallTest needs to use these options, - and using globals is not an option, this method can be used by the Main - class to pass the arguments it parses onto InstallTest. - - Args: - install_build: A string representing the Chrome build to be used for - install testing. Pass this argument only if testing - fresh install scenarios. - update_builds: A list that contains the Chrome builds to be used for - testing update scenarios. Pass this argument only if - testing upgrade scenarios. - base_url: Base url of the 'official chrome builds' page. - options: A list that contains options to be passed to Chrome installer. - """ - system = util.GetPlatformName() - InstallTest._install_build = install_build - InstallTest._update_builds = update_builds - InstallTest._installer_options = options - tempdir = util.MakeTempDir() - builds = [] - if InstallTest._install_build: - builds.append(InstallTest._install_build) - if InstallTest._update_builds: - builds.extend(InstallTest._update_builds) - # Remove any duplicate build numbers. - builds = list(frozenset(builds)) - for build in builds: - url = '%s%s/%s/mini_installer.exe' % (base_url, build, system) - installer_path = os.path.join(tempdir, 'mini_installer_%s.exe' % build) - InstallTest._installer_paths[build] = installer_path - InstallTest._Download(url, installer_path) - InstallTest._chrome_driver = os.path.join(tempdir, 'chromedriver.exe') - url = '%s%s/%s/%s/chromedriver.exe' % (base_url, build, system, - 'chrome-win32.test') - InstallTest._Download(url, InstallTest._chrome_driver) diff --git a/chrome/test/install_test/run_install_tests.py b/chrome/test/install_test/run_install_tests.py deleted file mode 100755 index 118acc822d..0000000000 --- a/chrome/test/install_test/run_install_tests.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 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. - -"""Runs install and update tests. - -Install tests are performed using a single Chrome build, whereas two or more -builds are needed for Update tests. There are separate command arguments for -the builds that will be used for each of the tests. If a test file contains -both types of tests(install and update), both arguments should be specified. -Otherwise, specify only the command argument that is required for the test. -To run a test with this script, append the module name to the _TEST_MODULES -list. Modules added to the list must be in the same directory or in a sub- -directory that's in the same location as this script. - -Example: - $ python run_install_tests.py --url=<chrome_builds_url> --filter=* \ - --install-build=24.0.1290.0 --update-builds=24.0.1289.0,24.0.1290.0 -""" - -import logging -import optparse -import os -import re -import sys -import unittest - -import chrome_installer_win -from install_test import InstallTest - -_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) -sys.path.append(os.path.join(_DIRECTORY, os.path.pardir, os.path.pardir, - os.path.pardir, 'build', 'util', 'lib')) - -from common import unittest_util -from common import util - -# To run tests from a module, append the module name to this list. -_TEST_MODULES = ['sample_updater', 'theme_updater'] - -for module in _TEST_MODULES: - __import__(module) - - -class Main(object): - """Main program for running 'Fresh Install' and 'Updater' tests.""" - - def __init__(self): - self._SetLoggingConfiguration() - self._ParseArgs() - self._Run() - - def _ParseArgs(self): - """Parses command line arguments.""" - parser = optparse.OptionParser() - parser.add_option( - '-u', '--url', type='string', default='', dest='url', - help='Specifies the build url, without the build number.') - parser.add_option( - '-o', '--options', type='string', default='', - help='Specifies any additional Chrome options (i.e. --system-level).') - parser.add_option( - '--install-build', type='string', default='', dest='install_build', - help='Specifies the build to be used for fresh install testing.') - parser.add_option( - '--update-builds', type='string', default='', dest='update_builds', - help='Specifies the builds to be used for updater testing.') - parser.add_option( - '--install-type', type='string', default='user', dest='install_type', - help='Type of installation (i.e., user, system, or both)') - parser.add_option( - '-f', '--filter', type='string', default='*', dest='filter', - help='Filter that specifies the test or testsuite to run.') - self._opts, self._args = parser.parse_args() - self._ValidateArgs() - if self._opts.install_type == 'system': - InstallTest.SetInstallType(chrome_installer_win.InstallationType.SYSTEM) - update_builds = (self._opts.update_builds.split(',') if - self._opts.update_builds else []) - options = self._opts.options.split(',') if self._opts.options else [] - InstallTest.InitTestFixture(self._opts.install_build, update_builds, - self._opts.url, options) - - def _ValidateArgs(self): - """Verifies the sanity of the command arguments. - - Confirms that all specified builds have a valid version number, and the - build urls are valid. - """ - builds = [] - if self._opts.install_build: - builds.append(self._opts.install_build) - if self._opts.update_builds: - builds.extend(self._opts.update_builds.split(',')) - builds = list(frozenset(builds)) - for build in builds: - if not re.match('\d+\.\d+\.\d+\.\d+', build): - raise RuntimeError('Invalid build number: %s' % build) - if not util.DoesUrlExist('%s/%s/' % (self._opts.url, build)): - raise RuntimeError('Could not locate build no. %s' % build) - - def _SetLoggingConfiguration(self): - """Sets the basic logging configuration.""" - log_format = '%(asctime)s %(levelname)-8s %(message)s' - logging.basicConfig(level=logging.INFO, format=log_format) - - def _Run(self): - """Runs the unit tests.""" - all_tests = unittest.defaultTestLoader.loadTestsFromNames(_TEST_MODULES) - tests = unittest_util.FilterTestSuite(all_tests, self._opts.filter) - result = unittest_util.TextTestRunner(verbosity=1).run(tests) - # Run tests again if installation type is 'both'(i.e., user and system). - if self._opts.install_type == 'both': - # Load the tests again so test parameters can be reinitialized. - all_tests = unittest.defaultTestLoader.loadTestsFromNames(_TEST_MODULES) - tests = unittest_util.FilterTestSuite(all_tests, self._opts.filter) - InstallTest.SetInstallType(chrome_installer_win.InstallationType.SYSTEM) - result = unittest_util.TextTestRunner(verbosity=1).run(tests) - del(tests) - if not result.wasSuccessful(): - print >>sys.stderr, ('Not all tests were successful.') - sys.exit(1) - sys.exit(0) - - -if __name__ == '__main__': - Main() diff --git a/chrome/test/install_test/sample_updater.py b/chrome/test/install_test/sample_updater.py deleted file mode 100644 index 01821fc364..0000000000 --- a/chrome/test/install_test/sample_updater.py +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright (c) 2012 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. - -"""Tests that demonstrate use of install test framework.""" - -import os -import sys -import unittest - -from install_test import InstallTest - - -class SampleUpdater(InstallTest): - """Sample update tests.""" - - def testCanOpenGoogle(self): - """Simple Navigation. - - This test case illustrates how to run an update test. Update tests require - two or more builds. - """ - self.Install(self.GetUpdateBuilds()[0]) - self.StartChrome() - self._driver.get('http://www.google.com/') - self.Install(self.GetUpdateBuilds()[1]) - self.StartChrome() - self._driver.get('http://www.google.org/') - - def testCanOpenGoogleOrg(self): - """Simple Navigation. - - This test case illustrates how to run a fresh install test. Simple install - tests, unlike update test, require only a single build. - """ - self.Install(self.GetInstallBuild()) - self.StartChrome() - self._driver.get('http://www.google.org/') - - def testCanOpenNewTab(self): - """Sample of using the extended webdriver interface.""" - self.Install(self.GetInstallBuild()) - self.StartChrome() - self._driver.create_blank_tab() diff --git a/chrome/test/install_test/theme_updater.py b/chrome/test/install_test/theme_updater.py deleted file mode 100644 index e52b0b681e..0000000000 --- a/chrome/test/install_test/theme_updater.py +++ /dev/null @@ -1,88 +0,0 @@ -# Copyright (c) 2012 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. - -"""Update tests for themes.""" -import os -import sys - -_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) -sys.path.append(os.path.join(_DIRECTORY, os.path.pardir, os.path.pardir, - os.path.pardir, 'build', 'util', 'lib')) - -from common import util - -import chrome_options -import install_test - - -class ThemeUpdater(install_test.InstallTest): - """Theme update tests.""" - _DIRECTORY = os.path.dirname(os.path.abspath(__file__)) - _EXTENSIONS_DIR = os.path.join(_DIRECTORY, os.path.pardir, 'data', - 'extensions') - camo_theme = os.path.join(_EXTENSIONS_DIR, 'theme.crx') - camo_img = ('chrome://theme/IDR_THEME_NTP_BACKGROUND?' - 'iamefpfkojoapidjnbafmgkgncegbkad') - - def setUp(self): - super(ThemeUpdater, self).setUp() - self._user_data_dir = util.MakeTempDir() - - def _CheckThemeApplied(self): - """Loads the New Tab Page and asserts that the theme is applied.""" - self._driver.get('chrome://newtab') - html = self._driver.find_element_by_xpath('html') - html_background = html.value_of_css_property('background-image') - self.assertTrue(self.camo_img in html_background, - msg='Did not find expected theme background-image') - - def _StartChromeProfile(self, incognito=False): - """Start Chrome with a temp profile. - - Args: - incognito: Boolean flag for starting Chrome in incognito. - """ - options = chrome_options.ChromeOptions() - options.SetUserDataDir(self._user_data_dir) - if incognito: - options.AddSwitch('incognito') - self.StartChrome(options.GetCapabilities()) - - def _StartChromeProfileExtension(self, extension): - """Start Chrome with a temp profile and with specified extension. - - Args: - extension: Paths to extension to be installed. - """ - options = chrome_options.ChromeOptions() - options.AddExtension(extension) - options.SetUserDataDir(self._user_data_dir) - self.StartChrome(options.GetCapabilities()) - - def testInstallTheme(self): - """Install a theme and check it is still applied after update.""" - self.Install(self.GetUpdateBuilds()[0]) - self._StartChromeProfileExtension(self.camo_theme) - self._CheckThemeApplied() - - # Update and relaunch without extension. - self.Install(self.GetUpdateBuilds()[1]) - self._StartChromeProfile() - self._CheckThemeApplied() - - def testInstallThemeIncognito(self): - """Install a theme and check it still applies to incognito after update.""" - self.Install(self.GetUpdateBuilds()[0]) - self._StartChromeProfileExtension(self.camo_theme) - self._CheckThemeApplied() - - # Relaunch without extension in incognito. - self._driver.quit() - self._StartChromeProfile(incognito=True) - self._CheckThemeApplied() - - # Update and relaunch without extension in incognito. - self.Install(self.GetUpdateBuilds()[1]) - self._StartChromeProfile(incognito=True) - self._CheckThemeApplied() diff --git a/chrome/test/nacl/pnacl_header_test.cc b/chrome/test/nacl/pnacl_header_test.cc index 2c62e6f0a3..6783397ea3 100644 --- a/chrome/test/nacl/pnacl_header_test.cc +++ b/chrome/test/nacl/pnacl_header_test.cc @@ -25,7 +25,7 @@ PnaclHeaderTest::PnaclHeaderTest() : noncors_loads_(0), cors_loads_(0) {} PnaclHeaderTest::~PnaclHeaderTest() {} -void PnaclHeaderTest::SetUp() { +void PnaclHeaderTest::StartServer() { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); // For most requests, just serve files, but register a special test handler @@ -35,19 +35,12 @@ void PnaclHeaderTest::SetUp() { embedded_test_server()->RegisterRequestHandler( base::Bind(&PnaclHeaderTest::WatchForPexeFetch, base::Unretained(this))); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); - noncors_loads_ = 0; - cors_loads_ = 0; - InProcessBrowserTest::SetUp(); -} - -void PnaclHeaderTest::TearDown() { - ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete()); - InProcessBrowserTest::TearDown(); } void PnaclHeaderTest::RunLoadTest(const std::string& url, int expected_noncors, int expected_cors) { + StartServer(); LoadTestMessageHandler handler; JavascriptTestObserver observer( browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost(), @@ -105,8 +98,7 @@ scoped_ptr<HttpResponse> PnaclHeaderTest::WatchForPexeFetch( return http_response.PassAs<HttpResponse>(); } -// Disabled: http://crbug.com/315328. -IN_PROC_BROWSER_TEST_F(PnaclHeaderTest, DISABLED_TestHasPnaclHeader) { +IN_PROC_BROWSER_TEST_F(PnaclHeaderTest, TestHasPnaclHeader) { // Load 2 pexes, one same origin and one cross orgin. RunLoadTest("/nacl/pnacl_request_header/pnacl_request_header.html", 1, 1); } diff --git a/chrome/test/nacl/pnacl_header_test.h b/chrome/test/nacl/pnacl_header_test.h index da41a967e6..9134925edd 100644 --- a/chrome/test/nacl/pnacl_header_test.h +++ b/chrome/test/nacl/pnacl_header_test.h @@ -32,10 +32,9 @@ class PnaclHeaderTest : public InProcessBrowserTest { int expected_noncors, int expected_cors); - virtual void SetUp() OVERRIDE; - virtual void TearDown() OVERRIDE; - private: + void StartServer(); + scoped_ptr<net::test_server::HttpResponse> WatchForPexeFetch( const net::test_server::HttpRequest& request); diff --git a/chrome/test/perf/generate_profile.cc b/chrome/test/perf/generate_profile.cc index b3fcf66c9a..0e38251f12 100644 --- a/chrome/test/perf/generate_profile.cc +++ b/chrome/test/perf/generate_profile.cc @@ -37,21 +37,6 @@ using content::BrowserThread; namespace { -// RAII for initializing and shutting down the TestBrowserProcess -class InitBrowserProcess { - public: - InitBrowserProcess() { - DCHECK(!g_browser_process); - g_browser_process = new TestingBrowserProcess; - } - - ~InitBrowserProcess() { - DCHECK(g_browser_process); - delete g_browser_process; - g_browser_process = NULL; - } -}; - // Probabilities of different word lengths, as measured from Darin's profile. // kWordLengthProbabilities[n-1] = P(word of length n) const float kWordLengthProbabilities[] = { 0.069f, 0.132f, 0.199f, @@ -205,7 +190,7 @@ void InsertURLBatch(Profile* profile, bool GenerateProfile(GenerateProfileTypes types, int url_count, const base::FilePath& dst_dir) { - if (!file_util::CreateDirectory(dst_dir)) { + if (!base::CreateDirectory(dst_dir)) { PLOG(ERROR) << "Unable to create directory " << dst_dir.value().c_str(); return false; } @@ -216,7 +201,7 @@ bool GenerateProfile(GenerateProfileTypes types, printf("Creating profiles for testing...\n"); - InitBrowserProcess initialize_browser_process; + TestingBrowserProcessInitializer initialize_browser_process; base::MessageLoopForUI message_loop; content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop); content::TestBrowserThread db_thread(BrowserThread::DB, &message_loop); diff --git a/chrome/test/perf/memory_test.cc b/chrome/test/perf/memory_test.cc index 95a03c0499..f5952ba73a 100644 --- a/chrome/test/perf/memory_test.cc +++ b/chrome/test/perf/memory_test.cc @@ -233,7 +233,7 @@ class MemoryTest : public UIPerfTest { // We create a copy of the test dir and use it so that each // run of this test starts with the same data. Running this // test has the side effect that it will change the profile. - if (!file_util::CreateNewTempDirectory(kTempDirName, &temp_dir_)) { + if (!base::CreateNewTempDirectory(kTempDirName, &temp_dir_)) { LOG(ERROR) << "Could not create temp directory:" << kTempDirName; return false; } diff --git a/chrome/test/ppapi/ppapi_browsertest.cc b/chrome/test/ppapi/ppapi_browsertest.cc index 6f4b8a3a22..840b2a25bd 100644 --- a/chrome/test/ppapi/ppapi_browsertest.cc +++ b/chrome/test/ppapi/ppapi_browsertest.cc @@ -306,6 +306,12 @@ TEST_PPAPI_NACL(Graphics2D_BindNull) #define MAYBE_OUT_Graphics3D Graphics3D #define MAYBE_NACL_Graphics3D DISABLED_Graphics3D #endif // defined(USE_AURA) +#elif defined(OS_MACOSX) +// These tests fail when using the legacy software mode. Reenable when the +// software compositor is enabled crbug.com/286038 +#define MAYBE_IN_Graphics3D DISABLED_Graphics3D +#define MAYBE_OUT_Graphics3D DISABLED_Graphics3D +#define MAYBE_NACL_Graphics3D DISABLED_Graphics3D #else // The tests are failing in-process. crbug.com/280282 #define MAYBE_IN_Graphics3D DISABLED_Graphics3D diff --git a/chrome/test/ppapi/ppapi_test.cc b/chrome/test/ppapi/ppapi_test.cc index a33e45cb52..783ae0e6cc 100644 --- a/chrome/test/ppapi/ppapi_test.cc +++ b/chrome/test/ppapi/ppapi_test.cc @@ -49,14 +49,12 @@ PPAPITestMessageHandler::PPAPITestMessageHandler() { TestMessageHandler::MessageResponse PPAPITestMessageHandler::HandleMessage( const std::string& json) { - std::string trimmed; - TrimString(json, "\"", &trimmed); - if (trimmed == "...") { - return CONTINUE; - } else { - message_ = trimmed; - return DONE; - } + std::string trimmed; + base::TrimString(json, "\"", &trimmed); + if (trimmed == "...") + return CONTINUE; + message_ = trimmed; + return DONE; } void PPAPITestMessageHandler::Reset() { @@ -109,8 +107,9 @@ void PPAPITestBase::InfoBarObserver::VerifyInfoBarState() { return; expecting_infobar_ = false; - InfoBarDelegate* infobar = infobar_service->infobar_at(0); - ConfirmInfoBarDelegate* delegate = infobar->AsConfirmInfoBarDelegate(); + InfoBar* infobar = infobar_service->infobar_at(0); + ConfirmInfoBarDelegate* delegate = + infobar->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(delegate != NULL); if (should_accept_) delegate->Accept(); diff --git a/chrome/test/pyautolib/OWNERS b/chrome/test/pyautolib/OWNERS index 79f71e6e40..afe7a77b01 100644 --- a/chrome/test/pyautolib/OWNERS +++ b/chrome/test/pyautolib/OWNERS @@ -1,2 +1 @@ craigdh@chromium.org -kkania@chromium.org diff --git a/chrome/test/pyautolib/asan_stub.c b/chrome/test/pyautolib/asan_stub.c index 396078b07a..d2184515fb 100644 --- a/chrome/test/pyautolib/asan_stub.c +++ b/chrome/test/pyautolib/asan_stub.c @@ -109,4 +109,25 @@ void __asan_unregister_globals() { } void __sanitizer_sandbox_on_notify() { } void __asan_before_dynamic_init(const char *module_name) { } void __asan_after_dynamic_init() { } - +int __asan_option_detect_stack_use_after_return; +typedef unsigned long long uptr; +uptr __asan_stack_malloc_1(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_2(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_3(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_4(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_5(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_6(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_7(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_8(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_9(uptr size, uptr real_stack) {} +uptr __asan_stack_malloc_10(uptr size, uptr real_stack) {} +void __asan_stack_free_1(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_2(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_3(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_4(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_5(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_6(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_7(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_8(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_9(uptr ptr, uptr size, uptr real_stack) {} +void __asan_stack_free_10(uptr ptr, uptr size, uptr real_stack) {} diff --git a/chrome/test/remoting/me2me_browsertest.cc b/chrome/test/remoting/me2me_browsertest.cc index 7072cae896..d5cefe7331 100644 --- a/chrome/test/remoting/me2me_browsertest.cc +++ b/chrome/test/remoting/me2me_browsertest.cc @@ -87,7 +87,7 @@ void Me2MeBrowserTest::TestKeyboardInput() { ASSERT_TRUE(TimeoutWaiter(base::TimeDelta::FromMilliseconds(300)).Wait()); base::FilePath temp_file; - EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_file)); + EXPECT_TRUE(base::CreateTemporaryFile(&temp_file)); // Write some text into the temp file. std::string text = "Abigail"; diff --git a/chrome/test/remoting/remote_desktop_browsertest.cc b/chrome/test/remoting/remote_desktop_browsertest.cc index 677392506a..2a03c2d2ef 100644 --- a/chrome/test/remoting/remote_desktop_browsertest.cc +++ b/chrome/test/remoting/remote_desktop_browsertest.cc @@ -161,7 +161,8 @@ void RemoteDesktopBrowserTest::LaunchChromotingApp() { OpenApplication(AppLaunchParams( browser()->profile(), extension_, - is_platform_app() ? extensions::LAUNCH_NONE : extensions::LAUNCH_TAB, + is_platform_app() ? extensions::LAUNCH_CONTAINER_NONE : + extensions::LAUNCH_CONTAINER_TAB, is_platform_app() ? NEW_WINDOW : CURRENT_TAB)); observer.Wait(); diff --git a/chrome/test/security_tests/sandbox_browsertest_linux.cc b/chrome/test/security_tests/sandbox_browsertest_linux.cc index f9c2659900..f51db555bf 100644 --- a/chrome/test/security_tests/sandbox_browsertest_linux.cc +++ b/chrome/test/security_tests/sandbox_browsertest_linux.cc @@ -27,7 +27,7 @@ IN_PROC_BROWSER_TEST_F(SandboxLinuxTest, MAYBE_SandboxStatus) { status & content::kSandboxLinuxPIDNS && status & content::kSandboxLinuxNetNS; // A second-layer sandbox is also required to be adequately sandboxed. - bool good_layer2 = status & content::kSandboxLinuxSeccompBpf; + bool good_layer2 = status & content::kSandboxLinuxSeccompBPF; EXPECT_TRUE(good_layer1); EXPECT_TRUE(good_layer2); |