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