sync_test.h revision effb81e5f8246d0db0270817048dc992db66e9fb
1// Copyright 2013 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#ifndef CHROME_BROWSER_SYNC_TEST_INTEGRATION_SYNC_TEST_H_ 6#define CHROME_BROWSER_SYNC_TEST_INTEGRATION_SYNC_TEST_H_ 7 8#include <string> 9#include <vector> 10 11#include "base/basictypes.h" 12#include "base/compiler_specific.h" 13#include "base/memory/scoped_ptr.h" 14#include "base/memory/scoped_vector.h" 15#include "chrome/test/base/in_process_browser_test.h" 16#include "net/dns/mock_host_resolver.h" 17#include "net/http/http_status_code.h" 18#include "net/url_request/url_request_status.h" 19#include "sync/internal_api/public/base/model_type.h" 20#include "sync/protocol/sync_protocol_error.h" 21#include "sync/test/fake_server/fake_server.h" 22#include "sync/test/local_sync_test_server.h" 23 24class Profile; 25class ProfileSyncServiceHarness; 26class P2PInvalidationForwarder; 27 28namespace base { 29class CommandLine; 30} 31 32namespace net { 33class FakeURLFetcherFactory; 34class ProxyConfig; 35class ScopedDefaultHostResolverProc; 36class URLFetcherImplFactory; 37class URLRequestContextGetter; 38} 39 40// This is the base class for integration tests for all sync data types. Derived 41// classes must be defined for each sync data type. Individual tests are defined 42// using the IN_PROC_BROWSER_TEST_F macro. 43class SyncTest : public InProcessBrowserTest { 44 public: 45 // The different types of live sync tests that can be implemented. 46 enum TestType { 47 // Tests where only one client profile is synced with the server. Typically 48 // sanity level tests. Safe to run against the FakeServer, not just the 49 // older python test server. 50 SINGLE_CLIENT, 51 52 // Tests where only one client profile is synced with the server. "Legacy" 53 // means that the scenario isn't yet supported by the FakeServer so they 54 // should be run against the python server instead. 55 SINGLE_CLIENT_LEGACY, 56 57 // Tests where two client profiles are synced with the server. Typically 58 // functionality level tests. 59 TWO_CLIENT, 60 61 // Tests where three or more client profiles are synced with the server. 62 // Typically, these tests create client side races and verify that sync 63 // works. 64 MULTIPLE_CLIENT 65 }; 66 67 // The type of server we're running against. 68 enum ServerType { 69 SERVER_TYPE_UNDECIDED, 70 LOCAL_PYTHON_SERVER, // The mock python server that runs locally and is 71 // part of the Chromium checkout. 72 LOCAL_LIVE_SERVER, // Some other server (maybe the real binary used by 73 // Google's sync service) that can be started on 74 // a per-test basis by running a command 75 EXTERNAL_LIVE_SERVER, // A remote server that the test code has no control 76 // over whatsoever; cross your fingers that the 77 // account state is initially clean. 78 IN_PROCESS_FAKE_SERVER, // The fake Sync server (FakeServer) running 79 // in-process (bypassing HTTP calls). This 80 // ServerType will eventually replace 81 // LOCAL_PYTHON_SERVER. 82 }; 83 84 // NOTE: IMPORTANT the enum here should match with 85 // the enum defined on the chromiumsync.py test server impl. 86 enum SyncErrorFrequency { 87 // Uninitialized state. 88 ERROR_FREQUENCY_NONE, 89 90 // Server sends the error on all requests. 91 ERROR_FREQUENCY_ALWAYS, 92 93 // Server sends the error on two thirds of the request. 94 // Note this is not random. The server would send the 95 // error on the first 2 requests of every 3 requests. 96 ERROR_FREQUENCY_TWO_THIRDS 97 }; 98 99 // Authentication state used by the python sync server. 100 enum PythonServerAuthState { 101 // Python server processes sync requests normally. 102 AUTHENTICATED_TRUE, 103 104 // Python server responds to sync requests with an authentication error. 105 AUTHENTICATED_FALSE 106 }; 107 108 // A SyncTest must be associated with a particular test type. 109 explicit SyncTest(TestType test_type); 110 111 virtual ~SyncTest(); 112 113 // Validates command line parameters and creates a local python test server if 114 // specified. 115 virtual void SetUp() OVERRIDE; 116 117 // Brings down local python test server if one was created. 118 virtual void TearDown() OVERRIDE; 119 120 // Sets up command line flags required for sync tests. 121 virtual void SetUpCommandLine(base::CommandLine* cl) OVERRIDE; 122 123 // Used to get the number of sync clients used by a test. 124 int num_clients() WARN_UNUSED_RESULT { return num_clients_; } 125 126 // Returns a pointer to a particular sync profile. Callee owns the object 127 // and manages its lifetime. 128 Profile* GetProfile(int index) WARN_UNUSED_RESULT; 129 130 // Returns a pointer to a particular browser. Callee owns the object 131 // and manages its lifetime. 132 Browser* GetBrowser(int index) WARN_UNUSED_RESULT; 133 134 // Returns a pointer to a particular sync client. Callee owns the object 135 // and manages its lifetime. 136 ProfileSyncServiceHarness* GetClient(int index) WARN_UNUSED_RESULT; 137 138 // Returns a reference to the collection of sync clients. Callee owns the 139 // object and manages its lifetime. 140 std::vector<ProfileSyncServiceHarness*>& clients() WARN_UNUSED_RESULT { 141 return clients_.get(); 142 } 143 144 // Returns a pointer to the sync profile that is used to verify changes to 145 // individual sync profiles. Callee owns the object and manages its lifetime. 146 Profile* verifier() WARN_UNUSED_RESULT; 147 148 // Used to determine whether the verifier profile should be updated or not. 149 bool use_verifier() WARN_UNUSED_RESULT { return use_verifier_; } 150 151 // After calling this method, changes made to a profile will no longer be 152 // reflected in the verifier profile. Note: Not all datatypes use this. 153 // TODO(rsimha): Hook up all datatypes to this mechanism. 154 void DisableVerifier(); 155 156 // Initializes sync clients and profiles but does not sync any of them. 157 virtual bool SetupClients() WARN_UNUSED_RESULT; 158 159 // Initializes sync clients and profiles if required and syncs each of them. 160 virtual bool SetupSync() WARN_UNUSED_RESULT; 161 162 // Enable outgoing network connections for the given profile. 163 virtual void EnableNetwork(Profile* profile); 164 165 // Disable outgoing network connections for the given profile. 166 virtual void DisableNetwork(Profile* profile); 167 168 // Kicks off encryption for profile |index|. 169 bool EnableEncryption(int index); 170 171 // Checks if encryption is complete for profile |index|. 172 bool IsEncryptionComplete(int index); 173 174 // Blocks until all sync clients have completed their mutual sync cycles. 175 // Returns true if a quiescent state was successfully reached. 176 bool AwaitQuiescence(); 177 178 // Returns true if the server being used supports controlling 179 // notifications. 180 bool ServerSupportsNotificationControl() const; 181 182 // Disable notifications on the server. This operation is available 183 // only if ServerSupportsNotificationControl() returned true. 184 void DisableNotifications(); 185 186 // Enable notifications on the server. This operation is available 187 // only if ServerSupportsNotificationControl() returned true. 188 void EnableNotifications(); 189 190 // Sets the mock gaia response for when an OAuth2 token is requested. 191 // Each call to this method will overwrite responses that were previously set. 192 void SetOAuth2TokenResponse(const std::string& response_data, 193 net::HttpStatusCode response_code, 194 net::URLRequestStatus::Status status); 195 196 // Trigger a notification to be sent to all clients. This operation 197 // is available only if ServerSupportsNotificationControl() returned 198 // true. 199 void TriggerNotification(syncer::ModelTypeSet changed_types); 200 201 // Returns true if the server being used supports injecting errors. 202 bool ServerSupportsErrorTriggering() const; 203 204 // Triggers a migration for one or more datatypes, and waits 205 // for the server to complete it. This operation is available 206 // only if ServerSupportsErrorTriggering() returned true. 207 void TriggerMigrationDoneError(syncer::ModelTypeSet model_types); 208 209 // Triggers the server to set its birthday to a random value thereby 210 // the server would return a birthday error on next sync. 211 void TriggerBirthdayError(); 212 213 // Triggers a transient error on the server. Note the server will stay in 214 // this state until shut down. 215 void TriggerTransientError(); 216 217 // Sets / unsets an auth error on the server. Can be used to simulate the case 218 // when the user's gaia password is changed at another location, or their 219 // OAuth2 tokens have expired. The server will stay in this state until 220 // this method is called with a different value. 221 void TriggerAuthState(PythonServerAuthState auth_state); 222 223 // Triggers an XMPP auth error on the server. Note the server will 224 // stay in this state until shut down. 225 void TriggerXmppAuthError(); 226 227 // Triggers a sync error on the server. 228 // error: The error the server is expected to return. 229 // frequency: Frequency with which the error is returned. 230 void TriggerSyncError(const syncer::SyncProtocolError& error, 231 SyncErrorFrequency frequency); 232 233 // Triggers the creation the Synced Bookmarks folder on the server. 234 void TriggerCreateSyncedBookmarks(); 235 236 protected: 237 // Add custom switches needed for running the test. 238 virtual void AddTestSwitches(base::CommandLine* cl); 239 240 // Append the command line switches to enable experimental types that aren't 241 // on by default yet. 242 virtual void AddOptionalTypesToCommandLine(base::CommandLine* cl); 243 244 // InProcessBrowserTest override. Destroys all the sync clients and sync 245 // profiles created by a test. 246 virtual void CleanUpOnMainThread() OVERRIDE; 247 248 // InProcessBrowserTest override. Changes behavior of the default host 249 // resolver to avoid DNS lookup errors. 250 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE; 251 252 // InProcessBrowserTest override. Resets the host resolver its default 253 // behavior. 254 virtual void TearDownInProcessBrowserTestFixture() OVERRIDE; 255 256 // Creates Profile, Browser and ProfileSyncServiceHarness instances for 257 // |index|. Used by SetupClients(). 258 virtual void InitializeInstance(int index); 259 260 // Implementations of the EnableNotifications() and DisableNotifications() 261 // functions defined above. 262 void DisableNotificationsImpl(); 263 void EnableNotificationsImpl(); 264 265 // GAIA account used by the test case. 266 std::string username_; 267 268 // GAIA password used by the test case. 269 std::string password_; 270 271 // Locally available plain text file in which GAIA credentials are stored. 272 base::FilePath password_file_; 273 274 // The FakeServer used in tests with server type IN_PROCESS_FAKE_SERVER. 275 scoped_ptr<fake_server::FakeServer> fake_server_; 276 277 private: 278 // Helper to ProfileManager::CreateProfile that handles path creation. 279 static Profile* MakeProfile(const base::FilePath::StringType name); 280 281 // Helper method used to read GAIA credentials from a local password file 282 // specified via the "--password-file-for-test" command line switch. 283 // Note: The password file must be a plain text file with exactly two lines -- 284 // the username on the first line and the password on the second line. 285 void ReadPasswordFile(); 286 287 // Helper method that starts up a sync test server if required. 288 void SetUpTestServerIfRequired(); 289 290 // Helper method used to start up a local python test server. Note: We set up 291 // an XMPP-only python server if |server_type_| is LOCAL_LIVE_SERVER and mock 292 // gaia credentials are in use. Returns true if successful. 293 bool SetUpLocalPythonTestServer(); 294 295 // Helper method used to start up a local sync test server. Returns true if 296 // successful. 297 bool SetUpLocalTestServer(); 298 299 // Helper method used to destroy the local python sync test server if one was 300 // created. Returns true if successful. 301 bool TearDownLocalPythonTestServer(); 302 303 // Helper method used to destroy the local sync test server if one was 304 // created. Returns true if successful. 305 bool TearDownLocalTestServer(); 306 307 // Helper method that waits for up to |wait| for the test server 308 // to start. Splits the time into |intervals| intervals, and polls the 309 // server after each interval to see if it has started. Returns true if 310 // successful. 311 bool WaitForTestServerToStart(base::TimeDelta wait, int intervals); 312 313 // Helper method used to check if the test server is up and running. 314 bool IsTestServerRunning(); 315 316 // Used to disable and enable network connectivity by providing and 317 // clearing an invalid proxy configuration. 318 void SetProxyConfig(net::URLRequestContextGetter* context, 319 const net::ProxyConfig& proxy_config); 320 321 // Helper method used to set up fake responses for kClientLoginUrl, 322 // kIssueAuthTokenUrl, kGetUserInfoUrl and kSearchDomainCheckUrl in order to 323 // mock out calls to GAIA servers. 324 void SetupMockGaiaResponses(); 325 326 // Helper method used to clear any fake responses that might have been set for 327 // various gaia URLs, cancel any outstanding URL requests, and return to using 328 // the default URLFetcher creation mechanism. 329 void ClearMockGaiaResponses(); 330 331 // Decide which sync server implementation to run against based on the type 332 // of test being run and command line args passed in. 333 void DecideServerType(); 334 335 // Python sync test server, started on demand. 336 syncer::LocalSyncTestServer sync_server_; 337 338 // Helper class to whitelist the notification port. 339 scoped_ptr<net::ScopedPortException> xmpp_port_; 340 341 // Used to differentiate between single-client, two-client, multi-client and 342 // many-client tests. 343 TestType test_type_; 344 345 // Tells us what kind of server we're using (some tests run only on certain 346 // server types). 347 ServerType server_type_; 348 349 // Number of sync clients that will be created by a test. 350 int num_clients_; 351 352 // Collection of sync profiles used by a test. A sync profile maintains sync 353 // data contained within its own subdirectory under the chrome user data 354 // directory. Profiles are owned by the ProfileManager. 355 std::vector<Profile*> profiles_; 356 357 // Collection of pointers to the browser objects used by a test. One browser 358 // instance is created for each sync profile. Browser object lifetime is 359 // managed by BrowserList, so we don't use a ScopedVector here. 360 std::vector<Browser*> browsers_; 361 362 // Collection of sync clients used by a test. A sync client is associated with 363 // a sync profile, and implements methods that sync the contents of the 364 // profile with the server. 365 ScopedVector<ProfileSyncServiceHarness> clients_; 366 367 // A set of objects to listen for commit activity and broadcast notifications 368 // of this activity to its peer sync clients. 369 ScopedVector<P2PInvalidationForwarder> invalidation_forwarders_; 370 371 // Sync profile against which changes to individual profiles are verified. We 372 // don't need a corresponding verifier sync client because the contents of the 373 // verifier profile are strictly local, and are not meant to be synced. 374 Profile* verifier_; 375 376 // Indicates whether changes to a profile should also change the verifier 377 // profile or not. 378 bool use_verifier_; 379 380 // Indicates whether or not notifications were explicitly enabled/disabled. 381 // Defaults to true. 382 bool notifications_enabled_; 383 384 // Sync integration tests need to make live DNS requests for access to 385 // GAIA and sync server URLs under google.com. We use a scoped version 386 // to override the default resolver while the test is active. 387 scoped_ptr<net::ScopedDefaultHostResolverProc> mock_host_resolver_override_; 388 389 // Used to start and stop the local test server. 390 base::ProcessHandle test_server_handle_; 391 392 // Fake URLFetcher factory used to mock out GAIA signin. 393 scoped_ptr<net::FakeURLFetcherFactory> fake_factory_; 394 395 // The URLFetcherImplFactory instance used to instantiate |fake_factory_|. 396 scoped_ptr<net::URLFetcherImplFactory> factory_; 397 398 DISALLOW_COPY_AND_ASSIGN(SyncTest); 399}; 400 401#endif // CHROME_BROWSER_SYNC_TEST_INTEGRATION_SYNC_TEST_H_ 402