diff options
49 files changed, 1273 insertions, 972 deletions
diff --git a/chrome/browser/chrome_plugin_unittest.cc b/chrome/browser/chrome_plugin_unittest.cc index cd80ac7..72c4a1a 100644 --- a/chrome/browser/chrome_plugin_unittest.cc +++ b/chrome/browser/chrome_plugin_unittest.cc @@ -13,10 +13,11 @@ #include "chrome/common/chrome_plugin_lib.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/test/chrome_plugin/test_chrome_plugin.h" +#include "chrome/test/test_url_request_context_getter.h" #include "net/base/io_buffer.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "net/test/test_server.h" #include "testing/gtest/include/gtest/gtest.h" @@ -26,22 +27,6 @@ const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data"); const char kPluginFilename[] = "test_chrome_plugin.dll"; const int kResponseBufferSize = 4096; -class TestURLRequestContextGetter : public URLRequestContextGetter { - public: - virtual net::URLRequestContext* GetURLRequestContext() { - if (!context_) - context_ = new TestURLRequestContext(); - return context_; - } - virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const { - return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); - } - - private: - ~TestURLRequestContextGetter() {} - scoped_refptr<net::URLRequestContext> context_; -}; - class ChromePluginTest : public testing::Test, public net::URLRequest::Delegate { public: diff --git a/chrome/browser/chromeos/gview_request_interceptor_unittest.cc b/chrome/browser/chromeos/gview_request_interceptor_unittest.cc index e195c4e..b2c8c86 100644 --- a/chrome/browser/chromeos/gview_request_interceptor_unittest.cc +++ b/chrome/browser/chromeos/gview_request_interceptor_unittest.cc @@ -11,7 +11,7 @@ #include "net/url_request/url_request.h" #include "net/url_request/url_request_job.h" #include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/glue/plugins/plugin_list.h" diff --git a/chrome/browser/download/download_uitest.cc b/chrome/browser/download/download_uitest.cc index 39e1ac2..743642c 100644 --- a/chrome/browser/download/download_uitest.cc +++ b/chrome/browser/download/download_uitest.cc @@ -23,7 +23,7 @@ #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/browser_proxy.h" #include "net/base/net_util.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #if defined(OS_WIN) #include <shlwapi.h> diff --git a/chrome/browser/download/save_page_uitest.cc b/chrome/browser/download/save_page_uitest.cc index d6078b3..3f72d80 100644 --- a/chrome/browser/download/save_page_uitest.cc +++ b/chrome/browser/download/save_page_uitest.cc @@ -14,7 +14,7 @@ #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "chrome/test/ui_test_utils.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" namespace { diff --git a/chrome/browser/extensions/user_script_listener_unittest.cc b/chrome/browser/extensions/user_script_listener_unittest.cc index 9847694..220cd06 100644 --- a/chrome/browser/extensions/user_script_listener_unittest.cc +++ b/chrome/browser/extensions/user_script_listener_unittest.cc @@ -16,7 +16,7 @@ #include "chrome/common/notification_type.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" class Profile; diff --git a/chrome/browser/google/google_url_tracker_unittest.cc b/chrome/browser/google/google_url_tracker_unittest.cc index 45b707a..9507150 100644 --- a/chrome/browser/google/google_url_tracker_unittest.cc +++ b/chrome/browser/google/google_url_tracker_unittest.cc @@ -19,7 +19,7 @@ #include "chrome/test/testing_pref_service.h" #include "chrome/test/testing_profile.h" #include "net/url_request/url_request.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" // TestNotificationObserver --------------------------------------------------- diff --git a/chrome/browser/policy/device_management_service_unittest.cc b/chrome/browser/policy/device_management_service_unittest.cc index 4162a3f..b21ed40 100644 --- a/chrome/browser/policy/device_management_service_unittest.cc +++ b/chrome/browser/policy/device_management_service_unittest.cc @@ -15,7 +15,7 @@ #include "chrome/test/test_url_request_context_getter.h" #include "net/base/escape.h" #include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" diff --git a/chrome/browser/printing/print_dialog_cloud_uitest.cc b/chrome/browser/printing/print_dialog_cloud_uitest.cc index 8ecb1ff..e64ff81 100644 --- a/chrome/browser/printing/print_dialog_cloud_uitest.cc +++ b/chrome/browser/printing/print_dialog_cloud_uitest.cc @@ -25,7 +25,7 @@ #include "chrome/test/ui_test_utils.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" namespace { diff --git a/chrome/browser/sync/glue/http_bridge_unittest.cc b/chrome/browser/sync/glue/http_bridge_unittest.cc index 600e570..88cd775 100644 --- a/chrome/browser/sync/glue/http_bridge_unittest.cc +++ b/chrome/browser/sync/glue/http_bridge_unittest.cc @@ -7,7 +7,8 @@ #include "chrome/browser/browser_thread.h" #include "chrome/browser/sync/glue/http_bridge.h" #include "chrome/common/net/test_url_fetcher_factory.h" -#include "net/url_request/url_request_unittest.h" +#include "chrome/test/test_url_request_context_getter.h" +#include "net/url_request/url_request_test_util.h" #include "net/test/test_server.h" #include "testing/gtest/include/gtest/gtest.h" @@ -18,24 +19,6 @@ namespace { const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data"); } -// Lazy getter for TestURLRequestContext instances. -class TestURLRequestContextGetter : public URLRequestContextGetter { - public: - virtual net::URLRequestContext* GetURLRequestContext() { - if (!context_) - context_ = new TestURLRequestContext; - return context_; - } - virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const { - return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); - } - - private: - ~TestURLRequestContextGetter() {} - - scoped_refptr<net::URLRequestContext> context_; -}; - class HttpBridgeTest : public testing::Test { public: HttpBridgeTest() diff --git a/chrome/browser/unload_uitest.cc b/chrome/browser/unload_uitest.cc index f30ed16..4a940b0 100644 --- a/chrome/browser/unload_uitest.cc +++ b/chrome/browser/unload_uitest.cc @@ -11,7 +11,7 @@ #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "ui/base/message_box_flags.h" #include "views/event.h" diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index bb56e40..ee495e0 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi @@ -34,6 +34,8 @@ 'theme_resources', '../base/base.gyp:test_support_base', '../ipc/ipc.gyp:test_support_ipc', + # 'test/test_url_request_context_getter.h' brings in this requirement. + '../net/net.gyp:net_test_support', '../skia/skia.gyp:skia', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', @@ -3207,6 +3209,7 @@ 'renderer', 'syncapi', '../base/base.gyp:base', + '../net/net.gyp:net_test_support', '../skia/skia.gyp:skia', ], 'include_dirs': [ diff --git a/chrome/common/net/url_fetcher_unittest.cc b/chrome/common/net/url_fetcher_unittest.cc index b4b3227..0d36f02 100644 --- a/chrome/common/net/url_fetcher_unittest.cc +++ b/chrome/common/net/url_fetcher_unittest.cc @@ -3,16 +3,16 @@ // found in the LICENSE file. #include "base/message_loop_proxy.h" -#include "base/threading/thread.h" #include "base/synchronization/waitable_event.h" +#include "base/threading/thread.h" #include "build/build_config.h" #include "chrome/common/chrome_plugin_lib.h" #include "chrome/common/net/url_fetcher.h" #include "chrome/common/net/url_request_context_getter.h" #include "net/http/http_response_headers.h" #include "net/test/test_server.h" +#include "net/url_request/url_request_test_util.h" #include "net/url_request/url_request_throttler_manager.h" -#include "net/url_request/url_request_unittest.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(USE_NSS) diff --git a/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc b/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc index 50ecaab..6d399b0 100644 --- a/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc +++ b/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc @@ -5,16 +5,16 @@ #include "base/command_line.h" #include "base/message_loop_proxy.h" #include "base/ref_counted.h" -#include "base/threading/thread.h" #include "base/synchronization/waitable_event.h" +#include "base/threading/thread.h" #include "chrome/common/net/url_request_context_getter.h" -#include "chrome/service/service_process.h" #include "chrome/service/cloud_print/cloud_print_url_fetcher.h" +#include "chrome/service/service_process.h" #include "googleurl/src/gurl.h" #include "net/test/test_server.h" #include "net/url_request/url_request_status.h" +#include "net/url_request/url_request_test_util.h" #include "net/url_request/url_request_throttler_manager.h" -#include "net/url_request/url_request_unittest.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; diff --git a/chrome/test/test_url_request_context_getter.h b/chrome/test/test_url_request_context_getter.h index 61dc327..43ff974 100644 --- a/chrome/test/test_url_request_context_getter.h +++ b/chrome/test/test_url_request_context_getter.h @@ -9,7 +9,7 @@ #include "base/ref_counted.h" #include "chrome/browser/browser_thread.h" #include "chrome/common/net/url_request_context_getter.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" // Used to return a dummy context (normally the context is on the IO thread). // The one here can be run on the main test thread. Note that this can lead to diff --git a/chrome/test/testing_profile.cc b/chrome/test/testing_profile.cc index 6b584af..00af1d1 100644 --- a/chrome/test/testing_profile.cc +++ b/chrome/test/testing_profile.cc @@ -46,7 +46,7 @@ #include "chrome/test/ui_test_utils.h" #include "net/base/cookie_monster.h" #include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "webkit/database/database_tracker.h" #if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS) diff --git a/chrome_frame/chrome_frame.gyp b/chrome_frame/chrome_frame.gyp index e1596c8..bfc88f3 100644 --- a/chrome_frame/chrome_frame.gyp +++ b/chrome_frame/chrome_frame.gyp @@ -484,8 +484,6 @@ 'npchrome_frame', ], 'sources': [ - '../net/url_request/url_request_unittest.cc', - '../net/url_request/url_request_unittest.h', 'test/chrome_frame_test_utils.cc', 'test/chrome_frame_test_utils.h', 'test/simulate_input.cc', diff --git a/chrome_frame/test/test_server_test.cc b/chrome_frame/test/test_server_test.cc index f273dce..1355471 100644 --- a/chrome_frame/test/test_server_test.cc +++ b/chrome_frame/test/test_server_test.cc @@ -16,7 +16,7 @@ #include "net/http/http_cache.h" #include "net/proxy/proxy_service.h" #include "net/url_request/url_request.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" class TestServerTest: public testing::Test { diff --git a/net/base/cookie_monster_store_test.cc b/net/base/cookie_monster_store_test.cc new file mode 100644 index 0000000..e785a38 --- /dev/null +++ b/net/base/cookie_monster_store_test.cc @@ -0,0 +1,176 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/base/cookie_monster_store_test.h" + +#include "base/message_loop.h" +#include "base/stringprintf.h" +#include "base/time.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { + +MockPersistentCookieStore::MockPersistentCookieStore() + : load_return_value_(true) { +} + +MockPersistentCookieStore::~MockPersistentCookieStore() {} + +void MockPersistentCookieStore::SetLoadExpectation( + bool return_value, + const std::vector<net::CookieMonster::CanonicalCookie*>& result) { + load_return_value_ = return_value; + load_result_ = result; +} + +bool MockPersistentCookieStore::Load( + std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies) { + bool ok = load_return_value_; + if (ok) + *out_cookies = load_result_; + return ok; +} + +void MockPersistentCookieStore::AddCookie( + const net::CookieMonster::CanonicalCookie& cookie) { + commands_.push_back( + CookieStoreCommand(CookieStoreCommand::ADD, cookie)); +} + +void MockPersistentCookieStore::UpdateCookieAccessTime( + const net::CookieMonster::CanonicalCookie& cookie) { + commands_.push_back(CookieStoreCommand( + CookieStoreCommand::UPDATE_ACCESS_TIME, cookie)); +} + +void MockPersistentCookieStore::DeleteCookie( + const net::CookieMonster::CanonicalCookie& cookie) { + commands_.push_back( + CookieStoreCommand(CookieStoreCommand::REMOVE, cookie)); +} + +void MockPersistentCookieStore::Flush(Task* completion_task) { + if (completion_task) + MessageLoop::current()->PostTask(FROM_HERE, completion_task); +} + +// No files are created so nothing to clear either +void +MockPersistentCookieStore::SetClearLocalStateOnExit(bool clear_local_state) { +} + +MockCookieMonsterDelegate::MockCookieMonsterDelegate() {} + +void MockCookieMonsterDelegate::OnCookieChanged( + const net::CookieMonster::CanonicalCookie& cookie, + bool removed) { + CookieNotification notification(cookie, removed); + changes_.push_back(notification); + } + +MockCookieMonsterDelegate::~MockCookieMonsterDelegate() {} + +void AddCookieToList( + const std::string& key, + const std::string& cookie_line, + const base::Time& creation_time, + std::vector<net::CookieMonster::CanonicalCookie*>* out_list) { + + // Parse the cookie line. + net::CookieMonster::ParsedCookie pc(cookie_line); + EXPECT_TRUE(pc.IsValid()); + + // This helper is simplistic in interpreting a parsed cookie, in order to + // avoid duplicated CookieMonster's CanonPath() and CanonExpiration() + // functions. Would be nice to export them, and re-use here. + EXPECT_FALSE(pc.HasMaxAge()); + EXPECT_TRUE(pc.HasPath()); + base::Time cookie_expires = pc.HasExpires() ? + net::CookieMonster::ParseCookieTime(pc.Expires()) : base::Time(); + std::string cookie_path = pc.Path(); + + scoped_ptr<net::CookieMonster::CanonicalCookie> cookie( + new net::CookieMonster::CanonicalCookie( + pc.Name(), pc.Value(), key, cookie_path, + pc.IsSecure(), pc.IsHttpOnly(), + creation_time, creation_time, + !cookie_expires.is_null(), + cookie_expires)); + + out_list->push_back(cookie.release()); +} + +MockSimplePersistentCookieStore::MockSimplePersistentCookieStore() {} + +MockSimplePersistentCookieStore::~MockSimplePersistentCookieStore() {} + +bool MockSimplePersistentCookieStore::Load( + std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies) { + for (CanonicalCookieMap::const_iterator it = cookies_.begin(); + it != cookies_.end(); it++) + out_cookies->push_back( + new net::CookieMonster::CanonicalCookie(it->second)); + return true; +} + +void MockSimplePersistentCookieStore::AddCookie( + const net::CookieMonster::CanonicalCookie& cookie) { + int64 creation_time = cookie.CreationDate().ToInternalValue(); + EXPECT_TRUE(cookies_.find(creation_time) == cookies_.end()); + cookies_[creation_time] = cookie; +} + +void MockSimplePersistentCookieStore::UpdateCookieAccessTime( + const net::CookieMonster::CanonicalCookie& cookie) { + int64 creation_time = cookie.CreationDate().ToInternalValue(); + ASSERT_TRUE(cookies_.find(creation_time) != cookies_.end()); + cookies_[creation_time].SetLastAccessDate(base::Time::Now()); +} + +void MockSimplePersistentCookieStore::DeleteCookie( + const net::CookieMonster::CanonicalCookie& cookie) { + int64 creation_time = cookie.CreationDate().ToInternalValue(); + CanonicalCookieMap::iterator it = cookies_.find(creation_time); + ASSERT_TRUE(it != cookies_.end()); + cookies_.erase(it); +} + +void MockSimplePersistentCookieStore::Flush(Task* completion_task) { + if (completion_task) + MessageLoop::current()->PostTask(FROM_HERE, completion_task); +} + +void MockSimplePersistentCookieStore::SetClearLocalStateOnExit( + bool clear_local_state) { +} + +net::CookieMonster* CreateMonsterFromStoreForGC( + int num_cookies, + int num_old_cookies, + int days_old) { + base::Time current(base::Time::Now()); + base::Time past_creation(base::Time::Now() - base::TimeDelta::FromDays(1000)); + scoped_refptr<MockSimplePersistentCookieStore> store( + new MockSimplePersistentCookieStore); + // Must expire to be persistent + for (int i = 0; i < num_old_cookies; i++) { + net::CookieMonster::CanonicalCookie cc( + "a", "1", base::StringPrintf("h%05d.izzle", i), "/path", false, false, + past_creation + base::TimeDelta::FromMicroseconds(i), + current - base::TimeDelta::FromDays(days_old), + true, current + base::TimeDelta::FromDays(30)); + store->AddCookie(cc); + } + for (int i = num_old_cookies; i < num_cookies; i++) { + net::CookieMonster::CanonicalCookie cc( + "a", "1", base::StringPrintf("h%05d.izzle", i), "/path", false, false, + past_creation + base::TimeDelta::FromMicroseconds(i), current, + true, current + base::TimeDelta::FromDays(30)); + store->AddCookie(cc); + } + + return new net::CookieMonster(store, NULL); +} + +} // namespace net diff --git a/net/base/cookie_monster_store_test.h b/net/base/cookie_monster_store_test.h index 84ead74..951c055 100644 --- a/net/base/cookie_monster_store_test.h +++ b/net/base/cookie_monster_store_test.h @@ -1,4 +1,4 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -7,12 +7,13 @@ // that need to test out CookieMonster interactions with the backing store. // It should only be included by test code. -#include "base/message_loop.h" -#include "base/time.h" #include "net/base/cookie_monster.h" -#include "testing/gtest/include/gtest/gtest.h" -namespace { +namespace base { +class Time; +} + +namespace net { // Describes a call to one of the 3 functions of PersistentCookieStore. struct CookieStoreCommand { @@ -39,52 +40,32 @@ class MockPersistentCookieStore public: typedef std::vector<CookieStoreCommand> CommandList; - MockPersistentCookieStore() : load_return_value_(true) { + MockPersistentCookieStore(); + virtual ~MockPersistentCookieStore(); + + void SetLoadExpectation( + bool return_value, + const std::vector<net::CookieMonster::CanonicalCookie*>& result); + + const CommandList& commands() const { + return commands_; } virtual bool Load( - std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies) { - bool ok = load_return_value_; - if (ok) - *out_cookies = load_result_; - return ok; - } + std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies); - virtual void AddCookie(const net::CookieMonster::CanonicalCookie& cookie) { - commands_.push_back( - CookieStoreCommand(CookieStoreCommand::ADD, cookie)); - } + virtual void AddCookie(const net::CookieMonster::CanonicalCookie& cookie); virtual void UpdateCookieAccessTime( - const net::CookieMonster::CanonicalCookie& cookie) { - commands_.push_back(CookieStoreCommand( - CookieStoreCommand::UPDATE_ACCESS_TIME, cookie)); - } + const net::CookieMonster::CanonicalCookie& cookie); virtual void DeleteCookie( - const net::CookieMonster::CanonicalCookie& cookie) { - commands_.push_back( - CookieStoreCommand(CookieStoreCommand::REMOVE, cookie)); - } + const net::CookieMonster::CanonicalCookie& cookie); - virtual void Flush(Task* completion_task) { - if (completion_task) - MessageLoop::current()->PostTask(FROM_HERE, completion_task); - } + virtual void Flush(Task* completion_task); // No files are created so nothing to clear either - virtual void SetClearLocalStateOnExit(bool clear_local_state) {} - - void SetLoadExpectation( - bool return_value, - const std::vector<net::CookieMonster::CanonicalCookie*>& result) { - load_return_value_ = return_value; - load_result_ = result; - } - - const CommandList& commands() const { - return commands_; - } + virtual void SetClearLocalStateOnExit(bool clear_local_state); private: CommandList commands_; @@ -102,21 +83,18 @@ class MockCookieMonsterDelegate : public net::CookieMonster::Delegate { typedef std::pair<net::CookieMonster::CanonicalCookie, bool> CookieNotification; - MockCookieMonsterDelegate() {} - - virtual void OnCookieChanged( - const net::CookieMonster::CanonicalCookie& cookie, - bool removed) { - CookieNotification notification(cookie, removed); - changes_.push_back(notification); - } + MockCookieMonsterDelegate(); const std::vector<CookieNotification>& changes() const { return changes_; } void reset() { changes_.clear(); } + virtual void OnCookieChanged( + const net::CookieMonster::CanonicalCookie& cookie, + bool removed); + private: - virtual ~MockCookieMonsterDelegate() {} + virtual ~MockCookieMonsterDelegate(); std::vector<CookieNotification> changes_; @@ -124,84 +102,40 @@ class MockCookieMonsterDelegate : public net::CookieMonster::Delegate { }; // Helper to build a list of CanonicalCookie*s. -static void AddCookieToList( +void AddCookieToList( const std::string& key, const std::string& cookie_line, const base::Time& creation_time, - std::vector<net::CookieMonster::CanonicalCookie*>* out_list) { - - // Parse the cookie line. - net::CookieMonster::ParsedCookie pc(cookie_line); - EXPECT_TRUE(pc.IsValid()); - - // This helper is simplistic in interpreting a parsed cookie, in order to - // avoid duplicated CookieMonster's CanonPath() and CanonExpiration() - // functions. Would be nice to export them, and re-use here. - EXPECT_FALSE(pc.HasMaxAge()); - EXPECT_TRUE(pc.HasPath()); - base::Time cookie_expires = pc.HasExpires() ? - net::CookieMonster::ParseCookieTime(pc.Expires()) : base::Time(); - std::string cookie_path = pc.Path(); - - scoped_ptr<net::CookieMonster::CanonicalCookie> cookie( - new net::CookieMonster::CanonicalCookie( - pc.Name(), pc.Value(), key, cookie_path, - pc.IsSecure(), pc.IsHttpOnly(), - creation_time, creation_time, - !cookie_expires.is_null(), - cookie_expires)); - - out_list->push_back(cookie.release()); -} + std::vector<net::CookieMonster::CanonicalCookie*>* out_list); // Just act like a backing database. Keep cookie information from // Add/Update/Delete and regurgitate it when Load is called. class MockSimplePersistentCookieStore : public net::CookieMonster::PersistentCookieStore { - private: - typedef std::map<int64, net::CookieMonster::CanonicalCookie> - CanonicalCookieMap; - public: + MockSimplePersistentCookieStore(); + virtual ~MockSimplePersistentCookieStore(); + virtual bool Load( - std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies) { - for (CanonicalCookieMap::const_iterator it = cookies_.begin(); - it != cookies_.end(); it++) - out_cookies->push_back( - new net::CookieMonster::CanonicalCookie(it->second)); - return true; - } + std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies); virtual void AddCookie( - const net::CookieMonster::CanonicalCookie& cookie) { - int64 creation_time = cookie.CreationDate().ToInternalValue(); - EXPECT_TRUE(cookies_.find(creation_time) == cookies_.end()); - cookies_[creation_time] = cookie; - } + const net::CookieMonster::CanonicalCookie& cookie); virtual void UpdateCookieAccessTime( - const net::CookieMonster::CanonicalCookie& cookie) { - int64 creation_time = cookie.CreationDate().ToInternalValue(); - ASSERT_TRUE(cookies_.find(creation_time) != cookies_.end()); - cookies_[creation_time].SetLastAccessDate(base::Time::Now()); - } + const net::CookieMonster::CanonicalCookie& cookie); virtual void DeleteCookie( - const net::CookieMonster::CanonicalCookie& cookie) { - int64 creation_time = cookie.CreationDate().ToInternalValue(); - CanonicalCookieMap::iterator it = cookies_.find(creation_time); - ASSERT_TRUE(it != cookies_.end()); - cookies_.erase(it); - } + const net::CookieMonster::CanonicalCookie& cookie); - virtual void Flush(Task* completion_task) { - if (completion_task) - MessageLoop::current()->PostTask(FROM_HERE, completion_task); - } + virtual void Flush(Task* completion_task); - virtual void SetClearLocalStateOnExit(bool clear_local_state) {} + virtual void SetClearLocalStateOnExit(bool clear_local_state); private: + typedef std::map<int64, net::CookieMonster::CanonicalCookie> + CanonicalCookieMap; + CanonicalCookieMap cookies_; }; @@ -213,32 +147,9 @@ class MockSimplePersistentCookieStore // Do two SetCookies(). Return whether each of the two SetCookies() took // longer than |gc_perf_micros| to complete, and how many cookie were // left in the store afterwards. -static net::CookieMonster* CreateMonsterFromStoreForGC( +net::CookieMonster* CreateMonsterFromStoreForGC( int num_cookies, int num_old_cookies, - int days_old) { - base::Time current(base::Time::Now()); - base::Time past_creation(base::Time::Now() - base::TimeDelta::FromDays(1000)); - scoped_refptr<MockSimplePersistentCookieStore> store( - new MockSimplePersistentCookieStore); - // Must expire to be persistent - for (int i = 0; i < num_old_cookies; i++) { - net::CookieMonster::CanonicalCookie cc( - "a", "1", StringPrintf("h%05d.izzle", i), "/path", false, false, - past_creation + base::TimeDelta::FromMicroseconds(i), - current - base::TimeDelta::FromDays(days_old), - true, current + base::TimeDelta::FromDays(30)); - store->AddCookie(cc); - } - for (int i = num_old_cookies; i < num_cookies; i++) { - net::CookieMonster::CanonicalCookie cc( - "a", "1", StringPrintf("h%05d.izzle", i), "/path", false, false, - past_creation + base::TimeDelta::FromMicroseconds(i), current, - true, current + base::TimeDelta::FromDays(30)); - store->AddCookie(cc); - } - - return new net::CookieMonster(store, NULL); -} + int days_old); -} // namespace +} // namespace net diff --git a/net/base/cookie_monster_unittest.cc b/net/base/cookie_monster_unittest.cc index f431674..caaad67 100644 --- a/net/base/cookie_monster_unittest.cc +++ b/net/base/cookie_monster_unittest.cc @@ -7,6 +7,7 @@ #include <string> #include "base/basictypes.h" +#include "base/message_loop.h" #include "base/ref_counted.h" #include "base/scoped_ptr.h" #include "base/string_util.h" diff --git a/net/base/filter_unittest.cc b/net/base/filter_unittest.cc index 75fee20..c65c3de 100644 --- a/net/base/filter_unittest.cc +++ b/net/base/filter_unittest.cc @@ -3,7 +3,7 @@ // found in the LICENSE file. #include "net/base/filter.h" -#include "net/base/filter_unittest.h" +#include "net/base/mock_filter_context.h" #include "testing/gtest/include/gtest/gtest.h" class FilterTest : public testing::Test { @@ -36,7 +36,7 @@ TEST(FilterTest, ContentTypeId) { // Check various fixups that modify content encoding lists. TEST(FilterTest, ApacheGzip) { const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetSdchResponse(false); // Check that redundant gzip mime type removes only solo gzip encoding. @@ -85,7 +85,7 @@ TEST(FilterTest, SdchEncoding) { // Handle content encodings including SDCH. const std::string kTextHtmlMime("text/html"); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetSdchResponse(true); std::vector<Filter::FilterType> encoding_types; @@ -123,7 +123,7 @@ TEST(FilterTest, MissingSdchEncoding) { // Handle interesting case where entire SDCH encoding assertion "got lost." const std::string kTextHtmlMime("text/html"); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetSdchResponse(true); std::vector<Filter::FilterType> encoding_types; @@ -159,7 +159,7 @@ TEST(FilterTest, MissingSdchEncoding) { TEST(FilterTest, Svgz) { const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); // Check that svgz files are only decompressed when not downloading. const std::string kSvgzMime("image/svg+xml"); @@ -208,7 +208,7 @@ TEST(FilterTest, Svgz) { TEST(FilterTest, UnsupportedMimeGzip) { // From issue 8170 - handling files with Content-Encoding: x-gzip const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); std::vector<Filter::FilterType> encoding_types; const std::string kTarMime("application/x-tar"); const std::string kCpioMime("application/x-cpio"); @@ -296,7 +296,7 @@ TEST(FilterTest, SupportedMimeGzip) { // From issue 16430 - Files with supported mime types should be decompressed, // even though these files end in .gz/.tgz. const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); std::vector<Filter::FilterType> encoding_types; const std::string kGzUrl("http://ignore.com/foo.gz"); const std::string kUrl("http://ignore.com/foo"); diff --git a/net/base/gzip_filter_unittest.cc b/net/base/gzip_filter_unittest.cc index 8ca1f4d..758418c 100644 --- a/net/base/gzip_filter_unittest.cc +++ b/net/base/gzip_filter_unittest.cc @@ -20,8 +20,8 @@ #include "base/file_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" -#include "net/base/filter_unittest.h" #include "net/base/gzip_filter.h" +#include "net/base/mock_filter_context.h" #include "net/base/io_buffer.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" @@ -243,7 +243,7 @@ TEST_F(GZipUnitTest, DecodeDeflate) { // Decode the compressed data with filter std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_DEFLATE); - MockFilterContext filter_context(kDefaultBufferSize); + net::MockFilterContext filter_context(kDefaultBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); memcpy(filter->stream_buffer()->data(), deflate_encode_buffer_, @@ -264,7 +264,7 @@ TEST_F(GZipUnitTest, DecodeGZip) { // Decode the compressed data with filter std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_GZIP); - MockFilterContext filter_context(kDefaultBufferSize); + net::MockFilterContext filter_context(kDefaultBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); memcpy(filter->stream_buffer()->data(), gzip_encode_buffer_, @@ -286,7 +286,7 @@ TEST_F(GZipUnitTest, DecodeGZip) { TEST_F(GZipUnitTest, DecodeWithSmallBuffer) { std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_DEFLATE); - MockFilterContext filter_context(kSmallBufferSize); + net::MockFilterContext filter_context(kSmallBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); DecodeAndCompareWithFilter(filter.get(), source_buffer(), source_len(), @@ -301,7 +301,7 @@ TEST_F(GZipUnitTest, DecodeWithSmallBuffer) { TEST_F(GZipUnitTest, DecodeWithOneByteBuffer) { std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_GZIP); - MockFilterContext filter_context(1); + net::MockFilterContext filter_context(1); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); DecodeAndCompareWithFilter(filter.get(), source_buffer(), source_len(), @@ -313,7 +313,7 @@ TEST_F(GZipUnitTest, DecodeWithOneByteBuffer) { TEST_F(GZipUnitTest, DecodeWithSmallOutputBuffer) { std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_DEFLATE); - MockFilterContext filter_context(kDefaultBufferSize); + net::MockFilterContext filter_context(kDefaultBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); DecodeAndCompareWithFilter(filter.get(), source_buffer(), source_len(), @@ -326,7 +326,7 @@ TEST_F(GZipUnitTest, DecodeWithSmallOutputBuffer) { TEST_F(GZipUnitTest, DecodeWithOneByteInputAndOutputBuffer) { std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_GZIP); - MockFilterContext filter_context(1); + net::MockFilterContext filter_context(1); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); DecodeAndCompareWithFilter(filter.get(), source_buffer(), source_len(), @@ -345,7 +345,7 @@ TEST_F(GZipUnitTest, DecodeCorruptedData) { // Decode the corrupted data with filter std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_DEFLATE); - MockFilterContext filter_context(kDefaultBufferSize); + net::MockFilterContext filter_context(kDefaultBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); char corrupt_decode_buffer[kDefaultBufferSize]; @@ -372,7 +372,7 @@ TEST_F(GZipUnitTest, DecodeMissingData) { // Decode the corrupted data with filter std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_DEFLATE); - MockFilterContext filter_context(kDefaultBufferSize); + net::MockFilterContext filter_context(kDefaultBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); char corrupt_decode_buffer[kDefaultBufferSize]; @@ -396,7 +396,7 @@ TEST_F(GZipUnitTest, DecodeCorruptedHeader) { // Decode the corrupted data with filter std::vector<Filter::FilterType> filter_types; filter_types.push_back(Filter::FILTER_TYPE_GZIP); - MockFilterContext filter_context(kDefaultBufferSize); + net::MockFilterContext filter_context(kDefaultBufferSize); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); ASSERT_TRUE(filter.get()); char corrupt_decode_buffer[kDefaultBufferSize]; diff --git a/net/base/listen_socket_unittest.cc b/net/base/listen_socket_unittest.cc index 53fc79b..75beeec 100644 --- a/net/base/listen_socket_unittest.cc +++ b/net/base/listen_socket_unittest.cc @@ -19,8 +19,12 @@ static const int kMaxQueueSize = 20; static const char kLoopback[] = "127.0.0.1"; static const int kDefaultTimeoutMs = 5000; -ListenSocket* ListenSocketTester::DoListen() { - return ListenSocket::Listen(kLoopback, kTestPort, this); +ListenSocketTester::ListenSocketTester() + : thread_(NULL), + loop_(NULL), + server_(NULL), + connection_(NULL), + cv_(&lock_) { } void ListenSocketTester::SetUp() { @@ -121,36 +125,6 @@ void ListenSocketTester::SendFromTester() { ReportAction(ListenSocketTestAction(ACTION_SEND)); } -void ListenSocketTester::DidAccept(ListenSocket *server, - ListenSocket *connection) { - connection_ = connection; - connection_->AddRef(); - ReportAction(ListenSocketTestAction(ACTION_ACCEPT)); -} - -void ListenSocketTester::DidRead(ListenSocket *connection, - const char* data, - int len) { - std::string str(data, len); - ReportAction(ListenSocketTestAction(ACTION_READ, str)); -} - -void ListenSocketTester::DidClose(ListenSocket *sock) { - ReportAction(ListenSocketTestAction(ACTION_CLOSE)); -} - -bool ListenSocketTester::Send(SOCKET sock, const std::string& str) { - int len = static_cast<int>(str.length()); - int send_len = HANDLE_EINTR(send(sock, str.data(), len, 0)); - if (send_len == SOCKET_ERROR) { - LOG(ERROR) << "send failed: " << errno; - return false; - } else if (send_len != len) { - return false; - } - return true; -} - void ListenSocketTester::TestClientSend() { ASSERT_TRUE(Send(test_socket_, kHelloWorld)); NextAction(); @@ -200,6 +174,42 @@ void ListenSocketTester::TestServerSend() { ASSERT_STREQ(buf, kHelloWorld); } +bool ListenSocketTester::Send(SOCKET sock, const std::string& str) { + int len = static_cast<int>(str.length()); + int send_len = HANDLE_EINTR(send(sock, str.data(), len, 0)); + if (send_len == SOCKET_ERROR) { + LOG(ERROR) << "send failed: " << errno; + return false; + } else if (send_len != len) { + return false; + } + return true; +} + +void ListenSocketTester::DidAccept(ListenSocket *server, + ListenSocket *connection) { + connection_ = connection; + connection_->AddRef(); + ReportAction(ListenSocketTestAction(ACTION_ACCEPT)); +} + +void ListenSocketTester::DidRead(ListenSocket *connection, + const char* data, + int len) { + std::string str(data, len); + ReportAction(ListenSocketTestAction(ACTION_READ, str)); +} + +void ListenSocketTester::DidClose(ListenSocket *sock) { + ReportAction(ListenSocketTestAction(ACTION_CLOSE)); +} + +ListenSocketTester::~ListenSocketTester() {} + +ListenSocket* ListenSocketTester::DoListen() { + return ListenSocket::Listen(kLoopback, kTestPort, this); +} + class ListenSocketTest: public PlatformTest { public: diff --git a/net/base/listen_socket_unittest.h b/net/base/listen_socket_unittest.h index f283cb0..f54fc31 100644 --- a/net/base/listen_socket_unittest.h +++ b/net/base/listen_socket_unittest.h @@ -68,24 +68,11 @@ class ListenSocketTester : public ListenSocket::ListenSocketDelegate, public base::RefCountedThreadSafe<ListenSocketTester> { - protected: - friend class base::RefCountedThreadSafe<ListenSocketTester>; - - virtual ~ListenSocketTester() {} - - virtual ListenSocket* DoListen(); - public: - ListenSocketTester() - : thread_(NULL), - loop_(NULL), - server_(NULL), - connection_(NULL), - cv_(&lock_) { - } + ListenSocketTester(); - virtual void SetUp(); - virtual void TearDown(); + void SetUp(); + void TearDown(); void ReportAction(const ListenSocketTestAction& action); void NextAction(); @@ -96,10 +83,6 @@ class ListenSocketTester : void Shutdown(); void Listen(); void SendFromTester(); - virtual void DidAccept(ListenSocket *server, ListenSocket *connection); - virtual void DidRead(ListenSocket *connection, const char* data, int len); - virtual void DidClose(ListenSocket *sock); - virtual bool Send(SOCKET sock, const std::string& str); // verify the send/read from client to server void TestClientSend(); // verify send/read of a longer string @@ -107,6 +90,13 @@ class ListenSocketTester : // verify a send/read from server to client void TestServerSend(); + virtual bool Send(SOCKET sock, const std::string& str); + + // ListenSocket::ListenSocketDelegate: + virtual void DidAccept(ListenSocket *server, ListenSocket *connection); + virtual void DidRead(ListenSocket *connection, const char* data, int len); + virtual void DidClose(ListenSocket *sock); + scoped_ptr<base::Thread> thread_; MessageLoopForIO* loop_; ListenSocket* server_; @@ -119,6 +109,13 @@ class ListenSocketTester : base::Lock lock_; // protects |queue_| and wraps |cv_| base::ConditionVariable cv_; std::deque<ListenSocketTestAction> queue_; + + protected: + friend class base::RefCountedThreadSafe<ListenSocketTester>; + + virtual ~ListenSocketTester(); + + virtual ListenSocket* DoListen(); }; #endif // NET_BASE_LISTEN_SOCKET_UNITTEST_H_ diff --git a/net/base/mock_filter_context.cc b/net/base/mock_filter_context.cc new file mode 100644 index 0000000..6ca541a --- /dev/null +++ b/net/base/mock_filter_context.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/base/mock_filter_context.h" + +namespace net { + +MockFilterContext::MockFilterContext(int buffer_size) + : buffer_size_(buffer_size), + is_cached_content_(false), + is_download_(false), + is_sdch_response_(false), + response_code_(-1) { +} + +MockFilterContext::~MockFilterContext() {} + +bool MockFilterContext::GetMimeType(std::string* mime_type) const { + *mime_type = mime_type_; + return true; +} + +// What URL was used to access this data? +// Return false if gurl is not present. +bool MockFilterContext::GetURL(GURL* gurl) const { + *gurl = gurl_; + return true; +} + +// What was this data requested from a server? +base::Time MockFilterContext::GetRequestTime() const { + return request_time_; +} + +bool MockFilterContext::IsCachedContent() const { return is_cached_content_; } + +bool MockFilterContext::IsDownload() const { return is_download_; } + +bool MockFilterContext::IsSdchResponse() const { return is_sdch_response_; } + +int64 MockFilterContext::GetByteReadCount() const { return 0; } + +int MockFilterContext::GetResponseCode() const { return response_code_; } + +int MockFilterContext::GetInputStreamBufferSize() const { return buffer_size_; } + +} // namespace net diff --git a/net/base/filter_unittest.h b/net/base/mock_filter_context.h index a45e353..53c63ec 100644 --- a/net/base/filter_unittest.h +++ b/net/base/mock_filter_context.h @@ -1,10 +1,9 @@ -// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// -#ifndef NET_BASE_FILTER_UNITTEST_H_ -#define NET_BASE_FILTER_UNITTEST_H_ +#ifndef NET_BASE_MOCK_FILTER_CONTEXT_H_ +#define NET_BASE_MOCK_FILTER_CONTEXT_H_ #pragma once #include <string> @@ -12,16 +11,12 @@ #include "googleurl/src/gurl.h" #include "net/base/filter.h" -//------------------------------------------------------------------------------ +namespace net { + class MockFilterContext : public FilterContext { public: - explicit MockFilterContext(int buffer_size) - : buffer_size_(buffer_size), - is_cached_content_(false), - is_download_(false), - is_sdch_response_(false), - response_code_(-1) { - } + explicit MockFilterContext(int buffer_size); + virtual ~MockFilterContext(); void SetBufferSize(int buffer_size) { buffer_size_ = buffer_size; } void SetMimeType(const std::string& mime_type) { mime_type_ = mime_type; } @@ -34,39 +29,31 @@ class MockFilterContext : public FilterContext { is_sdch_response_ = is_sdch_response; } - virtual bool GetMimeType(std::string* mime_type) const { - *mime_type = mime_type_; - return true; - } + virtual bool GetMimeType(std::string* mime_type) const; // What URL was used to access this data? // Return false if gurl is not present. - virtual bool GetURL(GURL* gurl) const { - *gurl = gurl_; - return true; - } + virtual bool GetURL(GURL* gurl) const; // What was this data requested from a server? - virtual base::Time GetRequestTime() const { - return request_time_; - } + virtual base::Time GetRequestTime() const; // Is data supplied from cache, or fresh across the net? - virtual bool IsCachedContent() const { return is_cached_content_; } + virtual bool IsCachedContent() const; // Is this a download? - virtual bool IsDownload() const { return is_download_; } + virtual bool IsDownload() const; // Was this data flagged as a response to a request with an SDCH dictionary? - virtual bool IsSdchResponse() const { return is_sdch_response_; } + virtual bool IsSdchResponse() const; // How many bytes were fed to filter(s) so far? - virtual int64 GetByteReadCount() const { return 0; } + virtual int64 GetByteReadCount() const; - virtual int GetResponseCode() const { return response_code_; } + virtual int GetResponseCode() const; // What is the desirable input buffer size for these filters? - virtual int GetInputStreamBufferSize() const { return buffer_size_; } + virtual int GetInputStreamBufferSize() const; virtual void RecordPacketStats(StatisticSelector statistic) const {} @@ -83,4 +70,6 @@ class MockFilterContext : public FilterContext { DISALLOW_COPY_AND_ASSIGN(MockFilterContext); }; -#endif // NET_BASE_FILTER_UNITTEST_H_ +} // namespace net + +#endif // NET_BASE_MOCK_FILTER_CONTEXT_H_ diff --git a/net/base/net_test_suite.cc b/net/base/net_test_suite.cc new file mode 100644 index 0000000..a37bc5b --- /dev/null +++ b/net/base/net_test_suite.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/base/net_test_suite.h" + +#include "base/message_loop.h" +#if defined(USE_NSS) +#include "net/ocsp/nss_ocsp.h" +#endif + +NetTestSuite::NetTestSuite(int argc, char** argv) + : TestSuite(argc, argv) { +} + +NetTestSuite::~NetTestSuite() {} + +void NetTestSuite::Initialize() { + TestSuite::Initialize(); + InitializeTestThread(); +} + +void NetTestSuite::Shutdown() { +#if defined(USE_NSS) + net::ShutdownOCSP(); +#endif + + // We want to destroy this here before the TestSuite continues to tear down + // the environment. + message_loop_.reset(); + + TestSuite::Shutdown(); +} + +void NetTestSuite::InitializeTestThread() { + network_change_notifier_.reset(net::NetworkChangeNotifier::CreateMock()); + + host_resolver_proc_ = new net::RuleBasedHostResolverProc(NULL); + scoped_host_resolver_proc_.Init(host_resolver_proc_.get()); + // In case any attempts are made to resolve host names, force them all to + // be mapped to localhost. This prevents DNS queries from being sent in + // the process of running these unit tests. + host_resolver_proc_->AddRule("*", "127.0.0.1"); + + message_loop_.reset(new MessageLoopForIO()); +} diff --git a/net/base/net_test_suite.h b/net/base/net_test_suite.h index 8ebc4e7..274d067 100644 --- a/net/base/net_test_suite.h +++ b/net/base/net_test_suite.h @@ -6,53 +6,33 @@ #define NET_BASE_NET_TEST_SUITE_H_ #pragma once -#include "base/message_loop.h" #include "base/ref_counted.h" #include "base/test/test_suite.h" #include "build/build_config.h" #include "net/base/mock_host_resolver.h" -#if defined(USE_NSS) -#include "net/ocsp/nss_ocsp.h" -#endif + +class MessageLoop; + +namespace net { +class NetworkChangeNotifier; +} class NetTestSuite : public base::TestSuite { public: - NetTestSuite(int argc, char** argv) : TestSuite(argc, argv) { - } + NetTestSuite(int argc, char** argv); + virtual ~NetTestSuite(); + + virtual void Initialize(); - virtual void Initialize() { - TestSuite::Initialize(); - InitializeTestThread(); - } + virtual void Shutdown(); + + protected: // Called from within Initialize(), but separate so that derived classes // can initialize the NetTestSuite instance only and not // TestSuite::Initialize(). TestSuite::Initialize() performs some global // initialization that can only be done once. - void InitializeTestThread() { - network_change_notifier_.reset(net::NetworkChangeNotifier::CreateMock()); - - host_resolver_proc_ = new net::RuleBasedHostResolverProc(NULL); - scoped_host_resolver_proc_.Init(host_resolver_proc_.get()); - // In case any attempts are made to resolve host names, force them all to - // be mapped to localhost. This prevents DNS queries from being sent in - // the process of running these unit tests. - host_resolver_proc_->AddRule("*", "127.0.0.1"); - - message_loop_.reset(new MessageLoopForIO()); - } - - virtual void Shutdown() { -#if defined(USE_NSS) - net::ShutdownOCSP(); -#endif - - // We want to destroy this here before the TestSuite continues to tear down - // the environment. - message_loop_.reset(); - - TestSuite::Shutdown(); - } + void InitializeTestThread(); private: scoped_ptr<net::NetworkChangeNotifier> network_change_notifier_; diff --git a/net/base/sdch_filter_unittest.cc b/net/base/sdch_filter_unittest.cc index 675a135..ccf07cb 100644 --- a/net/base/sdch_filter_unittest.cc +++ b/net/base/sdch_filter_unittest.cc @@ -17,8 +17,8 @@ #include "base/logging.h" #include "base/scoped_ptr.h" #include "net/base/filter.h" -#include "net/base/filter_unittest.h" #include "net/base/io_buffer.h" +#include "net/base/mock_filter_context.h" #include "net/base/sdch_filter.h" #include "net/url_request/url_request_http_job.h" #include "testing/gtest/include/gtest/gtest.h" @@ -158,7 +158,7 @@ TEST_F(SdchFilterTest, EmptyInputOk) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(30); char output_buffer[20]; - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); std::string url_string("http://ignore.com"); filter_context.SetURL(GURL(url_string)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -179,7 +179,7 @@ TEST_F(SdchFilterTest, PassThroughWhenTentative) { filter_types.push_back(Filter::FILTER_TYPE_GZIP_HELPING_SDCH); const int kInputBufferSize(30); char output_buffer[20]; - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); // Response code needs to be 200 to allow a pass through. filter_context.SetResponseCode(200); std::string url_string("http://ignore.com"); @@ -219,7 +219,7 @@ TEST_F(SdchFilterTest, RefreshBadReturnCode) { filter_types.push_back(Filter::FILTER_TYPE_SDCH_POSSIBLE); const int kInputBufferSize(30); char output_buffer[20]; - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); // Response code needs to be 200 to allow a pass through. filter_context.SetResponseCode(403); // Meta refresh will only appear for html content @@ -262,7 +262,7 @@ TEST_F(SdchFilterTest, ErrorOnBadReturnCode) { filter_types.push_back(Filter::FILTER_TYPE_SDCH_POSSIBLE); const int kInputBufferSize(30); char output_buffer[20]; - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); // Response code needs to be 200 to allow a pass through. filter_context.SetResponseCode(403); // Meta refresh will only appear for html content, so set to something else @@ -301,7 +301,7 @@ TEST_F(SdchFilterTest, ErrorOnBadReturnCodeWithHtml) { filter_types.push_back(Filter::FILTER_TYPE_SDCH_POSSIBLE); const int kInputBufferSize(30); char output_buffer[20]; - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); // Response code needs to be 200 to allow a pass through. filter_context.SetResponseCode(403); // Meta refresh will only appear for html content @@ -344,7 +344,7 @@ TEST_F(SdchFilterTest, BasicBadDictionary) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(30); char output_buffer[20]; - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); std::string url_string("http://ignore.com"); filter_context.SetURL(GURL(url_string)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -432,7 +432,7 @@ TEST_F(SdchFilterTest, BasicDictionary) { // Decode with a large buffer (larger than test input, or compressed data). const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(url); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -471,7 +471,7 @@ TEST_F(SdchFilterTest, NoDecodeHttps) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL("https://" + kSampleDomain)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -503,7 +503,7 @@ TEST_F(SdchFilterTest, NoDecodeFtp) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL("ftp://" + kSampleDomain)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -531,7 +531,7 @@ TEST_F(SdchFilterTest, NoDecodeFileColon) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL("file://" + kSampleDomain)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -559,7 +559,7 @@ TEST_F(SdchFilterTest, NoDecodeAboutColon) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL("about://" + kSampleDomain)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -587,7 +587,7 @@ TEST_F(SdchFilterTest, NoDecodeJavaScript) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL("javascript://" + kSampleDomain)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -615,7 +615,7 @@ TEST_F(SdchFilterTest, CanStillDecodeHttp) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL("http://" + kSampleDomain)); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -645,7 +645,7 @@ TEST_F(SdchFilterTest, CrossDomainDictionaryUse) { // Decode with content arriving from the "wrong" domain. // This tests SdchManager::CanSet(). - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); GURL wrong_domain_url("http://www.wrongdomain.com"); filter_context.SetURL(wrong_domain_url); scoped_ptr<Filter> filter((Filter::Factory(filter_types, filter_context))); @@ -686,7 +686,7 @@ TEST_F(SdchFilterTest, DictionaryPathValidation) { const int kInputBufferSize(100); // Test decode the path data, arriving from a valid path. - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL(url_string + path)); scoped_ptr<Filter> filter((Filter::Factory(filter_types, filter_context))); @@ -740,7 +740,7 @@ TEST_F(SdchFilterTest, DictionaryPortValidation) { const int kInputBufferSize(100); // Test decode the port data, arriving from a valid port. - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetURL(GURL(url_string + ":" + port)); scoped_ptr<Filter> filter((Filter::Factory(filter_types, filter_context))); @@ -863,7 +863,7 @@ TEST_F(SdchFilterTest, FilterChaining) { CHECK_GT(kLargeInputBufferSize, gzip_compressed_sdch.size()); CHECK_GT(kLargeInputBufferSize, sdch_compressed.size()); CHECK_GT(kLargeInputBufferSize, expanded_.size()); - MockFilterContext filter_context(kLargeInputBufferSize); + net::MockFilterContext filter_context(kLargeInputBufferSize); filter_context.SetURL(url); scoped_ptr<Filter> filter(Filter::Factory(filter_types, filter_context)); @@ -933,7 +933,7 @@ TEST_F(SdchFilterTest, DefaultGzipIfSdch) { filter_types.push_back(Filter::FILTER_TYPE_SDCH); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetMimeType("anything/mime"); filter_context.SetSdchResponse(true); Filter::FixupEncodingTypes(filter_context, &filter_types); @@ -993,7 +993,7 @@ TEST_F(SdchFilterTest, AcceptGzipSdchIfGzip) { filter_types.push_back(Filter::FILTER_TYPE_GZIP); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetMimeType("anything/mime"); filter_context.SetSdchResponse(true); Filter::FixupEncodingTypes(filter_context, &filter_types); @@ -1052,7 +1052,7 @@ TEST_F(SdchFilterTest, DefaultSdchGzipIfEmpty) { std::vector<Filter::FilterType> filter_types; const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetMimeType("anything/mime"); filter_context.SetSdchResponse(true); Filter::FixupEncodingTypes(filter_context, &filter_types); @@ -1115,7 +1115,7 @@ TEST_F(SdchFilterTest, AcceptGzipGzipSdchIfGzip) { filter_types.push_back(Filter::FILTER_TYPE_GZIP); const int kInputBufferSize(100); - MockFilterContext filter_context(kInputBufferSize); + net::MockFilterContext filter_context(kInputBufferSize); filter_context.SetMimeType("anything/mime"); filter_context.SetSdchResponse(true); Filter::FixupEncodingTypes(filter_context, &filter_types); diff --git a/net/http/http_auth_handler_factory_unittest.cc b/net/http/http_auth_handler_factory_unittest.cc index fb6e370..3145c4b 100644 --- a/net/http/http_auth_handler_factory_unittest.cc +++ b/net/http/http_auth_handler_factory_unittest.cc @@ -7,6 +7,7 @@ #include "net/base/net_errors.h" #include "net/http/http_auth_handler.h" #include "net/http/http_auth_handler_factory.h" +#include "net/http/mock_allow_url_security_manager.h" #include "net/http/url_security_manager.h" #include "testing/gtest/include/gtest/gtest.h" @@ -97,7 +98,7 @@ TEST(HttpAuthHandlerFactoryTest, RegistryFactory) { TEST(HttpAuthHandlerFactoryTest, DefaultFactory) { scoped_ptr<HostResolver> host_resolver(new MockHostResolver()); - URLSecurityManagerAllow url_security_manager; + MockAllowURLSecurityManager url_security_manager; scoped_ptr<HttpAuthHandlerRegistryFactory> http_auth_handler_factory( HttpAuthHandlerFactory::CreateDefault(host_resolver.get())); http_auth_handler_factory->SetURLSecurityManager( diff --git a/net/http/http_auth_handler_negotiate_unittest.cc b/net/http/http_auth_handler_negotiate_unittest.cc index 684ff55..bb57151 100644 --- a/net/http/http_auth_handler_negotiate_unittest.cc +++ b/net/http/http_auth_handler_negotiate_unittest.cc @@ -10,6 +10,7 @@ #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" #include "net/http/http_request_info.h" +#include "net/http/mock_allow_url_security_manager.h" #if defined(OS_WIN) #include "net/http/mock_sspi_library_win.h" #elif defined(OS_POSIX) @@ -36,7 +37,7 @@ class HttpAuthHandlerNegotiateTest : public PlatformTest { resolver_->rules()->AddIPLiteralRule("alias", "10.0.0.2", "canonical.example.com"); - url_security_manager_.reset(new URLSecurityManagerAllow()); + url_security_manager_.reset(new MockAllowURLSecurityManager()); factory_.reset(new HttpAuthHandlerNegotiate::Factory()); factory_->set_url_security_manager(url_security_manager_.get()); factory_->set_library(auth_library_); diff --git a/net/http/http_auth_unittest.cc b/net/http/http_auth_unittest.cc index f45d215..6788be2 100644 --- a/net/http/http_auth_unittest.cc +++ b/net/http/http_auth_unittest.cc @@ -17,6 +17,7 @@ #include "net/http/http_auth_handler_mock.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" +#include "net/http/mock_allow_url_security_manager.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -115,7 +116,7 @@ TEST(HttpAuthTest, ChooseBestChallenge) { }; GURL origin("http://www.example.com"); std::set<HttpAuth::Scheme> disabled_schemes; - URLSecurityManagerAllow url_security_manager; + MockAllowURLSecurityManager url_security_manager; scoped_ptr<HostResolver> host_resolver(new MockHostResolver()); scoped_ptr<HttpAuthHandlerRegistryFactory> http_auth_handler_factory( HttpAuthHandlerFactory::CreateDefault(host_resolver.get())); diff --git a/net/http/http_transaction_unittest.cc b/net/http/http_transaction_unittest.cc index 518c1f8..fabfb01 100644 --- a/net/http/http_transaction_unittest.cc +++ b/net/http/http_transaction_unittest.cc @@ -1,10 +1,11 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_transaction_unittest.h" -#include "base/hash_tables.h" +#include <algorithm> + #include "base/message_loop.h" #include "base/string_util.h" #include "net/base/net_errors.h" @@ -16,6 +17,11 @@ #include "net/http/http_transaction.h" #include "testing/gtest/include/gtest/gtest.h" +namespace { +typedef base::hash_map<std::string, const MockTransaction*> MockTransactionMap; +static MockTransactionMap mock_transactions; +} // namespace + //----------------------------------------------------------------------------- // mock transaction data @@ -104,18 +110,6 @@ static const MockTransaction* const kBuiltinMockTransactions[] = { &kRangeGET_Transaction }; -typedef base::hash_map<std::string, const MockTransaction*> -MockTransactionMap; -static MockTransactionMap mock_transactions; - -void AddMockTransaction(const MockTransaction* trans) { - mock_transactions[GURL(trans->url).spec()] = trans; -} - -void RemoveMockTransaction(const MockTransaction* trans) { - mock_transactions.erase(GURL(trans->url).spec()); -} - const MockTransaction* FindMockTransaction(const GURL& url) { // look for overrides: MockTransactionMap::const_iterator it = mock_transactions.find(url.spec()); @@ -130,12 +124,222 @@ const MockTransaction* FindMockTransaction(const GURL& url) { return NULL; } +void AddMockTransaction(const MockTransaction* trans) { + mock_transactions[GURL(trans->url).spec()] = trans; +} + +void RemoveMockTransaction(const MockTransaction* trans) { + mock_transactions.erase(GURL(trans->url).spec()); +} + +MockHttpRequest::MockHttpRequest(const MockTransaction& t) { + url = GURL(t.url); + method = t.method; + extra_headers.AddHeadersFromString(t.request_headers); + load_flags = t.load_flags; +} //----------------------------------------------------------------------------- // static int TestTransactionConsumer::quit_counter_ = 0; +TestTransactionConsumer::TestTransactionConsumer( + net::HttpTransactionFactory* factory) + : state_(IDLE), + trans_(NULL), + error_(net::OK) { + // Disregard the error code. + factory->CreateTransaction(&trans_); + ++quit_counter_; +} + +TestTransactionConsumer::~TestTransactionConsumer() { +} + +void TestTransactionConsumer::Start(const net::HttpRequestInfo* request, + const net::BoundNetLog& net_log) { + state_ = STARTING; + int result = trans_->Start(request, this, net_log); + if (result != net::ERR_IO_PENDING) + DidStart(result); +} + +void TestTransactionConsumer::DidStart(int result) { + if (result != net::OK) { + DidFinish(result); + } else { + Read(); + } +} + +void TestTransactionConsumer::DidRead(int result) { + if (result <= 0) { + DidFinish(result); + } else { + content_.append(read_buf_->data(), result); + Read(); + } +} + +void TestTransactionConsumer::DidFinish(int result) { + state_ = DONE; + error_ = result; + if (--quit_counter_ == 0) + MessageLoop::current()->Quit(); +} + +void TestTransactionConsumer::Read() { + state_ = READING; + read_buf_ = new net::IOBuffer(1024); + int result = trans_->Read(read_buf_, 1024, this); + if (result != net::ERR_IO_PENDING) + DidRead(result); +} + +void TestTransactionConsumer::RunWithParams(const Tuple1<int>& params) { + int result = params.a; + switch (state_) { + case STARTING: + DidStart(result); + break; + case READING: + DidRead(result); + break; + default: + NOTREACHED(); + } +} + + +MockNetworkTransaction::MockNetworkTransaction() : + ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), data_cursor_(0) { +} + +MockNetworkTransaction::~MockNetworkTransaction() {} + +int MockNetworkTransaction::Start(const net::HttpRequestInfo* request, + net::CompletionCallback* callback, + const net::BoundNetLog& net_log) { + const MockTransaction* t = FindMockTransaction(request->url); + if (!t) + return net::ERR_FAILED; + + std::string resp_status = t->status; + std::string resp_headers = t->response_headers; + std::string resp_data = t->data; + if (t->handler) + (t->handler)(request, &resp_status, &resp_headers, &resp_data); + + std::string header_data = base::StringPrintf( + "%s\n%s\n", resp_status.c_str(), resp_headers.c_str()); + std::replace(header_data.begin(), header_data.end(), '\n', '\0'); + + response_.request_time = base::Time::Now(); + if (!t->request_time.is_null()) + response_.request_time = t->request_time; + + response_.was_cached = false; + + response_.response_time = base::Time::Now(); + if (!t->response_time.is_null()) + response_.response_time = t->response_time; + + response_.headers = new net::HttpResponseHeaders(header_data); + response_.ssl_info.cert_status = t->cert_status; + data_ = resp_data; + test_mode_ = t->test_mode; + + if (test_mode_ & TEST_MODE_SYNC_NET_START) + return net::OK; + + CallbackLater(callback, net::OK); + return net::ERR_IO_PENDING; +} + +int MockNetworkTransaction::RestartIgnoringLastError( + net::CompletionCallback* callback) { + return net::ERR_FAILED; +} + +int MockNetworkTransaction::RestartWithCertificate( + net::X509Certificate* client_cert, + net::CompletionCallback* callback) { + return net::ERR_FAILED; +} + +int MockNetworkTransaction::RestartWithAuth(const string16& username, + const string16& password, + net::CompletionCallback* callback) { + return net::ERR_FAILED; +} + +bool MockNetworkTransaction::IsReadyToRestartForAuth() { + return false; +} + +int MockNetworkTransaction::Read(net::IOBuffer* buf, int buf_len, + net::CompletionCallback* callback) { + int data_len = static_cast<int>(data_.size()); + int num = std::min(buf_len, data_len - data_cursor_); + if (num) { + memcpy(buf->data(), data_.data() + data_cursor_, num); + data_cursor_ += num; + } + if (test_mode_ & TEST_MODE_SYNC_NET_READ) + return num; + + CallbackLater(callback, num); + return net::ERR_IO_PENDING; +} + +void MockNetworkTransaction::StopCaching() {} + +const net::HttpResponseInfo* MockNetworkTransaction::GetResponseInfo() const { + return &response_; +} + +net::LoadState MockNetworkTransaction::GetLoadState() const { + if (data_cursor_) + return net::LOAD_STATE_READING_RESPONSE; + return net::LOAD_STATE_IDLE; +} + +uint64 MockNetworkTransaction::GetUploadProgress() const { + return 0; +} + +void MockNetworkTransaction::CallbackLater(net::CompletionCallback* callback, + int result) { + MessageLoop::current()->PostTask(FROM_HERE, task_factory_.NewRunnableMethod( + &MockNetworkTransaction::RunCallback, callback, result)); +} + +void MockNetworkTransaction::RunCallback(net::CompletionCallback* callback, + int result) { + callback->Run(result); +} + +MockNetworkLayer::MockNetworkLayer() : transaction_count_(0) {} + +MockNetworkLayer::~MockNetworkLayer() {} + +int MockNetworkLayer::CreateTransaction( + scoped_ptr<net::HttpTransaction>* trans) { + transaction_count_++; + trans->reset(new MockNetworkTransaction()); + return net::OK; +} + +net::HttpCache* MockNetworkLayer::GetCache() { + return NULL; +} + +net::HttpNetworkSession* MockNetworkLayer::GetSession() { + return NULL; +} + +void MockNetworkLayer::Suspend(bool suspend) {} //----------------------------------------------------------------------------- // helpers diff --git a/net/http/http_transaction_unittest.h b/net/http/http_transaction_unittest.h index 3149534..0a11bb5 100644 --- a/net/http/http_transaction_unittest.h +++ b/net/http/http_transaction_unittest.h @@ -8,15 +8,11 @@ #include "net/http/http_transaction.h" -#include <algorithm> #include <string> #include "base/callback.h" #include "base/compiler_specific.h" -#include "base/message_loop.h" #include "base/string16.h" -#include "base/string_util.h" -#include "base/stringprintf.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" @@ -27,6 +23,10 @@ #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" +namespace net { +class IOBuffer; +} + //----------------------------------------------------------------------------- // mock transaction data @@ -97,12 +97,7 @@ struct ScopedMockTransaction : MockTransaction { class MockHttpRequest : public net::HttpRequestInfo { public: - explicit MockHttpRequest(const MockTransaction& t) { - url = GURL(t.url); - method = t.method; - extra_headers.AddHeadersFromString(t.request_headers); - load_flags = t.load_flags; - } + explicit MockHttpRequest(const MockTransaction& t); }; //----------------------------------------------------------------------------- @@ -110,25 +105,11 @@ class MockHttpRequest : public net::HttpRequestInfo { class TestTransactionConsumer : public CallbackRunner< Tuple1<int> > { public: - explicit TestTransactionConsumer(net::HttpTransactionFactory* factory) - : state_(IDLE), - trans_(NULL), - error_(net::OK) { - // Disregard the error code. - factory->CreateTransaction(&trans_); - ++quit_counter_; - } - - ~TestTransactionConsumer() { - } + explicit TestTransactionConsumer(net::HttpTransactionFactory* factory); + virtual ~TestTransactionConsumer(); void Start(const net::HttpRequestInfo* request, - const net::BoundNetLog& net_log) { - state_ = STARTING; - int result = trans_->Start(request, this, net_log); - if (result != net::ERR_IO_PENDING) - DidStart(result); - } + const net::BoundNetLog& net_log); bool is_done() const { return state_ == DONE; } int error() const { return error_; } @@ -139,60 +120,22 @@ class TestTransactionConsumer : public CallbackRunner< Tuple1<int> > { const std::string& content() const { return content_; } private: - // Callback implementation: - virtual void RunWithParams(const Tuple1<int>& params) { - int result = params.a; - switch (state_) { - case STARTING: - DidStart(result); - break; - case READING: - DidRead(result); - break; - default: - NOTREACHED(); - } - } - - void DidStart(int result) { - if (result != net::OK) { - DidFinish(result); - } else { - Read(); - } - } - - void DidRead(int result) { - if (result <= 0) { - DidFinish(result); - } else { - content_.append(read_buf_->data(), result); - Read(); - } - } - - void DidFinish(int result) { - state_ = DONE; - error_ = result; - if (--quit_counter_ == 0) - MessageLoop::current()->Quit(); - } - - void Read() { - state_ = READING; - read_buf_ = new net::IOBuffer(1024); - int result = trans_->Read(read_buf_, 1024, this); - if (result != net::ERR_IO_PENDING) - DidRead(result); - } - enum State { IDLE, STARTING, READING, DONE - } state_; + }; + + void DidStart(int result); + void DidRead(int result); + void DidFinish(int result); + void Read(); + + // Callback implementation: + virtual void RunWithParams(const Tuple1<int>& params); + State state_; scoped_ptr<net::HttpTransaction> trans_; std::string content_; scoped_refptr<net::IOBuffer> read_buf_; @@ -210,107 +153,38 @@ class TestTransactionConsumer : public CallbackRunner< Tuple1<int> > { // HttpCache implementation. class MockNetworkTransaction : public net::HttpTransaction { public: - MockNetworkTransaction() : - ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), data_cursor_(0) { - } + MockNetworkTransaction(); + virtual ~MockNetworkTransaction(); virtual int Start(const net::HttpRequestInfo* request, net::CompletionCallback* callback, - const net::BoundNetLog& net_log) { - const MockTransaction* t = FindMockTransaction(request->url); - if (!t) - return net::ERR_FAILED; - - std::string resp_status = t->status; - std::string resp_headers = t->response_headers; - std::string resp_data = t->data; - if (t->handler) - (t->handler)(request, &resp_status, &resp_headers, &resp_data); - - std::string header_data = base::StringPrintf( - "%s\n%s\n", resp_status.c_str(), resp_headers.c_str()); - std::replace(header_data.begin(), header_data.end(), '\n', '\0'); - - response_.request_time = base::Time::Now(); - if (!t->request_time.is_null()) - response_.request_time = t->request_time; - - response_.was_cached = false; + const net::BoundNetLog& net_log); - response_.response_time = base::Time::Now(); - if (!t->response_time.is_null()) - response_.response_time = t->response_time; - - response_.headers = new net::HttpResponseHeaders(header_data); - response_.ssl_info.cert_status = t->cert_status; - data_ = resp_data; - test_mode_ = t->test_mode; - - if (test_mode_ & TEST_MODE_SYNC_NET_START) - return net::OK; - - CallbackLater(callback, net::OK); - return net::ERR_IO_PENDING; - } - - virtual int RestartIgnoringLastError(net::CompletionCallback* callback) { - return net::ERR_FAILED; - } + virtual int RestartIgnoringLastError(net::CompletionCallback* callback); virtual int RestartWithCertificate(net::X509Certificate* client_cert, - net::CompletionCallback* callback) { - return net::ERR_FAILED; - } + net::CompletionCallback* callback); virtual int RestartWithAuth(const string16& username, const string16& password, - net::CompletionCallback* callback) { - return net::ERR_FAILED; - } + net::CompletionCallback* callback); - virtual bool IsReadyToRestartForAuth() { - return false; - } + virtual bool IsReadyToRestartForAuth(); virtual int Read(net::IOBuffer* buf, int buf_len, - net::CompletionCallback* callback) { - int data_len = static_cast<int>(data_.size()); - int num = std::min(buf_len, data_len - data_cursor_); - if (num) { - memcpy(buf->data(), data_.data() + data_cursor_, num); - data_cursor_ += num; - } - if (test_mode_ & TEST_MODE_SYNC_NET_READ) - return num; - - CallbackLater(callback, num); - return net::ERR_IO_PENDING; - } + net::CompletionCallback* callback); - virtual void StopCaching() {} + virtual void StopCaching(); - virtual const net::HttpResponseInfo* GetResponseInfo() const { - return &response_; - } + virtual const net::HttpResponseInfo* GetResponseInfo() const; - virtual net::LoadState GetLoadState() const { - if (data_cursor_) - return net::LOAD_STATE_READING_RESPONSE; - return net::LOAD_STATE_IDLE; - } + virtual net::LoadState GetLoadState() const; - virtual uint64 GetUploadProgress() const { - return 0; - } + virtual uint64 GetUploadProgress() const; private: - void CallbackLater(net::CompletionCallback* callback, int result) { - MessageLoop::current()->PostTask(FROM_HERE, task_factory_.NewRunnableMethod( - &MockNetworkTransaction::RunCallback, callback, result)); - } - void RunCallback(net::CompletionCallback* callback, int result) { - callback->Run(result); - } + void CallbackLater(net::CompletionCallback* callback, int result); + void RunCallback(net::CompletionCallback* callback, int result); ScopedRunnableMethodFactory<MockNetworkTransaction> task_factory_; net::HttpResponseInfo response_; @@ -321,32 +195,21 @@ class MockNetworkTransaction : public net::HttpTransaction { class MockNetworkLayer : public net::HttpTransactionFactory { public: - MockNetworkLayer() : transaction_count_(0) { - } - - virtual int CreateTransaction(scoped_ptr<net::HttpTransaction>* trans) { - transaction_count_++; - trans->reset(new MockNetworkTransaction()); - return net::OK; - } - - virtual net::HttpCache* GetCache() { - return NULL; - } - - virtual net::HttpNetworkSession* GetSession() { - return NULL; - } - - virtual void Suspend(bool suspend) {} + MockNetworkLayer(); + virtual ~MockNetworkLayer(); int transaction_count() const { return transaction_count_; } + // net::HttpTransactionFactory: + virtual int CreateTransaction(scoped_ptr<net::HttpTransaction>* trans); + virtual net::HttpCache* GetCache(); + virtual net::HttpNetworkSession* GetSession(); + virtual void Suspend(bool suspend); + private: int transaction_count_; }; - //----------------------------------------------------------------------------- // helpers diff --git a/net/http/mock_allow_url_security_manager.cc b/net/http/mock_allow_url_security_manager.cc new file mode 100644 index 0000000..e8b2c4f --- /dev/null +++ b/net/http/mock_allow_url_security_manager.cc @@ -0,0 +1,22 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/http/mock_allow_url_security_manager.h" + +namespace net { + +MockAllowURLSecurityManager::MockAllowURLSecurityManager() {} + +MockAllowURLSecurityManager::~MockAllowURLSecurityManager() {} + +bool MockAllowURLSecurityManager::CanUseDefaultCredentials( + const GURL& auth_origin) const { + return true; +} + +bool MockAllowURLSecurityManager::CanDelegate(const GURL& auth_origin) const { + return true; +} + +} // namespace net diff --git a/net/http/mock_allow_url_security_manager.h b/net/http/mock_allow_url_security_manager.h new file mode 100644 index 0000000..32f572e --- /dev/null +++ b/net/http/mock_allow_url_security_manager.h @@ -0,0 +1,29 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_HTTP_MOCK_ALLOW_URL_SECURITY_MANAGER_H_ +#define NET_HTTP_MOCK_ALLOW_URL_SECURITY_MANAGER_H_ +#pragma once + +#include "net/http/url_security_manager.h" + +namespace net { + +// An URLSecurityManager which is very permissive and which should only be used +// in unit testing. +class MockAllowURLSecurityManager : public URLSecurityManager { + public: + MockAllowURLSecurityManager(); + virtual ~MockAllowURLSecurityManager(); + + virtual bool CanUseDefaultCredentials(const GURL& auth_origin) const; + virtual bool CanDelegate(const GURL& auth_origin) const; + + private: + DISALLOW_COPY_AND_ASSIGN(MockAllowURLSecurityManager); +}; + +} // namespace net + +#endif // NET_HTTP_MOCK_ALLOW_URL_SECURITY_MANAGER_H_ diff --git a/net/http/url_security_manager.h b/net/http/url_security_manager.h index c6a5ec9..119d6bd 100644 --- a/net/http/url_security_manager.h +++ b/net/http/url_security_manager.h @@ -74,25 +74,6 @@ class URLSecurityManagerWhitelist : public URLSecurityManager { DISALLOW_COPY_AND_ASSIGN(URLSecurityManagerWhitelist); }; -#if defined(UNIT_TEST) -// An URLSecurityManager which is very permissive. -class URLSecurityManagerAllow : public URLSecurityManager { - public: - URLSecurityManagerAllow() {} - virtual ~URLSecurityManagerAllow() {} - - virtual bool CanUseDefaultCredentials(const GURL& auth_origin) const { - return true; - } - virtual bool CanDelegate(const GURL& auth_origin) const { - return true; - } - - private: - DISALLOW_COPY_AND_ASSIGN(URLSecurityManagerAllow); -}; -#endif // defined(UNIT_TEST) - } // namespace net #endif // NET_HTTP_URL_SECURITY_MANAGER_H_ diff --git a/net/net.gyp b/net/net.gyp index 1ab1371..240b270b 100644 --- a/net/net.gyp +++ b/net/net.gyp @@ -866,7 +866,6 @@ 'base/escape_unittest.cc', 'base/file_stream_unittest.cc', 'base/filter_unittest.cc', - 'base/filter_unittest.h', 'base/gzip_filter_unittest.cc', 'base/host_cache_unittest.cc', 'base/host_mapping_rules_unittest.cc', @@ -878,9 +877,10 @@ 'base/mapped_host_resolver_unittest.cc', 'base/mime_sniffer_unittest.cc', 'base/mime_util_unittest.cc', + 'base/mock_filter_context.cc', + 'base/mock_filter_context.h', 'base/net_log_unittest.cc', 'base/net_log_unittest.h', - 'base/net_test_suite.h', 'base/net_util_unittest.cc', 'base/pem_tokenizer_unittest.cc', 'base/registry_controlled_domain_unittest.cc', @@ -947,6 +947,8 @@ 'http/http_transaction_unittest.h', 'http/http_util_unittest.cc', 'http/http_vary_data_unittest.cc', + 'http/mock_allow_url_security_manager.cc', + 'http/mock_allow_url_security_manager.h', 'http/mock_gssapi_library_posix.cc', 'http/mock_gssapi_library_posix.h', 'http/mock_sspi_library_win.h', @@ -997,7 +999,6 @@ 'url_request/url_request_job_tracker_unittest.cc', 'url_request/url_request_throttler_unittest.cc', 'url_request/url_request_unittest.cc', - 'url_request/url_request_unittest.h', 'url_request/view_cache_helper_unittest.cc', 'websockets/websocket_frame_handler_unittest.cc', 'websockets/websocket_handshake_draft75_unittest.cc', @@ -1158,6 +1159,10 @@ 'sources': [ 'base/cert_test_util.cc', 'base/cert_test_util.h', + 'base/cookie_monster_store_test.cc', + 'base/cookie_monster_store_test.h', + 'base/net_test_suite.cc', + 'base/net_test_suite.h', 'base/test_completion_callback.cc', 'base/test_completion_callback.h', 'disk_cache/disk_cache_test_util.cc', @@ -1172,6 +1177,8 @@ 'test/test_server_posix.cc', 'test/test_server_win.cc', 'test/test_server.h', + 'url_request/url_request_test_util.cc', + 'url_request/url_request_test_util.h', ], 'conditions': [ ['inside_chromium_build==1', { diff --git a/net/proxy/proxy_script_fetcher_impl_unittest.cc b/net/proxy/proxy_script_fetcher_impl_unittest.cc index 3e068a6..4a96071 100644 --- a/net/proxy/proxy_script_fetcher_impl_unittest.cc +++ b/net/proxy/proxy_script_fetcher_impl_unittest.cc @@ -15,7 +15,7 @@ #include "net/base/test_completion_callback.h" #include "net/disk_cache/disk_cache.h" #include "net/http/http_cache.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" diff --git a/net/socket_stream/socket_stream_unittest.cc b/net/socket_stream/socket_stream_unittest.cc index 832b0ab..24a0ff0 100644 --- a/net/socket_stream/socket_stream_unittest.cc +++ b/net/socket_stream/socket_stream_unittest.cc @@ -14,7 +14,7 @@ #include "net/base/test_completion_callback.h" #include "net/socket/socket_test_util.h" #include "net/socket_stream/socket_stream.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" diff --git a/net/spdy/spdy_network_transaction_unittest.cc b/net/spdy/spdy_network_transaction_unittest.cc index e6413429..f7ee96c 100644 --- a/net/spdy/spdy_network_transaction_unittest.cc +++ b/net/spdy/spdy_network_transaction_unittest.cc @@ -13,7 +13,7 @@ #include "net/spdy/spdy_session.h" #include "net/spdy/spdy_session_pool.h" #include "net/spdy/spdy_test_util.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/platform_test.h" //----------------------------------------------------------------------------- diff --git a/net/url_request/url_request_job_tracker_unittest.cc b/net/url_request/url_request_job_tracker_unittest.cc index 11a5e3b..df6448b 100644 --- a/net/url_request/url_request_job_tracker_unittest.cc +++ b/net/url_request/url_request_job_tracker_unittest.cc @@ -14,7 +14,7 @@ #include "net/url_request/url_request_job.h" #include "net/url_request/url_request_job_tracker.h" #include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" diff --git a/net/url_request/url_request_test_util.cc b/net/url_request/url_request_test_util.cc new file mode 100644 index 0000000..099810a --- /dev/null +++ b/net/url_request/url_request_test_util.cc @@ -0,0 +1,281 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/url_request/url_request_test_util.h" + +#include "base/logging.h" +#include "base/message_loop.h" +#include "base/threading/thread.h" + +TestCookiePolicy::TestCookiePolicy(int options_bit_mask) + : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), + options_(options_bit_mask), + callback_(NULL) { +} + +TestCookiePolicy::~TestCookiePolicy() {} + +int TestCookiePolicy::CanGetCookies(const GURL& url, + const GURL& first_party, + net::CompletionCallback* callback) { + if ((options_ & ASYNC) && callback) { + callback_ = callback; + MessageLoop::current()->PostTask(FROM_HERE, + method_factory_.NewRunnableMethod( + &TestCookiePolicy::DoGetCookiesPolicy, url, first_party)); + return net::ERR_IO_PENDING; + } + + if (options_ & NO_GET_COOKIES) + return net::ERR_ACCESS_DENIED; + + return net::OK; +} + +int TestCookiePolicy::CanSetCookie(const GURL& url, + const GURL& first_party, + const std::string& cookie_line, + net::CompletionCallback* callback) { + if ((options_ & ASYNC) && callback) { + callback_ = callback; + MessageLoop::current()->PostTask(FROM_HERE, + method_factory_.NewRunnableMethod( + &TestCookiePolicy::DoSetCookiePolicy, url, first_party, + cookie_line)); + return net::ERR_IO_PENDING; + } + + if (options_ & NO_SET_COOKIE) + return net::ERR_ACCESS_DENIED; + + if (options_ & FORCE_SESSION) + return net::OK_FOR_SESSION_ONLY; + + return net::OK; +} + +void TestCookiePolicy::DoGetCookiesPolicy(const GURL& url, + const GURL& first_party) { + int policy = CanGetCookies(url, first_party, NULL); + + DCHECK(callback_); + net::CompletionCallback* callback = callback_; + callback_ = NULL; + callback->Run(policy); +} + +void TestCookiePolicy::DoSetCookiePolicy(const GURL& url, + const GURL& first_party, + const std::string& cookie_line) { + int policy = CanSetCookie(url, first_party, cookie_line, NULL); + + DCHECK(callback_); + net::CompletionCallback* callback = callback_; + callback_ = NULL; + callback->Run(policy); +} + + +TestURLRequestContext::TestURLRequestContext() { + host_resolver_ = + net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, + NULL, NULL); + proxy_service_ = net::ProxyService::CreateDirect(); + Init(); +} + +TestURLRequestContext::TestURLRequestContext(const std::string& proxy) { + host_resolver_ = + net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, + NULL, NULL); + net::ProxyConfig proxy_config; + proxy_config.proxy_rules().ParseFromString(proxy); + proxy_service_ = net::ProxyService::CreateFixed(proxy_config); + Init(); +} + +TestURLRequestContext::~TestURLRequestContext() { + delete ftp_transaction_factory_; + delete http_transaction_factory_; + delete http_auth_handler_factory_; + delete cert_verifier_; + delete host_resolver_; +} + +void TestURLRequestContext::Init() { + cert_verifier_ = new net::CertVerifier; + ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); + ssl_config_service_ = new net::SSLConfigServiceDefaults; + http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault( + host_resolver_); + http_transaction_factory_ = new net::HttpCache( + net::HttpNetworkLayer::CreateFactory(host_resolver_, + cert_verifier_, + NULL /* dnsrr_resolver */, + NULL /* dns_cert_checker */, + NULL /* ssl_host_info_factory */, + proxy_service_, + ssl_config_service_, + http_auth_handler_factory_, + network_delegate_, + NULL), + NULL /* net_log */, + net::HttpCache::DefaultBackend::InMemory(0)); + // In-memory cookie store. + cookie_store_ = new net::CookieMonster(NULL, NULL); + accept_language_ = "en-us,fr"; + accept_charset_ = "iso-8859-1,*,utf-8"; +} + + +TestURLRequest::TestURLRequest(const GURL& url, Delegate* delegate) + : net::URLRequest(url, delegate) { + set_context(new TestURLRequestContext()); +} + +TestURLRequest::~TestURLRequest() {} + +TestDelegate::TestDelegate() + : cancel_in_rr_(false), + cancel_in_rs_(false), + cancel_in_rd_(false), + cancel_in_rd_pending_(false), + cancel_in_getcookiesblocked_(false), + cancel_in_setcookieblocked_(false), + quit_on_complete_(true), + quit_on_redirect_(false), + allow_certificate_errors_(false), + response_started_count_(0), + received_bytes_count_(0), + received_redirect_count_(0), + blocked_get_cookies_count_(0), + blocked_set_cookie_count_(0), + set_cookie_count_(0), + received_data_before_response_(false), + request_failed_(false), + have_certificate_errors_(false), + buf_(new net::IOBuffer(kBufferSize)) { +} + +TestDelegate::~TestDelegate() {} + +void TestDelegate::OnReceivedRedirect(net::URLRequest* request, + const GURL& new_url, + bool* defer_redirect) { + received_redirect_count_++; + if (quit_on_redirect_) { + *defer_redirect = true; + MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); + } else if (cancel_in_rr_) { + request->Cancel(); + } +} + +void TestDelegate::OnAuthRequired(net::URLRequest* request, + net::AuthChallengeInfo* auth_info) { + if (!username_.empty() || !password_.empty()) { + request->SetAuth(username_, password_); + } else { + request->CancelAuth(); + } +} + +void TestDelegate::OnSSLCertificateError(net::URLRequest* request, + int cert_error, + net::X509Certificate* cert) { + // The caller can control whether it needs all SSL requests to go through, + // independent of any possible errors, or whether it wants SSL errors to + // cancel the request. + have_certificate_errors_ = true; + if (allow_certificate_errors_) + request->ContinueDespiteLastError(); + else + request->Cancel(); +} + +void TestDelegate::OnGetCookies(net::URLRequest* request, + bool blocked_by_policy) { + if (blocked_by_policy) { + blocked_get_cookies_count_++; + if (cancel_in_getcookiesblocked_) + request->Cancel(); + } +} + +void TestDelegate::OnSetCookie(net::URLRequest* request, + const std::string& cookie_line, + const net::CookieOptions& options, + bool blocked_by_policy) { + if (blocked_by_policy) { + blocked_set_cookie_count_++; + if (cancel_in_setcookieblocked_) + request->Cancel(); + } else { + set_cookie_count_++; + } +} + +void TestDelegate::OnResponseStarted(net::URLRequest* request) { + // It doesn't make sense for the request to have IO pending at this point. + DCHECK(!request->status().is_io_pending()); + + response_started_count_++; + if (cancel_in_rs_) { + request->Cancel(); + OnResponseCompleted(request); + } else if (!request->status().is_success()) { + DCHECK(request->status().status() == net::URLRequestStatus::FAILED || + request->status().status() == net::URLRequestStatus::CANCELED); + request_failed_ = true; + OnResponseCompleted(request); + } else { + // Initiate the first read. + int bytes_read = 0; + if (request->Read(buf_, kBufferSize, &bytes_read)) + OnReadCompleted(request, bytes_read); + else if (!request->status().is_io_pending()) + OnResponseCompleted(request); + } +} + +void TestDelegate::OnReadCompleted(net::URLRequest* request, int bytes_read) { + // It doesn't make sense for the request to have IO pending at this point. + DCHECK(!request->status().is_io_pending()); + + if (response_started_count_ == 0) + received_data_before_response_ = true; + + if (cancel_in_rd_) + request->Cancel(); + + if (bytes_read >= 0) { + // There is data to read. + received_bytes_count_ += bytes_read; + + // consume the data + data_received_.append(buf_->data(), bytes_read); + } + + // If it was not end of stream, request to read more. + if (request->status().is_success() && bytes_read > 0) { + bytes_read = 0; + while (request->Read(buf_, kBufferSize, &bytes_read)) { + if (bytes_read > 0) { + data_received_.append(buf_->data(), bytes_read); + received_bytes_count_ += bytes_read; + } else { + break; + } + } + } + if (!request->status().is_io_pending()) + OnResponseCompleted(request); + else if (cancel_in_rd_pending_) + request->Cancel(); +} + +void TestDelegate::OnResponseCompleted(net::URLRequest* request) { + if (quit_on_complete_) + MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); +} diff --git a/net/url_request/url_request_test_util.h b/net/url_request/url_request_test_util.h new file mode 100644 index 0000000..ab71db1 --- /dev/null +++ b/net/url_request/url_request_test_util.h @@ -0,0 +1,190 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ +#define NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ +#pragma once + +#include <stdlib.h> + +#include <sstream> +#include <string> + +#include "base/path_service.h" +#include "base/process_util.h" +#include "base/string_util.h" +#include "base/string16.h" +#include "base/time.h" +#include "base/utf_string_conversions.h" +#include "net/base/cert_verifier.h" +#include "net/base/cookie_monster.h" +#include "net/base/cookie_policy.h" +#include "net/base/host_resolver.h" +#include "net/base/io_buffer.h" +#include "net/base/net_errors.h" +#include "net/base/ssl_config_service_defaults.h" +#include "net/disk_cache/disk_cache.h" +#include "net/ftp/ftp_network_layer.h" +#include "net/http/http_auth_handler_factory.h" +#include "net/http/http_cache.h" +#include "net/http/http_network_layer.h" +#include "net/test/test_server.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" +#include "net/proxy/proxy_service.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "googleurl/src/url_util.h" + +using base::TimeDelta; + +//----------------------------------------------------------------------------- + +class TestCookiePolicy : public net::CookiePolicy { + public: + enum Options { + NO_GET_COOKIES = 1 << 0, + NO_SET_COOKIE = 1 << 1, + ASYNC = 1 << 2, + FORCE_SESSION = 1 << 3, + }; + + explicit TestCookiePolicy(int options_bit_mask); + virtual ~TestCookiePolicy(); + + // net::CookiePolicy: + virtual int CanGetCookies(const GURL& url, const GURL& first_party, + net::CompletionCallback* callback); + virtual int CanSetCookie(const GURL& url, const GURL& first_party, + const std::string& cookie_line, + net::CompletionCallback* callback); + + private: + void DoGetCookiesPolicy(const GURL& url, const GURL& first_party); + void DoSetCookiePolicy(const GURL& url, const GURL& first_party, + const std::string& cookie_line); + + ScopedRunnableMethodFactory<TestCookiePolicy> method_factory_; + int options_; + net::CompletionCallback* callback_; +}; + +//----------------------------------------------------------------------------- + +class TestURLRequestContext : public net::URLRequestContext { + public: + TestURLRequestContext(); + explicit TestURLRequestContext(const std::string& proxy); + + void set_cookie_policy(net::CookiePolicy* policy) { + cookie_policy_ = policy; + } + + protected: + virtual ~TestURLRequestContext(); + + private: + void Init(); +}; + +//----------------------------------------------------------------------------- + +class TestURLRequest : public net::URLRequest { + public: + TestURLRequest(const GURL& url, Delegate* delegate); + virtual ~TestURLRequest(); +}; + +//----------------------------------------------------------------------------- + +class TestDelegate : public net::URLRequest::Delegate { + public: + TestDelegate(); + virtual ~TestDelegate(); + + void set_cancel_in_received_redirect(bool val) { cancel_in_rr_ = val; } + void set_cancel_in_response_started(bool val) { cancel_in_rs_ = val; } + void set_cancel_in_received_data(bool val) { cancel_in_rd_ = val; } + void set_cancel_in_received_data_pending(bool val) { + cancel_in_rd_pending_ = val; + } + void set_cancel_in_get_cookies_blocked(bool val) { + cancel_in_getcookiesblocked_ = val; + } + void set_cancel_in_set_cookie_blocked(bool val) { + cancel_in_setcookieblocked_ = val; + } + void set_quit_on_complete(bool val) { quit_on_complete_ = val; } + void set_quit_on_redirect(bool val) { quit_on_redirect_ = val; } + void set_allow_certificate_errors(bool val) { + allow_certificate_errors_ = val; + } + void set_username(const string16& u) { username_ = u; } + void set_password(const string16& p) { password_ = p; } + + // query state + const std::string& data_received() const { return data_received_; } + int bytes_received() const { return static_cast<int>(data_received_.size()); } + int response_started_count() const { return response_started_count_; } + int received_redirect_count() const { return received_redirect_count_; } + int blocked_get_cookies_count() const { return blocked_get_cookies_count_; } + int blocked_set_cookie_count() const { return blocked_set_cookie_count_; } + int set_cookie_count() const { return set_cookie_count_; } + bool received_data_before_response() const { + return received_data_before_response_; + } + bool request_failed() const { return request_failed_; } + bool have_certificate_errors() const { return have_certificate_errors_; } + + // net::URLRequest::Delegate: + virtual void OnReceivedRedirect(net::URLRequest* request, const GURL& new_url, + bool* defer_redirect); + virtual void OnAuthRequired(net::URLRequest* request, + net::AuthChallengeInfo* auth_info); + virtual void OnSSLCertificateError(net::URLRequest* request, + int cert_error, + net::X509Certificate* cert); + virtual void OnGetCookies(net::URLRequest* request, bool blocked_by_policy); + virtual void OnSetCookie(net::URLRequest* request, + const std::string& cookie_line, + const net::CookieOptions& options, + bool blocked_by_policy); + virtual void OnResponseStarted(net::URLRequest* request); + virtual void OnReadCompleted(net::URLRequest* request, int bytes_read); + + private: + static const int kBufferSize = 4096; + + virtual void OnResponseCompleted(net::URLRequest* request); + + // options for controlling behavior + bool cancel_in_rr_; + bool cancel_in_rs_; + bool cancel_in_rd_; + bool cancel_in_rd_pending_; + bool cancel_in_getcookiesblocked_; + bool cancel_in_setcookieblocked_; + bool quit_on_complete_; + bool quit_on_redirect_; + bool allow_certificate_errors_; + + string16 username_; + string16 password_; + + // tracks status of callbacks + int response_started_count_; + int received_bytes_count_; + int received_redirect_count_; + int blocked_get_cookies_count_; + int blocked_set_cookie_count_; + int set_cookie_count_; + bool received_data_before_response_; + bool request_failed_; + bool have_certificate_errors_; + std::string data_received_; + + // our read buffer + scoped_refptr<net::IOBuffer> buf_; +}; + +#endif // NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index ce02eed..93daab0 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "net/url_request/url_request_unittest.h" - #include "build/build_config.h" #if defined(OS_WIN) @@ -48,6 +46,7 @@ #include "net/url_request/url_request_file_dir_job.h" #include "net/url_request/url_request_http_job.h" #include "net/url_request/url_request_test_job.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" diff --git a/net/url_request/url_request_unittest.h b/net/url_request/url_request_unittest.h deleted file mode 100644 index 030b59b..0000000 --- a/net/url_request/url_request_unittest.h +++ /dev/null @@ -1,405 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef NET_URL_REQUEST_URL_REQUEST_UNITTEST_H_ -#define NET_URL_REQUEST_URL_REQUEST_UNITTEST_H_ -#pragma once - -#include <stdlib.h> - -#include <sstream> -#include <string> - -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/path_service.h" -#include "base/process_util.h" -#include "base/string_util.h" -#include "base/string16.h" -#include "base/threading/thread.h" -#include "base/time.h" -#include "base/utf_string_conversions.h" -#include "net/base/cert_verifier.h" -#include "net/base/cookie_monster.h" -#include "net/base/cookie_policy.h" -#include "net/base/host_resolver.h" -#include "net/base/io_buffer.h" -#include "net/base/net_errors.h" -#include "net/base/ssl_config_service_defaults.h" -#include "net/disk_cache/disk_cache.h" -#include "net/ftp/ftp_network_layer.h" -#include "net/http/http_auth_handler_factory.h" -#include "net/http/http_cache.h" -#include "net/http/http_network_layer.h" -#include "net/test/test_server.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_context.h" -#include "net/proxy/proxy_service.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "googleurl/src/url_util.h" - -using base::TimeDelta; - -//----------------------------------------------------------------------------- - -class TestCookiePolicy : public net::CookiePolicy { - public: - enum Options { - NO_GET_COOKIES = 1 << 0, - NO_SET_COOKIE = 1 << 1, - ASYNC = 1 << 2, - FORCE_SESSION = 1 << 3, - }; - - explicit TestCookiePolicy(int options_bit_mask) - : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), - options_(options_bit_mask), - callback_(NULL) { - } - - virtual int CanGetCookies(const GURL& url, const GURL& first_party, - net::CompletionCallback* callback) { - if ((options_ & ASYNC) && callback) { - callback_ = callback; - MessageLoop::current()->PostTask(FROM_HERE, - method_factory_.NewRunnableMethod( - &TestCookiePolicy::DoGetCookiesPolicy, url, first_party)); - return net::ERR_IO_PENDING; - } - - if (options_ & NO_GET_COOKIES) - return net::ERR_ACCESS_DENIED; - - return net::OK; - } - - virtual int CanSetCookie(const GURL& url, const GURL& first_party, - const std::string& cookie_line, - net::CompletionCallback* callback) { - if ((options_ & ASYNC) && callback) { - callback_ = callback; - MessageLoop::current()->PostTask(FROM_HERE, - method_factory_.NewRunnableMethod( - &TestCookiePolicy::DoSetCookiePolicy, url, first_party, - cookie_line)); - return net::ERR_IO_PENDING; - } - - if (options_ & NO_SET_COOKIE) - return net::ERR_ACCESS_DENIED; - - if (options_ & FORCE_SESSION) - return net::OK_FOR_SESSION_ONLY; - - return net::OK; - } - - private: - void DoGetCookiesPolicy(const GURL& url, const GURL& first_party) { - int policy = CanGetCookies(url, first_party, NULL); - - DCHECK(callback_); - net::CompletionCallback* callback = callback_; - callback_ = NULL; - callback->Run(policy); - } - - void DoSetCookiePolicy(const GURL& url, const GURL& first_party, - const std::string& cookie_line) { - int policy = CanSetCookie(url, first_party, cookie_line, NULL); - - DCHECK(callback_); - net::CompletionCallback* callback = callback_; - callback_ = NULL; - callback->Run(policy); - } - - ScopedRunnableMethodFactory<TestCookiePolicy> method_factory_; - int options_; - net::CompletionCallback* callback_; -}; - -//----------------------------------------------------------------------------- - -class TestURLRequestContext : public net::URLRequestContext { - public: - TestURLRequestContext() { - host_resolver_ = - net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, - NULL, NULL); - proxy_service_ = net::ProxyService::CreateDirect(); - Init(); - } - - explicit TestURLRequestContext(const std::string& proxy) { - host_resolver_ = - net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, - NULL, NULL); - net::ProxyConfig proxy_config; - proxy_config.proxy_rules().ParseFromString(proxy); - proxy_service_ = net::ProxyService::CreateFixed(proxy_config); - Init(); - } - - void set_cookie_policy(net::CookiePolicy* policy) { - cookie_policy_ = policy; - } - - protected: - virtual ~TestURLRequestContext() { - delete ftp_transaction_factory_; - delete http_transaction_factory_; - delete http_auth_handler_factory_; - delete cert_verifier_; - delete host_resolver_; - } - - private: - void Init() { - cert_verifier_ = new net::CertVerifier; - ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); - ssl_config_service_ = new net::SSLConfigServiceDefaults; - http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault( - host_resolver_); - http_transaction_factory_ = new net::HttpCache( - net::HttpNetworkLayer::CreateFactory(host_resolver_, - cert_verifier_, - NULL /* dnsrr_resolver */, - NULL /* dns_cert_checker */, - NULL /* ssl_host_info_factory */, - proxy_service_, - ssl_config_service_, - http_auth_handler_factory_, - network_delegate_, - NULL), - NULL /* net_log */, - net::HttpCache::DefaultBackend::InMemory(0)); - // In-memory cookie store. - cookie_store_ = new net::CookieMonster(NULL, NULL); - accept_language_ = "en-us,fr"; - accept_charset_ = "iso-8859-1,*,utf-8"; - } -}; - -//----------------------------------------------------------------------------- - -class TestURLRequest : public net::URLRequest { - public: - TestURLRequest(const GURL& url, Delegate* delegate) - : net::URLRequest(url, delegate) { - set_context(new TestURLRequestContext()); - } -}; - -//----------------------------------------------------------------------------- - -class TestDelegate : public net::URLRequest::Delegate { - public: - TestDelegate() - : cancel_in_rr_(false), - cancel_in_rs_(false), - cancel_in_rd_(false), - cancel_in_rd_pending_(false), - cancel_in_getcookiesblocked_(false), - cancel_in_setcookieblocked_(false), - quit_on_complete_(true), - quit_on_redirect_(false), - allow_certificate_errors_(false), - response_started_count_(0), - received_bytes_count_(0), - received_redirect_count_(0), - blocked_get_cookies_count_(0), - blocked_set_cookie_count_(0), - set_cookie_count_(0), - received_data_before_response_(false), - request_failed_(false), - have_certificate_errors_(false), - buf_(new net::IOBuffer(kBufferSize)) { - } - - virtual void OnReceivedRedirect(net::URLRequest* request, const GURL& new_url, - bool* defer_redirect) { - received_redirect_count_++; - if (quit_on_redirect_) { - *defer_redirect = true; - MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); - } else if (cancel_in_rr_) { - request->Cancel(); - } - } - - virtual void OnResponseStarted(net::URLRequest* request) { - // It doesn't make sense for the request to have IO pending at this point. - DCHECK(!request->status().is_io_pending()); - - response_started_count_++; - if (cancel_in_rs_) { - request->Cancel(); - OnResponseCompleted(request); - } else if (!request->status().is_success()) { - DCHECK(request->status().status() == net::URLRequestStatus::FAILED || - request->status().status() == net::URLRequestStatus::CANCELED); - request_failed_ = true; - OnResponseCompleted(request); - } else { - // Initiate the first read. - int bytes_read = 0; - if (request->Read(buf_, kBufferSize, &bytes_read)) - OnReadCompleted(request, bytes_read); - else if (!request->status().is_io_pending()) - OnResponseCompleted(request); - } - } - - virtual void OnReadCompleted(net::URLRequest* request, int bytes_read) { - // It doesn't make sense for the request to have IO pending at this point. - DCHECK(!request->status().is_io_pending()); - - if (response_started_count_ == 0) - received_data_before_response_ = true; - - if (cancel_in_rd_) - request->Cancel(); - - if (bytes_read >= 0) { - // There is data to read. - received_bytes_count_ += bytes_read; - - // consume the data - data_received_.append(buf_->data(), bytes_read); - } - - // If it was not end of stream, request to read more. - if (request->status().is_success() && bytes_read > 0) { - bytes_read = 0; - while (request->Read(buf_, kBufferSize, &bytes_read)) { - if (bytes_read > 0) { - data_received_.append(buf_->data(), bytes_read); - received_bytes_count_ += bytes_read; - } else { - break; - } - } - } - if (!request->status().is_io_pending()) - OnResponseCompleted(request); - else if (cancel_in_rd_pending_) - request->Cancel(); - } - - virtual void OnResponseCompleted(net::URLRequest* request) { - if (quit_on_complete_) - MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); - } - - void OnAuthRequired(net::URLRequest* request, - net::AuthChallengeInfo* auth_info) { - if (!username_.empty() || !password_.empty()) { - request->SetAuth(username_, password_); - } else { - request->CancelAuth(); - } - } - - virtual void OnSSLCertificateError(net::URLRequest* request, - int cert_error, - net::X509Certificate* cert) { - // The caller can control whether it needs all SSL requests to go through, - // independent of any possible errors, or whether it wants SSL errors to - // cancel the request. - have_certificate_errors_ = true; - if (allow_certificate_errors_) - request->ContinueDespiteLastError(); - else - request->Cancel(); - } - - virtual void OnGetCookies(net::URLRequest* request, bool blocked_by_policy) { - if (blocked_by_policy) { - blocked_get_cookies_count_++; - if (cancel_in_getcookiesblocked_) - request->Cancel(); - } - } - - virtual void OnSetCookie(net::URLRequest* request, - const std::string& cookie_line, - const net::CookieOptions& options, - bool blocked_by_policy) { - if (blocked_by_policy) { - blocked_set_cookie_count_++; - if (cancel_in_setcookieblocked_) - request->Cancel(); - } else { - set_cookie_count_++; - } - } - - void set_cancel_in_received_redirect(bool val) { cancel_in_rr_ = val; } - void set_cancel_in_response_started(bool val) { cancel_in_rs_ = val; } - void set_cancel_in_received_data(bool val) { cancel_in_rd_ = val; } - void set_cancel_in_received_data_pending(bool val) { - cancel_in_rd_pending_ = val; - } - void set_cancel_in_get_cookies_blocked(bool val) { - cancel_in_getcookiesblocked_ = val; - } - void set_cancel_in_set_cookie_blocked(bool val) { - cancel_in_setcookieblocked_ = val; - } - void set_quit_on_complete(bool val) { quit_on_complete_ = val; } - void set_quit_on_redirect(bool val) { quit_on_redirect_ = val; } - void set_allow_certificate_errors(bool val) { - allow_certificate_errors_ = val; - } - void set_username(const string16& u) { username_ = u; } - void set_password(const string16& p) { password_ = p; } - - // query state - const std::string& data_received() const { return data_received_; } - int bytes_received() const { return static_cast<int>(data_received_.size()); } - int response_started_count() const { return response_started_count_; } - int received_redirect_count() const { return received_redirect_count_; } - int blocked_get_cookies_count() const { return blocked_get_cookies_count_; } - int blocked_set_cookie_count() const { return blocked_set_cookie_count_; } - int set_cookie_count() const { return set_cookie_count_; } - bool received_data_before_response() const { - return received_data_before_response_; - } - bool request_failed() const { return request_failed_; } - bool have_certificate_errors() const { return have_certificate_errors_; } - - private: - static const int kBufferSize = 4096; - // options for controlling behavior - bool cancel_in_rr_; - bool cancel_in_rs_; - bool cancel_in_rd_; - bool cancel_in_rd_pending_; - bool cancel_in_getcookiesblocked_; - bool cancel_in_setcookieblocked_; - bool quit_on_complete_; - bool quit_on_redirect_; - bool allow_certificate_errors_; - - string16 username_; - string16 password_; - - // tracks status of callbacks - int response_started_count_; - int received_bytes_count_; - int received_redirect_count_; - int blocked_get_cookies_count_; - int blocked_set_cookie_count_; - int set_cookie_count_; - bool received_data_before_response_; - bool request_failed_; - bool have_certificate_errors_; - std::string data_received_; - - // our read buffer - scoped_refptr<net::IOBuffer> buf_; -}; - -#endif // NET_URL_REQUEST_URL_REQUEST_UNITTEST_H_ diff --git a/net/websockets/websocket_unittest.cc b/net/websockets/websocket_unittest.cc index e711266..8c412d9 100644 --- a/net/websockets/websocket_unittest.cc +++ b/net/websockets/websocket_unittest.cc @@ -11,7 +11,7 @@ #include "net/base/mock_host_resolver.h" #include "net/base/test_completion_callback.h" #include "net/socket/socket_test_util.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "net/websockets/websocket.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" diff --git a/webkit/appcache/appcache_update_job_unittest.cc b/webkit/appcache/appcache_update_job_unittest.cc index 66e145c..7fcfa5b 100644 --- a/webkit/appcache/appcache_update_job_unittest.cc +++ b/webkit/appcache/appcache_update_job_unittest.cc @@ -11,7 +11,7 @@ #include "net/http/http_response_headers.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "webkit/appcache/appcache_group.h" #include "webkit/appcache/appcache_host.h" #include "webkit/appcache/appcache_policy.h" diff --git a/webkit/glue/mimetype_unittest.cc b/webkit/glue/mimetype_unittest.cc index 8322099..00be1a5 100644 --- a/webkit/glue/mimetype_unittest.cc +++ b/webkit/glue/mimetype_unittest.cc @@ -5,7 +5,7 @@ #include <string> #include "base/string_util.h" -#include "net/url_request/url_request_unittest.h" +#include "net/url_request/url_request_test_util.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #include "webkit/glue/unittest_test_server.h" |