diff options
author | erg@google.com <erg@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-01-25 23:56:08 +0000 |
---|---|---|
committer | erg@google.com <erg@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-01-25 23:56:08 +0000 |
commit | 318e421e5f205dbf7c1988c338e1b27253a63f62 (patch) | |
tree | 54713671124e39b081a58e840e7ad8da0a83f4f7 | |
parent | ceb61da3987d8b7ed828c88daac779b1fbc8c6f9 (diff) | |
download | chromium_src-318e421e5f205dbf7c1988c338e1b27253a63f62.zip chromium_src-318e421e5f205dbf7c1988c338e1b27253a63f62.tar.gz chromium_src-318e421e5f205dbf7c1988c338e1b27253a63f62.tar.bz2 |
Revert "Clean up net unit testing code." since it breaks the shlib builder.
This reverts commit 006f377bbb65ece3490b7c76e58e0dc4cb330909 (r72562).
BUG=68682
TEST=compiles
TBR=thomasvl
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@72564 0039d316-1c4b-4281-b951-d872f2087c98
49 files changed, 935 insertions, 1266 deletions
diff --git a/chrome/browser/chrome_plugin_unittest.cc b/chrome/browser/chrome_plugin_unittest.cc index 03cc345..cd80ac7 100644 --- a/chrome/browser/chrome_plugin_unittest.cc +++ b/chrome/browser/chrome_plugin_unittest.cc @@ -16,7 +16,7 @@ #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_test_util.h" +#include "net/url_request/url_request_unittest.h" #include "net/test/test_server.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chrome/browser/chromeos/gview_request_interceptor_unittest.cc b/chrome/browser/chromeos/gview_request_interceptor_unittest.cc index b2c8c86..e195c4e 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_test_util.h" +#include "net/url_request/url_request_unittest.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 743642c..39e1ac2 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_test_util.h" +#include "net/url_request/url_request_unittest.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 3f72d80..d6078b3 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_test_util.h" +#include "net/url_request/url_request_unittest.h" namespace { diff --git a/chrome/browser/extensions/user_script_listener_unittest.cc b/chrome/browser/extensions/user_script_listener_unittest.cc index 220cd06..9847694 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_test_util.h" +#include "net/url_request/url_request_unittest.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 9507150..45b707a 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_test_util.h" +#include "net/url_request/url_request_unittest.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 b21ed40..4162a3f 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_test_util.h" +#include "net/url_request/url_request_unittest.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 e64ff81..8ecb1ff 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_test_util.h" +#include "net/url_request/url_request_unittest.h" namespace { diff --git a/chrome/browser/sync/glue/http_bridge_unittest.cc b/chrome/browser/sync/glue/http_bridge_unittest.cc index c5d46e7..600e570 100644 --- a/chrome/browser/sync/glue/http_bridge_unittest.cc +++ b/chrome/browser/sync/glue/http_bridge_unittest.cc @@ -7,7 +7,7 @@ #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_test_util.h" +#include "net/url_request/url_request_unittest.h" #include "net/test/test_server.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chrome/browser/unload_uitest.cc b/chrome/browser/unload_uitest.cc index 4a940b0..f30ed16 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_test_util.h" +#include "net/url_request/url_request_unittest.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 4f01aa7..a4a36d4 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi @@ -3202,7 +3202,6 @@ '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 5969e20..b4b3227 100644 --- a/chrome/common/net/url_fetcher_unittest.cc +++ b/chrome/common/net/url_fetcher_unittest.cc @@ -12,7 +12,7 @@ #include "net/http/http_response_headers.h" #include "net/test/test_server.h" #include "net/url_request/url_request_throttler_manager.h" -#include "net/url_request/url_request_test_util.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 fd3e9ab..50ecaab 100644 --- a/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc +++ b/chrome/service/cloud_print/cloud_print_url_fetcher_unittest.cc @@ -14,7 +14,7 @@ #include "net/test/test_server.h" #include "net/url_request/url_request_status.h" #include "net/url_request/url_request_throttler_manager.h" -#include "net/url_request/url_request_test_util.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 43ff974..61dc327 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_test_util.h" +#include "net/url_request/url_request_unittest.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 00af1d1..6b584af 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_test_util.h" +#include "net/url_request/url_request_unittest.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 bfc88f3..e1596c8 100644 --- a/chrome_frame/chrome_frame.gyp +++ b/chrome_frame/chrome_frame.gyp @@ -484,6 +484,8 @@ '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 1355471..f273dce 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_test_util.h" +#include "net/url_request/url_request_unittest.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 deleted file mode 100644 index e785a38..0000000 --- a/net/base/cookie_monster_store_test.cc +++ /dev/null @@ -1,176 +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. - -#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 951c055..84ead74 100644 --- a/net/base/cookie_monster_store_test.h +++ b/net/base/cookie_monster_store_test.h @@ -1,4 +1,4 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2010 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,13 +7,12 @@ // 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 base { -class Time; -} - -namespace net { +namespace { // Describes a call to one of the 3 functions of PersistentCookieStore. struct CookieStoreCommand { @@ -40,32 +39,52 @@ class MockPersistentCookieStore public: typedef std::vector<CookieStoreCommand> CommandList; - MockPersistentCookieStore(); - virtual ~MockPersistentCookieStore(); - - void SetLoadExpectation( - bool return_value, - const std::vector<net::CookieMonster::CanonicalCookie*>& result); - - const CommandList& commands() const { - return commands_; + MockPersistentCookieStore() : load_return_value_(true) { } virtual bool Load( - std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies); + std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies) { + bool ok = load_return_value_; + if (ok) + *out_cookies = load_result_; + return ok; + } - virtual void AddCookie(const net::CookieMonster::CanonicalCookie& cookie); + virtual void AddCookie(const net::CookieMonster::CanonicalCookie& cookie) { + commands_.push_back( + CookieStoreCommand(CookieStoreCommand::ADD, cookie)); + } virtual void UpdateCookieAccessTime( - const net::CookieMonster::CanonicalCookie& cookie); + const net::CookieMonster::CanonicalCookie& cookie) { + commands_.push_back(CookieStoreCommand( + CookieStoreCommand::UPDATE_ACCESS_TIME, cookie)); + } virtual void DeleteCookie( - const net::CookieMonster::CanonicalCookie& cookie); + const net::CookieMonster::CanonicalCookie& cookie) { + commands_.push_back( + CookieStoreCommand(CookieStoreCommand::REMOVE, cookie)); + } - virtual void Flush(Task* completion_task); + virtual void Flush(Task* completion_task) { + if (completion_task) + MessageLoop::current()->PostTask(FROM_HERE, completion_task); + } // No files are created so nothing to clear either - virtual void SetClearLocalStateOnExit(bool clear_local_state); + 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_; + } private: CommandList commands_; @@ -83,18 +102,21 @@ class MockCookieMonsterDelegate : public net::CookieMonster::Delegate { typedef std::pair<net::CookieMonster::CanonicalCookie, bool> CookieNotification; - MockCookieMonsterDelegate(); + MockCookieMonsterDelegate() {} + + virtual void OnCookieChanged( + const net::CookieMonster::CanonicalCookie& cookie, + bool removed) { + CookieNotification notification(cookie, removed); + changes_.push_back(notification); + } 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_; @@ -102,40 +124,84 @@ class MockCookieMonsterDelegate : public net::CookieMonster::Delegate { }; // Helper to build a list of CanonicalCookie*s. -void AddCookieToList( +static void AddCookieToList( const std::string& key, const std::string& cookie_line, const base::Time& creation_time, - std::vector<net::CookieMonster::CanonicalCookie*>* out_list); + 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()); +} // 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 { - public: - MockSimplePersistentCookieStore(); - virtual ~MockSimplePersistentCookieStore(); + private: + typedef std::map<int64, net::CookieMonster::CanonicalCookie> + CanonicalCookieMap; + public: virtual bool Load( - std::vector<net::CookieMonster::CanonicalCookie*>* out_cookies); + 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; + } virtual void AddCookie( - const net::CookieMonster::CanonicalCookie& cookie); + const net::CookieMonster::CanonicalCookie& cookie) { + int64 creation_time = cookie.CreationDate().ToInternalValue(); + EXPECT_TRUE(cookies_.find(creation_time) == cookies_.end()); + cookies_[creation_time] = cookie; + } virtual void UpdateCookieAccessTime( - const net::CookieMonster::CanonicalCookie& cookie); + 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()); + } virtual void DeleteCookie( - const net::CookieMonster::CanonicalCookie& cookie); + 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); + } - virtual void Flush(Task* completion_task); + virtual void Flush(Task* completion_task) { + if (completion_task) + MessageLoop::current()->PostTask(FROM_HERE, 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_; }; @@ -147,9 +213,32 @@ 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. -net::CookieMonster* CreateMonsterFromStoreForGC( +static net::CookieMonster* CreateMonsterFromStoreForGC( int num_cookies, int num_old_cookies, - int days_old); + 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); +} -} // namespace net +} // namespace diff --git a/net/base/cookie_monster_unittest.cc b/net/base/cookie_monster_unittest.cc index caaad67..f431674 100644 --- a/net/base/cookie_monster_unittest.cc +++ b/net/base/cookie_monster_unittest.cc @@ -7,7 +7,6 @@ #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 c65c3de..75fee20 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/mock_filter_context.h" +#include "net/base/filter_unittest.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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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/mock_filter_context.h b/net/base/filter_unittest.h index 3b746e0..a45e353 100644 --- a/net/base/mock_filter_context.h +++ b/net/base/filter_unittest.h @@ -1,9 +1,10 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2006-2009 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_MOCK_FILTER_CONTEXT_H_ -#define NET_BASE_MOCK_FILTER_CONTEXT_H_ +#ifndef NET_BASE_FILTER_UNITTEST_H_ +#define NET_BASE_FILTER_UNITTEST_H_ #pragma once #include <string> @@ -11,12 +12,16 @@ #include "googleurl/src/gurl.h" #include "net/base/filter.h" -namespace net { - +//------------------------------------------------------------------------------ class MockFilterContext : public FilterContext { public: - explicit MockFilterContext(int buffer_size); - virtual ~MockFilterContext(); + explicit MockFilterContext(int buffer_size) + : buffer_size_(buffer_size), + is_cached_content_(false), + is_download_(false), + is_sdch_response_(false), + response_code_(-1) { + } void SetBufferSize(int buffer_size) { buffer_size_ = buffer_size; } void SetMimeType(const std::string& mime_type) { mime_type_ = mime_type; } @@ -29,31 +34,39 @@ class MockFilterContext : public FilterContext { is_sdch_response_ = is_sdch_response; } - virtual bool GetMimeType(std::string* mime_type) const; + virtual bool 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. - virtual bool GetURL(GURL* gurl) const; + virtual bool GetURL(GURL* gurl) const { + *gurl = gurl_; + return true; + } // What was this data requested from a server? - virtual base::Time GetRequestTime() const; + virtual base::Time GetRequestTime() const { + return request_time_; + } // Is data supplied from cache, or fresh across the net? - virtual bool IsCachedContent() const; + virtual bool IsCachedContent() const { return is_cached_content_; } // Is this a download? - virtual bool IsDownload() const; + virtual bool IsDownload() const { return is_download_; } // Was this data flagged as a response to a request with an SDCH dictionary? - virtual bool IsSdchResponse() const; + virtual bool IsSdchResponse() const { return is_sdch_response_; } // How many bytes were fed to filter(s) so far? - virtual int64 GetByteReadCount() const; + virtual int64 GetByteReadCount() const { return 0; } - virtual int GetResponseCode() const; + virtual int GetResponseCode() const { return response_code_; } // What is the desirable input buffer size for these filters? - virtual int GetInputStreamBufferSize() const; + virtual int GetInputStreamBufferSize() const { return buffer_size_; } virtual void RecordPacketStats(StatisticSelector statistic) const {} @@ -70,6 +83,4 @@ class MockFilterContext : public FilterContext { DISALLOW_COPY_AND_ASSIGN(MockFilterContext); }; -} // namespace net - -#endif // NET_BASE_MOCK_FILTER_CONTEXT_H_ +#endif // NET_BASE_FILTER_UNITTEST_H_ diff --git a/net/base/gzip_filter_unittest.cc b/net/base/gzip_filter_unittest.cc index 758418c..8ca1f4d 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); - net::MockFilterContext filter_context(kDefaultBufferSize); + 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); - net::MockFilterContext filter_context(kDefaultBufferSize); + 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); - net::MockFilterContext filter_context(kSmallBufferSize); + 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); - net::MockFilterContext filter_context(1); + 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); - net::MockFilterContext filter_context(kDefaultBufferSize); + 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); - net::MockFilterContext filter_context(1); + 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); - net::MockFilterContext filter_context(kDefaultBufferSize); + 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); - net::MockFilterContext filter_context(kDefaultBufferSize); + 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); - net::MockFilterContext filter_context(kDefaultBufferSize); + 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 75beeec..53fc79b 100644 --- a/net/base/listen_socket_unittest.cc +++ b/net/base/listen_socket_unittest.cc @@ -19,12 +19,8 @@ static const int kMaxQueueSize = 20; static const char kLoopback[] = "127.0.0.1"; static const int kDefaultTimeoutMs = 5000; -ListenSocketTester::ListenSocketTester() - : thread_(NULL), - loop_(NULL), - server_(NULL), - connection_(NULL), - cv_(&lock_) { +ListenSocket* ListenSocketTester::DoListen() { + return ListenSocket::Listen(kLoopback, kTestPort, this); } void ListenSocketTester::SetUp() { @@ -125,6 +121,36 @@ 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(); @@ -174,42 +200,6 @@ 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 f54fc31..f283cb0 100644 --- a/net/base/listen_socket_unittest.h +++ b/net/base/listen_socket_unittest.h @@ -68,11 +68,24 @@ class ListenSocketTester : public ListenSocket::ListenSocketDelegate, public base::RefCountedThreadSafe<ListenSocketTester> { + protected: + friend class base::RefCountedThreadSafe<ListenSocketTester>; + + virtual ~ListenSocketTester() {} + + virtual ListenSocket* DoListen(); + public: - ListenSocketTester(); + ListenSocketTester() + : thread_(NULL), + loop_(NULL), + server_(NULL), + connection_(NULL), + cv_(&lock_) { + } - void SetUp(); - void TearDown(); + virtual void SetUp(); + virtual void TearDown(); void ReportAction(const ListenSocketTestAction& action); void NextAction(); @@ -83,6 +96,10 @@ 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 @@ -90,13 +107,6 @@ 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_; @@ -109,13 +119,6 @@ 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 deleted file mode 100644 index a453ed8..0000000 --- a/net/base/mock_filter_context.cc +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2010 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/net_test_suite.cc b/net/base/net_test_suite.cc deleted file mode 100644 index a37bc5b..0000000 --- a/net/base/net_test_suite.cc +++ /dev/null @@ -1,46 +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. - -#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 274d067..8ebc4e7 100644 --- a/net/base/net_test_suite.h +++ b/net/base/net_test_suite.h @@ -6,33 +6,53 @@ #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" - -class MessageLoop; - -namespace net { -class NetworkChangeNotifier; -} +#if defined(USE_NSS) +#include "net/ocsp/nss_ocsp.h" +#endif class NetTestSuite : public base::TestSuite { public: - NetTestSuite(int argc, char** argv); - virtual ~NetTestSuite(); - - virtual void Initialize(); + NetTestSuite(int argc, char** argv) : TestSuite(argc, argv) { + } - virtual void Shutdown(); - - protected: + virtual void Initialize() { + TestSuite::Initialize(); + InitializeTestThread(); + } // 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(); + 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(); + } 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 ccf07cb..675a135 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]; - net::MockFilterContext filter_context(kInputBufferSize); + 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]; - net::MockFilterContext filter_context(kInputBufferSize); + 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]; - net::MockFilterContext filter_context(kInputBufferSize); + 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]; - net::MockFilterContext filter_context(kInputBufferSize); + 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]; - net::MockFilterContext filter_context(kInputBufferSize); + 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]; - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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(). - net::MockFilterContext filter_context(kInputBufferSize); + 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. - net::MockFilterContext filter_context(kInputBufferSize); + 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. - net::MockFilterContext filter_context(kInputBufferSize); + 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()); - net::MockFilterContext filter_context(kLargeInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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); - net::MockFilterContext filter_context(kInputBufferSize); + 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 3145c4b..fb6e370 100644 --- a/net/http/http_auth_handler_factory_unittest.cc +++ b/net/http/http_auth_handler_factory_unittest.cc @@ -7,7 +7,6 @@ #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" @@ -98,7 +97,7 @@ TEST(HttpAuthHandlerFactoryTest, RegistryFactory) { TEST(HttpAuthHandlerFactoryTest, DefaultFactory) { scoped_ptr<HostResolver> host_resolver(new MockHostResolver()); - MockAllowURLSecurityManager url_security_manager; + URLSecurityManagerAllow 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 bb57151..684ff55 100644 --- a/net/http/http_auth_handler_negotiate_unittest.cc +++ b/net/http/http_auth_handler_negotiate_unittest.cc @@ -10,7 +10,6 @@ #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) @@ -37,7 +36,7 @@ class HttpAuthHandlerNegotiateTest : public PlatformTest { resolver_->rules()->AddIPLiteralRule("alias", "10.0.0.2", "canonical.example.com"); - url_security_manager_.reset(new MockAllowURLSecurityManager()); + url_security_manager_.reset(new URLSecurityManagerAllow()); 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 6788be2..f45d215 100644 --- a/net/http/http_auth_unittest.cc +++ b/net/http/http_auth_unittest.cc @@ -17,7 +17,6 @@ #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 { @@ -116,7 +115,7 @@ TEST(HttpAuthTest, ChooseBestChallenge) { }; GURL origin("http://www.example.com"); std::set<HttpAuth::Scheme> disabled_schemes; - MockAllowURLSecurityManager url_security_manager; + URLSecurityManagerAllow 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 fabfb01..518c1f8 100644 --- a/net/http/http_transaction_unittest.cc +++ b/net/http/http_transaction_unittest.cc @@ -1,11 +1,10 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Copyright (c) 2006-2008 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 <algorithm> - +#include "base/hash_tables.h" #include "base/message_loop.h" #include "base/string_util.h" #include "net/base/net_errors.h" @@ -17,11 +16,6 @@ #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 @@ -110,6 +104,18 @@ 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()); @@ -124,222 +130,12 @@ 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 0a11bb5..3149534 100644 --- a/net/http/http_transaction_unittest.h +++ b/net/http/http_transaction_unittest.h @@ -8,11 +8,15 @@ #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" @@ -23,10 +27,6 @@ #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" -namespace net { -class IOBuffer; -} - //----------------------------------------------------------------------------- // mock transaction data @@ -97,7 +97,12 @@ struct ScopedMockTransaction : MockTransaction { class MockHttpRequest : public net::HttpRequestInfo { public: - explicit MockHttpRequest(const MockTransaction& t); + explicit MockHttpRequest(const MockTransaction& t) { + url = GURL(t.url); + method = t.method; + extra_headers.AddHeadersFromString(t.request_headers); + load_flags = t.load_flags; + } }; //----------------------------------------------------------------------------- @@ -105,11 +110,25 @@ class MockHttpRequest : public net::HttpRequestInfo { class TestTransactionConsumer : public CallbackRunner< Tuple1<int> > { public: - explicit TestTransactionConsumer(net::HttpTransactionFactory* factory); - virtual ~TestTransactionConsumer(); + explicit TestTransactionConsumer(net::HttpTransactionFactory* factory) + : state_(IDLE), + trans_(NULL), + error_(net::OK) { + // Disregard the error code. + factory->CreateTransaction(&trans_); + ++quit_counter_; + } + + ~TestTransactionConsumer() { + } void Start(const net::HttpRequestInfo* request, - const net::BoundNetLog& net_log); + const net::BoundNetLog& net_log) { + state_ = STARTING; + int result = trans_->Start(request, this, net_log); + if (result != net::ERR_IO_PENDING) + DidStart(result); + } bool is_done() const { return state_ == DONE; } int error() const { return error_; } @@ -120,22 +139,60 @@ 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 - }; - - 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 state_; scoped_ptr<net::HttpTransaction> trans_; std::string content_; scoped_refptr<net::IOBuffer> read_buf_; @@ -153,38 +210,107 @@ class TestTransactionConsumer : public CallbackRunner< Tuple1<int> > { // HttpCache implementation. class MockNetworkTransaction : public net::HttpTransaction { public: - MockNetworkTransaction(); - virtual ~MockNetworkTransaction(); + MockNetworkTransaction() : + ALLOW_THIS_IN_INITIALIZER_LIST(task_factory_(this)), data_cursor_(0) { + } virtual int Start(const net::HttpRequestInfo* request, net::CompletionCallback* callback, - const net::BoundNetLog& net_log); + 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; - virtual int RestartIgnoringLastError(net::CompletionCallback* callback); + 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 RestartWithCertificate(net::X509Certificate* client_cert, - net::CompletionCallback* callback); + net::CompletionCallback* callback) { + return net::ERR_FAILED; + } virtual int RestartWithAuth(const string16& username, const string16& password, - net::CompletionCallback* callback); + net::CompletionCallback* callback) { + return net::ERR_FAILED; + } - virtual bool IsReadyToRestartForAuth(); + virtual bool IsReadyToRestartForAuth() { + return false; + } virtual int Read(net::IOBuffer* buf, int buf_len, - net::CompletionCallback* callback); + 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; + } - virtual void StopCaching(); + virtual void StopCaching() {} - virtual const net::HttpResponseInfo* GetResponseInfo() const; + virtual const net::HttpResponseInfo* GetResponseInfo() const { + return &response_; + } - virtual net::LoadState GetLoadState() const; + virtual net::LoadState GetLoadState() const { + if (data_cursor_) + return net::LOAD_STATE_READING_RESPONSE; + return net::LOAD_STATE_IDLE; + } - virtual uint64 GetUploadProgress() const; + virtual uint64 GetUploadProgress() const { + return 0; + } private: - void CallbackLater(net::CompletionCallback* callback, int result); - void RunCallback(net::CompletionCallback* callback, int result); + 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); + } ScopedRunnableMethodFactory<MockNetworkTransaction> task_factory_; net::HttpResponseInfo response_; @@ -195,21 +321,32 @@ class MockNetworkTransaction : public net::HttpTransaction { class MockNetworkLayer : public net::HttpTransactionFactory { public: - MockNetworkLayer(); - virtual ~MockNetworkLayer(); + MockNetworkLayer() : transaction_count_(0) { + } - int transaction_count() const { return transaction_count_; } + 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; + } - // net::HttpTransactionFactory: - virtual int CreateTransaction(scoped_ptr<net::HttpTransaction>* trans); - virtual net::HttpCache* GetCache(); - virtual net::HttpNetworkSession* GetSession(); - virtual void Suspend(bool suspend); + virtual void Suspend(bool suspend) {} + + int transaction_count() const { return transaction_count_; } 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 deleted file mode 100644 index e8b2c4f..0000000 --- a/net/http/mock_allow_url_security_manager.cc +++ /dev/null @@ -1,22 +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. - -#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 deleted file mode 100644 index 32f572e..0000000 --- a/net/http/mock_allow_url_security_manager.h +++ /dev/null @@ -1,29 +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_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 119d6bd..c6a5ec9 100644 --- a/net/http/url_security_manager.h +++ b/net/http/url_security_manager.h @@ -74,6 +74,25 @@ 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 aeff659..7dedb46 100644 --- a/net/net.gyp +++ b/net/net.gyp @@ -866,6 +866,7 @@ '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', @@ -877,10 +878,9 @@ '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,8 +947,6 @@ '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', @@ -999,6 +997,7 @@ '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', @@ -1159,10 +1158,6 @@ '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', @@ -1177,8 +1172,6 @@ '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 4a96071..3e068a6 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_test_util.h" +#include "net/url_request/url_request_unittest.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 24a0ff0..832b0ab 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_test_util.h" +#include "net/url_request/url_request_unittest.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 f7ee96c..e6413429 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_test_util.h" +#include "net/url_request/url_request_unittest.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 df6448b..11a5e3b 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_test_util.h" +#include "net/url_request/url_request_unittest.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 deleted file mode 100644 index 099810a..0000000 --- a/net/url_request/url_request_test_util.cc +++ /dev/null @@ -1,281 +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. - -#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 deleted file mode 100644 index aabb3f0..0000000 --- a/net/url_request/url_request_test_util.h +++ /dev/null @@ -1,190 +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/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_UNITTEST_H_ diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 93daab0..ce02eed 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc @@ -2,6 +2,8 @@ // 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) @@ -46,7 +48,6 @@ #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 new file mode 100644 index 0000000..030b59b --- /dev/null +++ b/net/url_request/url_request_unittest.h @@ -0,0 +1,405 @@ +// 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 8c412d9..e711266 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_test_util.h" +#include "net/url_request/url_request_unittest.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 7fcfa5b..66e145c 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_test_util.h" +#include "net/url_request/url_request_unittest.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 00be1a5..8322099 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_test_util.h" +#include "net/url_request/url_request_unittest.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" |