Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(534)

Side by Side Diff: chrome/browser/policy/enterprise_metrics_unittest.cc

Issue 7345010: Tests for cloud policy UMA metrics. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase Created 9 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2011 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 // These tests run in a child process because they depend on the static
6 // initialization of the UMA counters. Those depend on a singleton instance of
7 // base::StatisticsRecorder, which isn't available for unit_tests. Creating
8 // one just for a couple of tests could lead to problems with other tests that
9 // also depend on the base::StatisticsRecorder; basically, each statically
10 // initialized UMA counter will belong to the StatisticsRecorder that exists
11 // on the first execution of the function that contains the counter. Since we
12 // can't make sure we are the first invokers of that function, we spawn a
13 // child process instead that will create the StatisticsRecorder on its entry
14 // function.
gfeher 2011/07/15 12:21:34 I am going to contradict one of my comments in our
Joao da Silva 2011/07/18 08:45:10 As discussed offline, the out-of-process tests wer
15
16 #include <vector>
17
18 #include "base/file_util.h"
19 #include "base/message_loop.h"
20 #include "base/metrics/histogram.h"
21 #include "base/scoped_temp_dir.h"
22 #include "base/test/multiprocess_test.h"
23 #include "base/time.h"
24 #include "chrome/browser/policy/cloud_policy_controller.h"
25 #include "chrome/browser/policy/cloud_policy_data_store.h"
26 #include "chrome/browser/policy/device_management_backend.h"
27 #include "chrome/browser/policy/device_management_backend_mock.h"
28 #include "chrome/browser/policy/device_management_service.h"
29 #include "chrome/browser/policy/device_token_fetcher.h"
30 #include "chrome/browser/policy/enterprise_metrics.h"
31 #include "chrome/browser/policy/policy_notifier.h"
32 #include "chrome/browser/policy/proto/device_management_backend.pb.h"
33 #include "chrome/browser/policy/proto/device_management_local.pb.h"
34 #include "chrome/browser/policy/user_policy_cache.h"
35 #include "chrome/browser/policy/user_policy_disk_cache.h"
36 #include "chrome/browser/policy/user_policy_token_cache.h"
37 #include "content/browser/browser_thread.h"
38 #include "net/url_request/url_request_status.h"
39 #include "testing/gmock/include/gmock/gmock.h"
40 #include "testing/gtest/include/gtest/gtest.h"
41 #include "testing/multiprocess_func_list.h"
42
43 #if defined(OS_CHROMEOS)
44 #include "chrome/browser/chromeos/cros/mock_cryptohome_library.h"
45 #include "chrome/browser/chromeos/login/signed_settings.h"
46 #include "chrome/browser/chromeos/login/signed_settings_helper.h"
47 #include "chrome/browser/policy/device_policy_cache.h"
48 #include "chrome/browser/policy/enterprise_install_attributes.h"
49 #endif
50
51 namespace policy {
52
53 namespace em = enterprise_management;
54
55 class EnterpriseMetricsTest : public base::MultiProcessTest {
56 protected:
57 EnterpriseMetricsTest() {}
58
59 void TestSubProcess(const std::string& child_name);
60
61 private:
62 DISALLOW_COPY_AND_ASSIGN(EnterpriseMetricsTest);
63 };
64
65 void EnterpriseMetricsTest::TestSubProcess(const std::string& child_name) {
66 base::ProcessHandle handle = SpawnChild(child_name, false);
67 ASSERT_TRUE(handle);
68 int exit_code = 0;
69 EXPECT_TRUE(base::WaitForExitCode(handle, &exit_code));
70 EXPECT_EQ(exit_code, 0);
71 }
72
73 TEST_F(EnterpriseMetricsTest, TokenFetch) {
74 TestSubProcess("enterprise_metrics_token_fetch");
75 }
76
77 TEST_F(EnterpriseMetricsTest, TokenStorage) {
78 TestSubProcess("enterprise_metrics_token_storage");
79 }
80
81 TEST_F(EnterpriseMetricsTest, PolicyFetch) {
82 TestSubProcess("enterprise_metrics_policy_fetch");
83 }
84
85 TEST_F(EnterpriseMetricsTest, UserPolicyStorage) {
86 TestSubProcess("enterprise_metrics_user_policy_storage");
87 }
88
89 #if defined(OS_CHROMEOS)
90
91 TEST_F(EnterpriseMetricsTest, DevicePolicyStorage) {
92 TestSubProcess("enterprise_metrics_device_policy_storage");
93 }
94
95 #endif
96
97 // Tests in child processes have to return a non-zero value to signal that they
98 // failed. These macros are used to return the appropriate value.
99
100 // MULTIPROCESS_TEST_MAIN defines a function that returns an int, while
101 // ASSERT_* macros return void, so they can't be used. Use this macro after
102 // an EXPECT_* call that can't fail instead.
103 #define RETURN_IF_FAILED() \
104 do { \
105 if (testing::Test::HasFailure()) \
106 return 1; \
107 } while (0)
108
109 #define RETURN_CHECK_FAILED() \
110 return testing::Test::HasFailure() ? 1 : 0
111
112 namespace {
113
114 using testing::_;
115 using testing::AnyNumber;
116 using testing::DoAll;
117 using testing::Return;
118 using testing::SetArgumentPointee;
119
120 class MockDeviceManagementService : public DeviceManagementService {
gfeher 2011/07/15 12:21:34 Have you considered reusing the existing MockDevic
Joao da Silva 2011/07/18 08:45:10 They are indeed different, wdyt of the merged vers
121 public:
122 MockDeviceManagementService()
123 : DeviceManagementService(""),
124 response_code_(-1) {
125 }
126
127 virtual void StartJob(DeviceManagementJob* job) OVERRIDE {
128 job->HandleResponse(status_, response_code_, cookies_, data_);
129 }
130
131 void set_url_request_status(const net::URLRequestStatus& status) {
132 status_ = status;
133 }
134
135 void set_response_code(int response_code) {
136 response_code_ = response_code;
137 }
138
139 void set_cookies(const net::ResponseCookies& cookies) {
140 cookies_ = cookies;
141 }
142
143 void set_data(const std::string& data) {
144 data_ = data;
145 }
146
147 private:
148 DeviceManagementJob* job_;
149 net::URLRequestStatus status_;
150 int response_code_;
151 net::ResponseCookies cookies_;
152 std::string data_;
153
154 DISALLOW_COPY_AND_ASSIGN(MockDeviceManagementService);
155 };
156
157 class MockTokenAvailableObserver
158 : public policy::CloudPolicyDataStore::Observer {
159 public:
160 MockTokenAvailableObserver() {}
161 virtual ~MockTokenAvailableObserver() {}
162
163 MOCK_METHOD0(OnDeviceTokenChanged, void());
164 MOCK_METHOD0(OnCredentialsChanged, void());
165 MOCK_METHOD0(OnDataStoreGoingAway, void());
166
167 private:
168 DISALLOW_COPY_AND_ASSIGN(MockTokenAvailableObserver);
169 };
170
171 #if defined(OS_CHROMEOS)
172
173 class MockSignedSettingsHelper : public chromeos::SignedSettingsHelper {
174 public:
175 MockSignedSettingsHelper() {}
176 virtual ~MockSignedSettingsHelper() {}
177
178 MOCK_METHOD2(StartCheckWhitelistOp,
179 void(const std::string& email, Callback*));
180 MOCK_METHOD3(StartWhitelistOp,
181 void(const std::string&, bool, Callback*));
182 MOCK_METHOD3(StartStorePropertyOp,
183 void(const std::string&, const std::string&, Callback*));
184 MOCK_METHOD2(StartRetrieveProperty,
185 void(const std::string&, Callback*));
186 MOCK_METHOD2(StartStorePolicyOp,
187 void(const em::PolicyFetchResponse&, Callback*));
188 MOCK_METHOD1(StartRetrievePolicyOp, void(Callback* callback));
189 MOCK_METHOD1(CancelCallback, void(Callback*));
190
191 private:
192 DISALLOW_COPY_AND_ASSIGN(MockSignedSettingsHelper);
193 };
194
195 ACTION_P(MockSignedSettingsHelperStorePolicy, status_code) {
196 arg1->OnStorePolicyCompleted(status_code);
197 }
198
199 class TestInstallAttributes {
200 public:
201 explicit TestInstallAttributes(const std::string& user)
202 : user_(user),
203 owned_("true"),
204 install_attributes_(&mock_cryptohome_library_) {
205 EXPECT_CALL(mock_cryptohome_library_, InstallAttributesIsReady())
206 .WillOnce(Return(true));
207 EXPECT_CALL(mock_cryptohome_library_, InstallAttributesIsInvalid())
208 .WillOnce(Return(false));
209 EXPECT_CALL(mock_cryptohome_library_, InstallAttributesIsFirstInstall())
210 .WillOnce(Return(false));
211 EXPECT_CALL(mock_cryptohome_library_,
212 InstallAttributesGet("enterprise.owned", _))
213 .WillOnce(DoAll(SetArgumentPointee<1>(owned_),
214 Return(true)));
215 EXPECT_CALL(mock_cryptohome_library_,
216 InstallAttributesGet("enterprise.user", _))
217 .WillOnce(DoAll(SetArgumentPointee<1>(user_),
218 Return(true)));
219 }
220
221 EnterpriseInstallAttributes* install_attributes() {
222 return &install_attributes_;
223 }
224
225 private:
226 std::string user_;
227 std::string owned_;
228 chromeos::MockCryptohomeLibrary mock_cryptohome_library_;
229 EnterpriseInstallAttributes install_attributes_;
230
231 DISALLOW_COPY_AND_ASSIGN(TestInstallAttributes);
232 };
233
234 #endif
235
236 // A helper class for out-of-process tests.
237 class MetricsTest {
gfeher 2011/07/15 12:21:34 Maybe call it MetricsTestHelper?
Joao da Silva 2011/07/18 08:45:10 Obsolete.
238 public:
239 explicit MetricsTest(const std::string& metric_name)
240 : ui_thread_(BrowserThread::UI, &loop_),
241 file_thread_(BrowserThread::FILE, &loop_),
242 metric_name_(metric_name) {
243 EXPECT_TRUE(temp_user_data_dir_.CreateUniqueTempDir());
244
245 if (metric_name_ == kMetricToken) {
246 samples_.resize(kMetricTokenSize, 0);
247 } else if (metric_name_ == kMetricPolicy) {
248 samples_.resize(kMetricPolicySize, 0);
249 } else {
250 NOTREACHED();
251 }
252 }
253
254 const FilePath& temp_dir() {
255 return temp_user_data_dir_.path();
256 }
257
258 void RunAllPending() {
259 loop_.RunAllPending();
260 }
261
262 void Done() {
263 RunAllPending();
264 CheckSamples("Done");
265 }
266
267 void ExpectSample(int sample) {
268 ASSERT_GE(sample, 0);
269 ASSERT_LT(sample, (int) samples_.size());
270 samples_[sample]++;
271 }
272
273 void CheckSamples(const std::string& test_case) {
274 bool expects_samples = false;
275 for (size_t i = 0; i < samples_.size(); ++i) {
276 if (samples_[i] > 0) {
277 expects_samples = true;
278 break;
279 }
280 }
281
282 // The histogram won't be available until the first sample is measured.
283 base::Histogram* histogram = NULL;
284 if (!expects_samples) {
285 EXPECT_FALSE(base::StatisticsRecorder::FindHistogram(metric_name_,
286 &histogram));
287 return;
288 }
289
290 EXPECT_TRUE(base::StatisticsRecorder::FindHistogram(metric_name_,
291 &histogram));
292 ASSERT_TRUE(histogram != NULL);
293
294 base::Histogram::SampleSet samples;
295 histogram->SnapshotSample(&samples);
296
297 size_t sum = 0;
298 for (size_t i = 0; i < samples_.size(); ++i) {
299 EXPECT_EQ(samples_[i], samples.counts(i))
300 << "Mismatch for " << test_case << ", i is " << i;
301 sum += samples_[i];
302 }
303 EXPECT_EQ(sum, (size_t) samples.TotalCount());
304 }
305
306 private:
307 base::StatisticsRecorder statistics_recorder_;
308 MessageLoop loop_;
309 ScopedTempDir temp_user_data_dir_;
310 BrowserThread ui_thread_;
311 BrowserThread file_thread_;
312 std::string metric_name_;
313 std::vector<int> samples_;
gfeher 2011/07/15 12:21:34 Call this expected_samples_?
Joao da Silva 2011/07/18 08:45:10 Done.
314
315 DISALLOW_COPY_AND_ASSIGN(MetricsTest);
316 };
317
318 } // namespace
319
320 MULTIPROCESS_TEST_MAIN(enterprise_metrics_token_fetch) {
321 MetricsTest test(kMetricToken);
322 RETURN_IF_FAILED();
323
324 MockDeviceManagementService service;
325 service.ScheduleInitialization(0);
326 test.RunAllPending();
327 scoped_ptr<DeviceManagementBackend> backend(service.CreateBackend());
328
329 em::DeviceRegisterRequest request;
330 DeviceRegisterResponseDelegateMock delegate;
331 EXPECT_CALL(delegate, OnError(_)).Times(AnyNumber());
332 EXPECT_CALL(delegate, HandleRegisterResponse(_)).Times(AnyNumber());
333 net::URLRequestStatus status;
334
335 // Test failed requests.
336 status.set_status(net::URLRequestStatus::FAILED);
337 service.set_url_request_status(status);
338 test.ExpectSample(kMetricTokenFetchRequested);
339 test.ExpectSample(kMetricTokenFetchRequestFailed);
340 backend->ProcessRegisterRequest("token", "testid", request, &delegate);
341 test.CheckSamples("FailedRequest");
342
343 // Test invalid data.
344 std::string data("\xff");
345 status.set_status(net::URLRequestStatus::SUCCESS);
346 service.set_url_request_status(status);
347 service.set_response_code(200);
348 service.set_data(data);
349 test.ExpectSample(kMetricTokenFetchRequested);
350 test.ExpectSample(kMetricTokenFetchBadResponse);
351 backend->ProcessRegisterRequest("token", "testid", request, &delegate);
352 test.CheckSamples("BadData");
353
354 // Test various error cases.
355 struct {
356 const char* test_case;
357 int error_code;
358 MetricToken sample;
359 } cases[] = {
360 { "400", 400, kMetricTokenFetchRequestFailed },
361 { "401", 401, kMetricTokenFetchServerFailed },
362 { "403", 403, kMetricTokenFetchManagementNotSupported },
363 { "404", 404, kMetricTokenFetchServerFailed },
364 { "410", 410, kMetricTokenFetchDeviceNotFound },
365 { "412", 412, kMetricTokenFetchServerFailed },
366 { "500", 500, kMetricTokenFetchServerFailed },
367 { "503", 503, kMetricTokenFetchServerFailed },
368 { "902", 902, kMetricTokenFetchServerFailed },
369 { "491", 491, kMetricTokenFetchServerFailed },
370 { "901", 901, kMetricTokenFetchDeviceNotFound },
371 };
372
373 service.set_data(std::string());
374
375 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
376 service.set_response_code(cases[i].error_code);
377 test.ExpectSample(kMetricTokenFetchRequested);
378 test.ExpectSample(cases[i].sample);
379 backend->ProcessRegisterRequest("token", "testid", request, &delegate);
380 test.CheckSamples(cases[i].test_case);
381 }
382
383 // Test successful token retrieval.
384 service.set_response_code(200);
385 test.ExpectSample(kMetricTokenFetchRequested);
386 test.ExpectSample(kMetricTokenFetchResponseReceived);
387 backend->ProcessRegisterRequest("token", "testid", request, &delegate);
388 test.CheckSamples("ResponseReceived");
389
390 // Test token fetcher.
391 UserPolicyCache cache(test.temp_dir().AppendASCII("FetchTokenTest"));
392 scoped_ptr<CloudPolicyDataStore> data_store;
393 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
394 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
395 "fake_auth_token", true);
396 PolicyNotifier notifier;
397 DeviceTokenFetcher fetcher(&service, &cache, data_store.get(), &notifier);
398
399 MockTokenAvailableObserver observer;
400 data_store->AddObserver(&observer);
401 EXPECT_CALL(observer, OnDeviceTokenChanged()).Times(1);
402
403 em::DeviceManagementResponse response;
404 response.mutable_register_response()->set_device_management_token("token");
405 response.SerializeToString(&data);
406 service.set_data(data);
407
408 fetcher.FetchToken();
409
410 test.ExpectSample(kMetricTokenFetchRequested);
411 test.ExpectSample(kMetricTokenFetchResponseReceived);
412 test.ExpectSample(kMetricTokenFetchOK);
413 test.CheckSamples("FetchOK");
414
415 // Cleanup.
416 data_store->RemoveObserver(&observer);
417
418 test.Done();
419 RETURN_CHECK_FAILED();
420 }
421
422 MULTIPROCESS_TEST_MAIN(enterprise_metrics_token_storage) {
423 MetricsTest test(kMetricToken);
424 RETURN_IF_FAILED();
425
426 FilePath path = test.temp_dir().AppendASCII("StoreTokenTest");
427
428 scoped_ptr<CloudPolicyDataStore> data_store;
429 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
430 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
431 "fake_auth_token", false);
432 UserPolicyTokenCache cache(data_store.get(), path);
433
434 // Try loading a non-existing file first.
435 cache.Load();
436 test.RunAllPending();
437 // No samples expected.
438 test.CheckSamples("LoadEmpty");
439
440 // Try loading an invalid file.
441 std::string data("\xff");
442 int result = file_util::WriteFile(path, data.c_str(), data.size());
443 EXPECT_EQ((int) data.size(), result);
444 RETURN_IF_FAILED();
445
446 // Make the data store expect a load from cache again.
447 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
448 "fake_auth_token", false);
449 cache.Load();
450 test.RunAllPending();
451 test.ExpectSample(kMetricTokenLoadFailed);
452 test.CheckSamples("LoadFailed");
453
454 // Test storing a valid cache.
455 data_store->SetupForTesting("token", "fake_device_id", "fake_user_name",
456 "fake_auth_token", false);
457 cache.OnDeviceTokenChanged();
458 test.RunAllPending();
459 test.ExpectSample(kMetricTokenStoreSucceeded);
460 test.CheckSamples("StoreSucceeded");
461
462 // Test loading a valid cache.
463 // Make the data store expect a load from cache again.
464 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
465 "fake_auth_token", false);
466 cache.Load();
467 test.RunAllPending();
468 test.ExpectSample(kMetricTokenLoadSucceeded);
469 test.CheckSamples("LoadSucceeded");
470
471 test.Done();
472 RETURN_CHECK_FAILED();
473 }
474
475 MULTIPROCESS_TEST_MAIN(enterprise_metrics_policy_fetch) {
476 MetricsTest test(kMetricPolicy);
477 RETURN_IF_FAILED();
478
479 MockDeviceManagementService service;
480 service.ScheduleInitialization(0);
481 test.RunAllPending();
482 scoped_ptr<DeviceManagementBackend> backend(service.CreateBackend());
483
484 em::DevicePolicyRequest request;
485 DevicePolicyResponseDelegateMock delegate;
486 EXPECT_CALL(delegate, OnError(_)).Times(AnyNumber());
487 EXPECT_CALL(delegate, HandlePolicyResponse(_)).Times(AnyNumber());
488 net::URLRequestStatus status;
489
490 // Test failed requests.
491 status.set_status(net::URLRequestStatus::FAILED);
492 service.set_url_request_status(status);
493 test.ExpectSample(kMetricPolicyFetchRequested);
494 test.ExpectSample(kMetricPolicyFetchRequestFailed);
495 backend->ProcessPolicyRequest("token", "testid", request, &delegate);
496 test.CheckSamples("FailedRequest");
497
498 // Test invalid data.
499 std::string data("\xff");
500 status.set_status(net::URLRequestStatus::SUCCESS);
501 service.set_url_request_status(status);
502 service.set_response_code(200);
503 service.set_data(data);
504 test.ExpectSample(kMetricPolicyFetchRequested);
505 test.ExpectSample(kMetricPolicyFetchBadResponse);
506 backend->ProcessPolicyRequest("token", "testid", request, &delegate);
507 test.CheckSamples("BadData");
508
509 // Test various error cases.
510 struct {
511 const char* test_case;
512 int error_code;
513 MetricPolicy sample;
514 } cases[] = {
515 { "400", 400, kMetricPolicyFetchRequestFailed },
516 { "401", 401, kMetricPolicyFetchInvalidToken },
517 { "403", 403, kMetricPolicyFetchServerFailed },
518 { "404", 404, kMetricPolicyFetchServerFailed },
519 { "410", 410, kMetricPolicyFetchServerFailed },
520 { "412", 412, kMetricPolicyFetchServerFailed },
521 { "500", 500, kMetricPolicyFetchServerFailed },
522 { "503", 503, kMetricPolicyFetchServerFailed },
523 { "902", 902, kMetricPolicyFetchNotFound },
524 { "491", 491, kMetricPolicyFetchServerFailed },
525 { "901", 901, kMetricPolicyFetchServerFailed },
526 };
527
528 service.set_data(std::string());
529
530 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
531 service.set_response_code(cases[i].error_code);
532 test.ExpectSample(kMetricPolicyFetchRequested);
533 test.ExpectSample(cases[i].sample);
534 backend->ProcessPolicyRequest("token", "testid", request, &delegate);
535 test.CheckSamples(cases[i].test_case);
536 }
537
538 // Test successful policy retrieval.
539 service.set_response_code(200);
540 test.ExpectSample(kMetricPolicyFetchRequested);
541 test.ExpectSample(kMetricPolicyFetchResponseReceived);
542 backend->ProcessPolicyRequest("token", "testid", request, &delegate);
543 test.CheckSamples("ResponseReceived");
544
545 // Test fetching an invalid policy.
546 UserPolicyCache cache(test.temp_dir().AppendASCII("UserPolicyCacheTest"));
547 // This is to bypass the private method override in UserPolicyCache:
548 UserPolicyDiskCache::Delegate* cache_as_delegate =
549 implicit_cast<UserPolicyDiskCache::Delegate*>(&cache);
550
551 em::CachedCloudPolicyResponse response;
552 response.mutable_cloud_policy()->set_policy_data(data);
553 cache_as_delegate->OnDiskCacheLoaded(response);
554 test.ExpectSample(kMetricPolicyFetchInvalidPolicy);
555 test.CheckSamples("InvalidPolicy");
556
557 // Test timestamp in future.
558 em::PolicyData policy_data;
559 base::TimeDelta timestamp =
560 (base::Time::NowFromSystemTime() + base::TimeDelta::FromDays(1000)) -
561 base::Time::UnixEpoch();
562 policy_data.set_timestamp(timestamp.InMilliseconds());
563 policy_data.SerializeToString(&data);
564 response.mutable_cloud_policy()->set_policy_data(data);
565 cache_as_delegate->OnDiskCacheLoaded(response);
566 test.ExpectSample(kMetricPolicyFetchTimestampInFuture);
567 test.CheckSamples("TimestampInFuture");
568
569 // Test policy not modified.
570 policy_data.set_timestamp(0);
571 policy_data.SerializeToString(&data);
572 response.mutable_cloud_policy()->set_policy_data(data);
573 cache_as_delegate->OnDiskCacheLoaded(response);
574 test.ExpectSample(kMetricPolicyFetchNotModified);
575 test.CheckSamples("NotModified");
576
577 // Test fetch OK.
578 cache.SetPolicy(response.cloud_policy());
579 test.ExpectSample(kMetricPolicyFetchOK);
580 test.ExpectSample(kMetricPolicyFetchNotModified);
581 test.CheckSamples("FetchOK");
582 // This also triggers a store. Update the expected samples.
583 test.RunAllPending();
584 test.ExpectSample(kMetricPolicyStoreSucceeded);
585 test.CheckSamples("FetchOKAndStore");
586
587 // Test bad responses.
588 PolicyNotifier notifier;
589 scoped_ptr<CloudPolicyDataStore> data_store;
590 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
591 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
592 "fake_auth_token", true);
593 CloudPolicyController controller(NULL, &cache, NULL, data_store.get(),
594 &notifier);
595 em::DevicePolicyResponse device_policy_response;
596 controller.HandlePolicyResponse(device_policy_response);
597 test.ExpectSample(kMetricPolicyFetchBadResponse);
598 test.CheckSamples("BadResponse");
599
600 // More bad responses.
601 em::PolicyFetchResponse* policy_fetch_response =
602 device_policy_response.add_response();
603 policy_fetch_response->set_error_code(
604 DeviceManagementBackend::kErrorServicePolicyNotFound);
605 controller.HandlePolicyResponse(device_policy_response);
606 test.ExpectSample(kMetricPolicyFetchBadResponse);
607 test.CheckSamples("BadResponse2");
608
609 test.Done();
610 RETURN_CHECK_FAILED();
611 }
612
613 MULTIPROCESS_TEST_MAIN(enterprise_metrics_user_policy_storage) {
614 MetricsTest test(kMetricPolicy);
615 RETURN_IF_FAILED();
616
617 FilePath path = test.temp_dir().AppendASCII("UserPolicyDiskCacheTest");
618
619 scoped_refptr<UserPolicyDiskCache> cache(
620 new UserPolicyDiskCache(base::WeakPtr<UserPolicyDiskCache::Delegate>(),
621 path));
622
623 // Load empty cache.
624 cache->Load();
625 test.RunAllPending();
626 // No samples expected.
627 test.CheckSamples("NoCache");
628
629 // Load an invalid cache.
630 std::string data("\xff");
631 int result = file_util::WriteFile(path, data.c_str(), data.size());
632 EXPECT_EQ((int) data.size(), result);
633 RETURN_IF_FAILED();
634
635 cache->Load();
636 test.RunAllPending();
637 test.ExpectSample(kMetricPolicyLoadFailed);
638 test.CheckSamples("InvalidCache");
639
640 // Store a cache.
641 em::CachedCloudPolicyResponse response;
642 cache->Store(response);
643 test.RunAllPending();
644 test.ExpectSample(kMetricPolicyStoreSucceeded);
645 test.CheckSamples("StoreCache");
646
647 // Load a good cache.
648 cache->Load();
649 test.RunAllPending();
650 test.ExpectSample(kMetricPolicyLoadSucceeded);
651 test.CheckSamples("LoadCache");
652
653 test.Done();
654 RETURN_CHECK_FAILED();
655 }
656
657 #if defined(OS_CHROMEOS)
658
659 MULTIPROCESS_TEST_MAIN(enterprise_metrics_device_policy_storage) {
660 MetricsTest test(kMetricPolicy);
661 RETURN_IF_FAILED();
662
663 scoped_ptr<CloudPolicyDataStore> data_store;
664 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
665 // The DevicePolicyCache is reset to a new object to have
666 // |starting_up_| set to true again, and test the loading path.
667 scoped_ptr<DevicePolicyCache> device_policy_cache;
668 em::PolicyFetchResponse response;
669
670 // Test non-existing policy.
671 device_policy_cache.reset(new DevicePolicyCache(data_store.get(), NULL));
672 data_store->SetupForTesting("", "id", "user", "token", false);
673 device_policy_cache->OnRetrievePolicyCompleted(
674 chromeos::SignedSettings::NOT_FOUND, response);
675 // No samples expected.
676 test.CheckSamples("NoPolicy");
677
678 // Test bad policy data.
679 response.set_policy_data(std::string("\xff"));
680 device_policy_cache.reset(new DevicePolicyCache(data_store.get(), NULL));
681 data_store->SetupForTesting("", "id", "user", "token", false);
682 device_policy_cache->OnRetrievePolicyCompleted(
683 chromeos::SignedSettings::SUCCESS, response);
684 test.ExpectSample(kMetricPolicyLoadFailed);
685 test.CheckSamples("BadPolicyData");
686
687 // Test more bad policy data.
688 em::PolicyData policy_data;
689 policy_data.set_request_token("token");
690 std::string policy_data_string;
691 policy_data.SerializeToString(&policy_data_string);
692 response.set_policy_data(policy_data_string);
693 device_policy_cache.reset(new DevicePolicyCache(data_store.get(), NULL));
694 data_store->SetupForTesting("", "id", "user", "token", false);
695 device_policy_cache->OnRetrievePolicyCompleted(
696 chromeos::SignedSettings::SUCCESS, response);
697 test.ExpectSample(kMetricPolicyLoadFailed);
698 test.CheckSamples("BadPolicyData2");
699
700 // Test good policy data.
701 policy_data.set_username("user");
702 policy_data.set_device_id("device_id");
703 policy_data.SerializeToString(&policy_data_string);
704 response.set_policy_data(policy_data_string);
705 device_policy_cache.reset(new DevicePolicyCache(data_store.get(), NULL));
706 data_store->SetupForTesting("", "id", "user", "token", false);
707 device_policy_cache->OnRetrievePolicyCompleted(
708 chromeos::SignedSettings::SUCCESS, response);
709 test.ExpectSample(kMetricPolicyLoadSucceeded);
710 // There is no policy data though.
711 test.ExpectSample(kMetricPolicyFetchNotModified);
712 test.CheckSamples("LoadSucceeded");
713
714 // Test storing the device policy.
715 struct {
716 const char* case_name;
717 chromeos::SignedSettings::ReturnCode return_code;
718 int expected_retrieve;
719 int expected_sample;
720 int expected_sample2;
721 } cases[] = {
722 { "StoreSuceeded", chromeos::SignedSettings::SUCCESS, 1,
723 kMetricPolicyStoreSucceeded, -1 },
724 { "StoreBadSignature", chromeos::SignedSettings::BAD_SIGNATURE, 0,
725 kMetricPolicyStoreFailed, kMetricPolicyFetchBadSignature },
726 { "StoreOtherFailed", chromeos::SignedSettings::OPERATION_FAILED, 0,
727 kMetricPolicyStoreFailed, kMetricPolicyFetchOtherFailed },
728 };
729
730 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
731 TestInstallAttributes install_attributes("user");
732 MockSignedSettingsHelper mock_signed_settings_helper;
733
734 device_policy_cache.reset(
735 new DevicePolicyCache(data_store.get(),
736 install_attributes.install_attributes(), &mock_signed_settings_helper));
737
738 EXPECT_CALL(mock_signed_settings_helper, StartStorePolicyOp(_, _)).WillOnce(
739 MockSignedSettingsHelperStorePolicy(cases[i].return_code));
740 EXPECT_CALL(mock_signed_settings_helper, CancelCallback(_)).Times(2);
741 EXPECT_CALL(mock_signed_settings_helper,
742 StartRetrievePolicyOp(_)).Times(cases[i].expected_retrieve);
743
744 // Make the cache have |starting_up_| set to false.
745 data_store->SetupForTesting("", "id", "user", "token", false);
746 device_policy_cache->OnRetrievePolicyCompleted(
747 chromeos::SignedSettings::NOT_FOUND, response);
748 // Now trigger the store.
749 device_policy_cache->SetPolicy(response);
750 test.ExpectSample(cases[i].expected_sample);
751 if (cases[i].expected_sample2 >= 0)
752 test.ExpectSample(cases[i].expected_sample2);
753 test.CheckSamples(cases[i].case_name);
754
755 // Cleanup while the MockSignedSettingsHelper is alive.
756 device_policy_cache.reset();
757 }
758
759 // Test setting policy on non-enterprise device.
760 {
761 EnterpriseInstallAttributes install_attributes(NULL);
762 device_policy_cache.reset(new DevicePolicyCache(data_store.get(),
763 &install_attributes));
764 // Make the cache have |starting_up_| set to false.
765 data_store->SetupForTesting("", "id", "user", "token", false);
766 device_policy_cache->OnRetrievePolicyCompleted(
767 chromeos::SignedSettings::NOT_FOUND, response);
768 // Now trigger the error.
769 device_policy_cache->SetPolicy(response);
770 test.ExpectSample(kMetricPolicyFetchNonEnterpriseDevice);
771 test.CheckSamples("NonEnterprise");
772 }
773
774 // Test user-mismatch between device and policy.
775 {
776 TestInstallAttributes install_attributes("bogus");
777 device_policy_cache.reset(new DevicePolicyCache(data_store.get(),
778 install_attributes.install_attributes()));
779 // Make the cache have |starting_up_| set to false.
780 data_store->SetupForTesting("", "id", "user", "token", false);
781 device_policy_cache->OnRetrievePolicyCompleted(
782 chromeos::SignedSettings::NOT_FOUND, response);
783 // Now trigger the store.
784 device_policy_cache->SetPolicy(response);
785 test.ExpectSample(kMetricPolicyFetchUserMismatch);
786 test.CheckSamples("UserMismatch");
787 }
788
789 // Test bad signature.
790 device_policy_cache.reset(new DevicePolicyCache(data_store.get(), NULL));
791 // Make the cache have |starting_up_| set to false.
792 data_store->SetupForTesting("", "id", "user", "token", false);
793 device_policy_cache->OnRetrievePolicyCompleted(
794 chromeos::SignedSettings::NOT_FOUND, response);
795 // Now trigger the store.
796 device_policy_cache->OnRetrievePolicyCompleted(
797 chromeos::SignedSettings::BAD_SIGNATURE, response);
798 test.ExpectSample(kMetricPolicyFetchBadSignature);
799 test.CheckSamples("BadSignature");
800
801 // Test other failures.
802 device_policy_cache.reset(new DevicePolicyCache(data_store.get(), NULL));
803 // Make the cache have |starting_up_| set to false.
804 data_store->SetupForTesting("", "id", "user", "token", false);
805 device_policy_cache->OnRetrievePolicyCompleted(
806 chromeos::SignedSettings::NOT_FOUND, response);
807 // Now trigger the store.
808 device_policy_cache->OnRetrievePolicyCompleted(
809 chromeos::SignedSettings::OPERATION_FAILED, response);
810 test.ExpectSample(kMetricPolicyFetchOtherFailed);
811 test.CheckSamples("BadSignature");
812
813 // Test fetching invalid policy.
814 {
815 TestInstallAttributes install_attributes("user");
816 device_policy_cache.reset(new DevicePolicyCache(data_store.get(),
817 install_attributes.install_attributes()));
818 // Make the cache have |starting_up_| set to false.
819 data_store->SetupForTesting("", "id", "user", "token", false);
820 device_policy_cache->OnRetrievePolicyCompleted(
821 chromeos::SignedSettings::NOT_FOUND, response);
822 // Now trigger the store.
823 response.set_policy_data(std::string("\xff"));
824 device_policy_cache->SetPolicy(response);
825 test.ExpectSample(kMetricPolicyFetchInvalidPolicy);
826 test.CheckSamples("UserMismatch");
827 }
828
829 test.Done();
830 RETURN_CHECK_FAILED();
831 }
832
833 #endif
834
835 } // namespace policy
OLDNEW
« no previous file with comments | « chrome/browser/policy/enterprise_metrics_browsertest.cc ('k') | chrome/browser/policy/user_policy_token_cache.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698