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

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

Issue 7345010: Tests for cloud policy UMA metrics. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Reviewed 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 #include "base/basictypes.h"
6 #include "base/file_util.h"
7 #include "base/message_loop.h"
8 #include "base/metrics/histogram.h"
9 #include "base/scoped_temp_dir.h"
10 #include "base/time.h"
11 #include "chrome/browser/policy/cloud_policy_controller.h"
12 #include "chrome/browser/policy/cloud_policy_data_store.h"
13 #include "chrome/browser/policy/device_management_backend.h"
14 #include "chrome/browser/policy/device_management_backend_mock.h"
15 #include "chrome/browser/policy/device_management_service.h"
16 #include "chrome/browser/policy/device_token_fetcher.h"
17 #include "chrome/browser/policy/enterprise_metrics.h"
18 #include "chrome/browser/policy/mock_cloud_policy_data_store.h"
19 #include "chrome/browser/policy/mock_device_management_service.h"
20 #include "chrome/browser/policy/policy_notifier.h"
21 #include "chrome/browser/policy/proto/device_management_backend.pb.h"
22 #include "chrome/browser/policy/proto/device_management_local.pb.h"
23 #include "chrome/browser/policy/user_policy_cache.h"
24 #include "chrome/browser/policy/user_policy_token_cache.h"
25 #include "content/browser/browser_thread.h"
26 #include "net/url_request/url_request_status.h"
27 #include "testing/gmock/include/gmock/gmock.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29
30 #if defined(OS_CHROMEOS)
31 #include "chrome/browser/chromeos/cros/mock_cryptohome_library.h"
32 #include "chrome/browser/chromeos/login/mock_signed_settings_helper.h"
33 #include "chrome/browser/chromeos/login/signed_settings.h"
34 #include "chrome/browser/policy/device_policy_cache.h"
35 #include "chrome/browser/policy/enterprise_install_attributes.h"
36 #endif
37
38 namespace policy {
39
40 namespace em = enterprise_management;
41
42 using testing::_;
43 using testing::AnyNumber;
44 using testing::DoAll;
45 using testing::Invoke;
46 using testing::Mock;
47 using testing::Return;
48 using testing::SetArgumentPointee;
49
50 namespace {
51
52 // Helper with common code for tests that use the DeviceManagementBackendImpl.
53 class DeviceManagementBackendTestHelper {
54 public:
55 explicit DeviceManagementBackendTestHelper(MessageLoop* loop) {
56 service_.ScheduleInitialization(0);
57 loop->RunAllPending();
58 backend_.reset(service_.CreateBackendNotMocked());
59 }
60
61 DeviceManagementService& service() {
62 return service_;
63 }
64
65 void ProcessRegisterRequest() {
66 em::DeviceRegisterRequest request;
67 DeviceRegisterResponseDelegateMock delegate;
68 EXPECT_CALL(delegate, OnError(_)).Times(AnyNumber());
69 EXPECT_CALL(delegate, HandleRegisterResponse(_)).Times(AnyNumber());
70 backend_->ProcessRegisterRequest("token", "testid", request, &delegate);
71 }
72
73 void ProcessPolicyRequest() {
74 em::DevicePolicyRequest request;
75 DevicePolicyResponseDelegateMock delegate;
76 EXPECT_CALL(delegate, OnError(_)).Times(AnyNumber());
77 EXPECT_CALL(delegate, HandlePolicyResponse(_)).Times(AnyNumber());
78 backend_->ProcessPolicyRequest("token", "testid", request, &delegate);
79 }
80
81 void UnmockCreateBackend() {
82 EXPECT_CALL(service_, CreateBackend())
83 .WillOnce(Invoke(&service_,
84 &MockDeviceManagementService::CreateBackendNotMocked));
85 }
86
87 void ExpectStartJob(net::URLRequestStatus::Status status, int response_code,
88 const std::string& data) {
89 net::ResponseCookies cookies;
90 net::URLRequestStatus url_request_status(status, 0);
91 EXPECT_CALL(service_, StartJob(_))
92 .WillOnce(MockDeviceManagementServiceRespondToJob(
93 url_request_status, response_code, cookies, data));
94 }
95
96 bool VerifyAndClearExpectations() {
97 return Mock::VerifyAndClearExpectations(&service_);
98 }
99
100 private:
101 MockDeviceManagementService service_;
102 scoped_ptr<DeviceManagementBackend> backend_;
103
104 DISALLOW_COPY_AND_ASSIGN(DeviceManagementBackendTestHelper);
105 };
106
107 } // namespace
108
109 // This derives from testing::Test and not from InProcessBrowserTest and is
110 // linked with browser_tests. The reason is that these are just unit tests, but
111 // due to the static initialization of the UMA counters they have to run each
112 // in its own process to make sure the counters are not initialized before the
113 // test runs, and that the StatisticsRecorder instance created for the test
114 // doesn't interfere with counters in other tests.
115 class EnterpriseMetricsTest : public testing::Test {
116 public:
117 EnterpriseMetricsTest()
118 : ui_thread_(BrowserThread::UI, &loop_),
119 file_thread_(BrowserThread::FILE, &loop_) {
120 EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
121 }
122
123 void SetMetricName(const std::string& metric_name) {
124 metric_name_ = metric_name;
125 if (metric_name == kMetricToken) {
126 expected_samples_.resize(kMetricTokenSize, 0);
127 } else if (metric_name == kMetricPolicy) {
128 expected_samples_.resize(kMetricPolicySize, 0);
129 } else {
130 NOTREACHED();
131 }
132 }
133
134 // Run pending tasks, and check that no unexpected samples were recorded.
135 virtual void TearDown() OVERRIDE {
136 RunAllPending();
137 EXPECT_TRUE(CheckSamples());
138 }
139
140 const FilePath& temp_dir() {
141 return temp_dir_.path();
142 }
143
144 MessageLoop* loop() {
145 return &loop_;
146 }
147
148 void RunAllPending() {
149 loop_.RunAllPending();
150 }
151
152 // Adds |sample| to the list of expected samples. Subsequent calls of
153 // CheckSamples() will expect this sample.
154 void ExpectSample(int sample) {
155 ASSERT_FALSE(metric_name_.empty());
156 ASSERT_GE(sample, 0);
157 ASSERT_LT(sample, (int) expected_samples_.size());
158 expected_samples_[sample]++;
159 }
160
161 // Checks the current recorded samples against the expected set. Returns
162 // true if they match.
163 bool CheckSamples() {
164 EXPECT_FALSE(metric_name_.empty());
165 if (metric_name_.empty())
166 return false;
167 bool expects_samples = false;
168 for (size_t i = 0; i < expected_samples_.size(); ++i) {
169 if (expected_samples_[i] > 0) {
170 expects_samples = true;
171 break;
172 }
173 }
174 base::Histogram* histogram = NULL;
175 bool found = base::StatisticsRecorder::FindHistogram(metric_name_,
176 &histogram);
gfeher 2011/07/20 11:56:22 What do you think about the following? found = fou
Joao da Silva 2011/07/20 15:23:22 Less code is better code! Done.
177 // The histogram won't be available until the first sample is measured.
178 if (!expects_samples) {
179 EXPECT_FALSE(found);
180 return !found;
181 } else {
182 EXPECT_TRUE(found);
183 if (!found)
184 return false;
185 EXPECT_TRUE(histogram != NULL);
186 if (histogram == NULL)
187 return false;
188 }
189
190 base::Histogram::SampleSet samples;
191 histogram->SnapshotSample(&samples);
192
193 bool result = true;
194 size_t sum = 0;
gfeher 2011/07/20 11:56:22 Using signed ints is preferred, unless you really
Joao da Silva 2011/07/20 15:23:22 Done.
195 for (size_t i = 0; i < expected_samples_.size(); ++i) {
196 EXPECT_EQ(expected_samples_[i], samples.counts(i)) << "i is " << i;
gfeher 2011/07/20 11:56:22 Please either print a bit more verbose error messa
Joao da Silva 2011/07/20 15:23:22 Done.
197 if (expected_samples_[i] != samples.counts(i))
198 result = false;
199 sum += expected_samples_[i];
200 }
201 EXPECT_EQ(sum, (size_t) samples.TotalCount());
202 if (sum != (size_t) samples.TotalCount())
203 result = false;
204 return result;
205 }
206
207 private:
208 base::StatisticsRecorder statistics_recorder_;
gfeher 2011/07/20 11:56:22 I don't see you using this. Is it something that d
Joao da Silva 2011/07/20 15:23:22 Yes, the ctor initializes the internal static memb
209 MessageLoop loop_;
210 BrowserThread ui_thread_;
211 BrowserThread file_thread_;
212 // |metric_name_| is the UMA counter that is being tested. It must be set
213 // before any calls to ExpectSample or CheckSamples.
214 std::string metric_name_;
215 // List of expected samples.
216 std::vector<int> expected_samples_;
217 ScopedTempDir temp_dir_;
218
219 DISALLOW_COPY_AND_ASSIGN(EnterpriseMetricsTest);
220 };
221
222 TEST_F(EnterpriseMetricsTest, TokenFetchRequestFail) {
223 SetMetricName(kMetricToken);
224 DeviceManagementBackendTestHelper helper(loop());
225
226 helper.ExpectStartJob(net::URLRequestStatus::FAILED, -1, std::string());
227 ExpectSample(kMetricTokenFetchRequested);
228 ExpectSample(kMetricTokenFetchRequestFailed);
229 helper.ProcessRegisterRequest();
230 EXPECT_TRUE(helper.VerifyAndClearExpectations());
231 EXPECT_TRUE(CheckSamples());
232 }
233
234 TEST_F(EnterpriseMetricsTest, TokenFetchInvalidData) {
235 SetMetricName(kMetricToken);
236 DeviceManagementBackendTestHelper helper(loop());
237
238 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS, 200, "\xff");
239 ExpectSample(kMetricTokenFetchRequested);
240 ExpectSample(kMetricTokenFetchBadResponse);
241 helper.ProcessRegisterRequest();
242 EXPECT_TRUE(helper.VerifyAndClearExpectations());
243 EXPECT_TRUE(CheckSamples());
244 }
245
246 TEST_F(EnterpriseMetricsTest, TokenFetchErrors) {
247 SetMetricName(kMetricToken);
248 DeviceManagementBackendTestHelper helper(loop());
249
250 struct {
251 int error_code;
252 MetricToken sample;
253 } cases[] = {
254 { 400, kMetricTokenFetchRequestFailed },
255 { 401, kMetricTokenFetchServerFailed },
256 { 403, kMetricTokenFetchManagementNotSupported },
257 { 404, kMetricTokenFetchServerFailed },
258 { 410, kMetricTokenFetchDeviceNotFound },
259 { 412, kMetricTokenFetchServerFailed },
260 { 500, kMetricTokenFetchServerFailed },
261 { 503, kMetricTokenFetchServerFailed },
262 { 902, kMetricTokenFetchServerFailed },
263 { 491, kMetricTokenFetchServerFailed },
264 { 901, kMetricTokenFetchDeviceNotFound },
265 };
266
267 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
268 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS,
269 cases[i].error_code, std::string());
270 ExpectSample(kMetricTokenFetchRequested);
271 ExpectSample(cases[i].sample);
272 helper.ProcessRegisterRequest();
273 EXPECT_TRUE(helper.VerifyAndClearExpectations());
274 EXPECT_TRUE(CheckSamples());
275 }
276 }
277
278 TEST_F(EnterpriseMetricsTest, TokenFetchReceiveResponse) {
279 SetMetricName(kMetricToken);
280 DeviceManagementBackendTestHelper helper(loop());
281
282 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS, 200, std::string());
283 ExpectSample(kMetricTokenFetchRequested);
284 ExpectSample(kMetricTokenFetchResponseReceived);
285 helper.ProcessRegisterRequest();
286 EXPECT_TRUE(helper.VerifyAndClearExpectations());
287 EXPECT_TRUE(CheckSamples());
288 }
289
290 TEST_F(EnterpriseMetricsTest, TokenFetchOK) {
291 SetMetricName(kMetricToken);
292 DeviceManagementBackendTestHelper helper(loop());
293
294 // Test token fetcher.
295 UserPolicyCache cache(temp_dir().AppendASCII("FetchTokenTest"));
296 scoped_ptr<CloudPolicyDataStore> data_store;
297 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
298 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
299 "fake_auth_token", true);
300 PolicyNotifier notifier;
301 DeviceTokenFetcher fetcher(&helper.service(), &cache, data_store.get(),
302 &notifier);
303
304 MockCloudPolicyDataStoreObserver observer;
305 data_store->AddObserver(&observer);
306 EXPECT_CALL(observer, OnDeviceTokenChanged()).Times(1);
307
308 std::string data;
309 em::DeviceManagementResponse response;
310 response.mutable_register_response()->set_device_management_token("token");
311 response.SerializeToString(&data);
312 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS, 200, data);
313
314 // FetchToken() will reset the backend. Make sure it does the right thing.
315 helper.UnmockCreateBackend();
316
317 fetcher.FetchToken();
318
319 ExpectSample(kMetricTokenFetchRequested);
320 ExpectSample(kMetricTokenFetchResponseReceived);
321 ExpectSample(kMetricTokenFetchOK);
322 EXPECT_TRUE(helper.VerifyAndClearExpectations());
323 EXPECT_TRUE(CheckSamples());
324
325 // Cleanup.
326 data_store->RemoveObserver(&observer);
327 }
328
329 TEST_F(EnterpriseMetricsTest, TokenStorage) {
330 SetMetricName(kMetricToken);
331
332 FilePath path = temp_dir().AppendASCII("StoreTokenTest");
333
334 scoped_ptr<CloudPolicyDataStore> data_store;
335 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
336 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
337 "fake_auth_token", false);
338 UserPolicyTokenCache cache(data_store.get(), path);
339
340 // Try loading a non-existing file first.
341 cache.Load();
342 RunAllPending();
343 // No samples expected.
344 EXPECT_TRUE(CheckSamples());
345
346 // Try loading an invalid file.
347 std::string data("\xff");
348 int result = file_util::WriteFile(path, data.c_str(), data.size());
349 ASSERT_EQ((int) data.size(), result);
350
351 // Make the data store expect a load from cache again.
352 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
353 "fake_auth_token", false);
354 cache.Load();
355 RunAllPending();
356 ExpectSample(kMetricTokenLoadFailed);
357 EXPECT_TRUE(CheckSamples());
358
359 // Test storing a valid cache.
360 data_store->SetupForTesting("token", "fake_device_id", "fake_user_name",
361 "fake_auth_token", false);
362 cache.OnDeviceTokenChanged();
363 RunAllPending();
364 ExpectSample(kMetricTokenStoreSucceeded);
365 EXPECT_TRUE(CheckSamples());
366
367 // Test loading a valid cache.
368 // Make the data store expect a load from cache again.
369 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
370 "fake_auth_token", false);
371 cache.Load();
372 RunAllPending();
373 ExpectSample(kMetricTokenLoadSucceeded);
374 EXPECT_TRUE(CheckSamples());
375 }
376
377 TEST_F(EnterpriseMetricsTest, PolicyFetchRequestFails) {
378 SetMetricName(kMetricPolicy);
379 DeviceManagementBackendTestHelper helper(loop());
380
381 helper.ExpectStartJob(net::URLRequestStatus::FAILED, -1, std::string());
382 ExpectSample(kMetricPolicyFetchRequested);
383 ExpectSample(kMetricPolicyFetchRequestFailed);
384 helper.ProcessPolicyRequest();
385 EXPECT_TRUE(helper.VerifyAndClearExpectations());
386 EXPECT_TRUE(CheckSamples());
387 }
388
389 TEST_F(EnterpriseMetricsTest, PolicyFetchInvalidData) {
390 SetMetricName(kMetricPolicy);
391 DeviceManagementBackendTestHelper helper(loop());
392
393 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS, 200, "\xff");
394 ExpectSample(kMetricPolicyFetchRequested);
395 ExpectSample(kMetricPolicyFetchBadResponse);
396 helper.ProcessPolicyRequest();
397 EXPECT_TRUE(helper.VerifyAndClearExpectations());
398 EXPECT_TRUE(CheckSamples());
399 }
400
401 TEST_F(EnterpriseMetricsTest, PolicyFetchErrors) {
402 SetMetricName(kMetricPolicy);
403 DeviceManagementBackendTestHelper helper(loop());
404
405 struct {
406 int error_code;
407 MetricPolicy sample;
408 } cases[] = {
409 { 400, kMetricPolicyFetchRequestFailed },
410 { 401, kMetricPolicyFetchInvalidToken },
411 { 403, kMetricPolicyFetchServerFailed },
412 { 404, kMetricPolicyFetchServerFailed },
413 { 410, kMetricPolicyFetchServerFailed },
414 { 412, kMetricPolicyFetchServerFailed },
415 { 500, kMetricPolicyFetchServerFailed },
416 { 503, kMetricPolicyFetchServerFailed },
417 { 902, kMetricPolicyFetchNotFound },
418 { 491, kMetricPolicyFetchServerFailed },
419 { 901, kMetricPolicyFetchServerFailed },
420 };
421
422 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
423 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS, cases[i].error_code,
424 std::string());
425 ExpectSample(kMetricPolicyFetchRequested);
426 ExpectSample(cases[i].sample);
427 helper.ProcessPolicyRequest();
428 EXPECT_TRUE(helper.VerifyAndClearExpectations());
429 EXPECT_TRUE(CheckSamples());
430 }
431 }
432
433 TEST_F(EnterpriseMetricsTest, PolicyFetchReceiveResponse) {
434 SetMetricName(kMetricPolicy);
435 DeviceManagementBackendTestHelper helper(loop());
436
437 helper.ExpectStartJob(net::URLRequestStatus::SUCCESS, 200, std::string());
438 ExpectSample(kMetricPolicyFetchRequested);
439 ExpectSample(kMetricPolicyFetchResponseReceived);
440 helper.ProcessPolicyRequest();
441 EXPECT_TRUE(helper.VerifyAndClearExpectations());
442 EXPECT_TRUE(CheckSamples());
443 }
444
445 TEST_F(EnterpriseMetricsTest, PolicyFetchInvalidPolicy) {
446 SetMetricName(kMetricPolicy);
447
448 UserPolicyCache cache(temp_dir().AppendASCII("UserPolicyCacheTest"));
449 UserPolicyDiskCache::Delegate* cache_as_delegate =
450 implicit_cast<UserPolicyDiskCache::Delegate*>(&cache);
451
452 em::CachedCloudPolicyResponse response;
453 response.mutable_cloud_policy()->set_policy_data("\xff");
454 cache_as_delegate->OnDiskCacheLoaded(response);
455 ExpectSample(kMetricPolicyFetchInvalidPolicy);
456 EXPECT_TRUE(CheckSamples());
457 }
458
459 TEST_F(EnterpriseMetricsTest, PolicyFetchTimestampInFuture) {
460 SetMetricName(kMetricPolicy);
461
462 UserPolicyCache cache(temp_dir().AppendASCII("UserPolicyCacheTest"));
463 UserPolicyDiskCache::Delegate* cache_as_delegate =
464 implicit_cast<UserPolicyDiskCache::Delegate*>(&cache);
465
466 std::string data;
467 em::PolicyData policy_data;
468 base::TimeDelta timestamp =
469 (base::Time::NowFromSystemTime() + base::TimeDelta::FromDays(1000)) -
470 base::Time::UnixEpoch();
471 policy_data.set_timestamp(timestamp.InMilliseconds());
472 policy_data.SerializeToString(&data);
473 em::CachedCloudPolicyResponse response;
474 response.mutable_cloud_policy()->set_policy_data(data);
475 cache_as_delegate->OnDiskCacheLoaded(response);
476 ExpectSample(kMetricPolicyFetchTimestampInFuture);
477 EXPECT_TRUE(CheckSamples());
478 }
479
480 TEST_F(EnterpriseMetricsTest, PolicyFetchNotModified) {
481 SetMetricName(kMetricPolicy);
482
483 UserPolicyCache cache(temp_dir().AppendASCII("UserPolicyCacheTest"));
484 UserPolicyDiskCache::Delegate* cache_as_delegate =
485 implicit_cast<UserPolicyDiskCache::Delegate*>(&cache);
486
487 std::string data;
488 em::PolicyData policy_data;
489 policy_data.set_timestamp(0);
490 policy_data.SerializeToString(&data);
491 em::CachedCloudPolicyResponse response;
492 response.mutable_cloud_policy()->set_policy_data(data);
493 cache_as_delegate->OnDiskCacheLoaded(response);
494 ExpectSample(kMetricPolicyFetchNotModified);
495 EXPECT_TRUE(CheckSamples());
496 }
497
498 TEST_F(EnterpriseMetricsTest, PolicyFetchOK) {
499 SetMetricName(kMetricPolicy);
500
501 UserPolicyCache cache(temp_dir().AppendASCII("UserPolicyCacheTest"));
502
503 std::string data;
504 em::PolicyData policy_data;
505 policy_data.set_timestamp(0);
506 policy_data.SerializeToString(&data);
507 em::CachedCloudPolicyResponse response;
508 cache.SetPolicy(response.cloud_policy());
509 ExpectSample(kMetricPolicyFetchOK);
510 ExpectSample(kMetricPolicyFetchNotModified);
511 EXPECT_TRUE(CheckSamples());
512 // This also triggers a store. Update the expected samples.
513 RunAllPending();
514 ExpectSample(kMetricPolicyStoreSucceeded);
515 EXPECT_TRUE(CheckSamples());
516 }
517
518 TEST_F(EnterpriseMetricsTest, PolicyFetchBadResponse) {
519 SetMetricName(kMetricPolicy);
520
521 UserPolicyCache cache(temp_dir().AppendASCII("UserPolicyCacheTest"));
522 PolicyNotifier notifier;
523 scoped_ptr<CloudPolicyDataStore> data_store;
524 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
525 data_store->SetupForTesting("", "fake_device_id", "fake_user_name",
526 "fake_auth_token", true);
527 CloudPolicyController controller(NULL, &cache, NULL, data_store.get(),
528 &notifier);
529 em::DevicePolicyResponse device_policy_response;
530 controller.HandlePolicyResponse(device_policy_response);
531 ExpectSample(kMetricPolicyFetchBadResponse);
532 EXPECT_TRUE(CheckSamples());
533
534 // More bad responses.
535 em::PolicyFetchResponse* policy_fetch_response =
536 device_policy_response.add_response();
537 policy_fetch_response->set_error_code(
538 DeviceManagementBackend::kErrorServicePolicyNotFound);
539 controller.HandlePolicyResponse(device_policy_response);
540 ExpectSample(kMetricPolicyFetchBadResponse);
541 EXPECT_TRUE(CheckSamples());
542 }
543
544 TEST_F(EnterpriseMetricsTest, PolicyStorage) {
545 SetMetricName(kMetricPolicy);
546
547 FilePath path = temp_dir().AppendASCII("UserPolicyDiskCacheTest");
548
549 scoped_refptr<UserPolicyDiskCache> cache(
550 new UserPolicyDiskCache(base::WeakPtr<UserPolicyDiskCache::Delegate>(),
551 path));
552
553 // Load empty cache.
554 cache->Load();
555 RunAllPending();
556 // No samples expected.
557 EXPECT_TRUE(CheckSamples());
558
559 // Load an invalid cache.
560 std::string data("\xff");
561 int result = file_util::WriteFile(path, data.c_str(), data.size());
562 ASSERT_EQ((int) data.size(), result);
563
564 cache->Load();
565 RunAllPending();
566 ExpectSample(kMetricPolicyLoadFailed);
567 EXPECT_TRUE(CheckSamples());
568
569 // Store a cache.
570 em::CachedCloudPolicyResponse response;
571 cache->Store(response);
572 RunAllPending();
573 ExpectSample(kMetricPolicyStoreSucceeded);
574 EXPECT_TRUE(CheckSamples());
575
576 // Load a good cache.
577 cache->Load();
578 RunAllPending();
579 ExpectSample(kMetricPolicyLoadSucceeded);
580 EXPECT_TRUE(CheckSamples());
581 }
582
583 #if defined(OS_CHROMEOS)
584
585 namespace {
586
587 // Wrapper around an instance of EnterpriseInstallAttributes that uses a
588 // mock CryptohomeLibrary. The wrapped EnterpriseInstallAttributes instance
589 // is expected to be used to load the attributes once.
590 class TestInstallAttributes {
591 public:
592 // |user| is the user to be returned as the value of the "enterprise.user"
593 // attribute.
594 explicit TestInstallAttributes(const std::string& user)
595 : user_(user),
596 owned_("true"),
597 install_attributes_(&mock_cryptohome_library_) {}
598
599 void ExpectUsage() {
600 EXPECT_CALL(mock_cryptohome_library_, InstallAttributesIsReady())
601 .WillOnce(Return(true));
602 EXPECT_CALL(mock_cryptohome_library_, InstallAttributesIsInvalid())
603 .WillOnce(Return(false));
604 EXPECT_CALL(mock_cryptohome_library_, InstallAttributesIsFirstInstall())
605 .WillOnce(Return(false));
606 EXPECT_CALL(mock_cryptohome_library_,
607 InstallAttributesGet("enterprise.owned", _))
608 .WillOnce(DoAll(SetArgumentPointee<1>(owned_),
gfeher 2011/07/20 11:56:22 Nit: SetArgumentPointee seems to be deprected, ple
Joao da Silva 2011/07/20 15:23:22 Didn't notice in the docs, good catch. Done.
609 Return(true)));
610 EXPECT_CALL(mock_cryptohome_library_,
611 InstallAttributesGet("enterprise.user", _))
612 .WillOnce(DoAll(SetArgumentPointee<1>(user_),
gfeher 2011/07/20 11:56:22 Same here.
Joao da Silva 2011/07/20 15:23:22 Done.
613 Return(true)));
614 }
615
616 EnterpriseInstallAttributes* install_attributes() {
617 return &install_attributes_;
618 }
619
620 private:
621 std::string user_;
622 std::string owned_;
623 chromeos::MockCryptohomeLibrary mock_cryptohome_library_;
624 EnterpriseInstallAttributes install_attributes_;
625
626 DISALLOW_COPY_AND_ASSIGN(TestInstallAttributes);
627 };
628
629 } // namespace
630
631 // Helper for tests that use a DevicePolicyCache.
632 class DevicePolicyCacheTestHelper {
633 public:
634 DevicePolicyCacheTestHelper()
635 : install_attributes_("user") {
636 Init();
637 }
638
639 explicit DevicePolicyCacheTestHelper(const std::string& user)
640 : install_attributes_(user) {
641 Init();
642 }
643
644 void CompleteRetrieve(chromeos::SignedSettings::ReturnCode code) {
645 device_policy_cache_->OnRetrievePolicyCompleted(code, response_);
646 }
647
648 void SetPolicy() {
649 device_policy_cache_->SetPolicy(response_);
650 }
651
652 void SetData(const std::string& data) {
653 response_.set_policy_data(data);
654 }
655
656 void SetGoodData() {
657 em::PolicyData policy_data;
658 policy_data.set_request_token("token");
659 policy_data.set_username("user");
660 policy_data.set_device_id("device_id");
661 std::string data;
662 policy_data.SerializeToString(&data);
663 response_.set_policy_data(data);
664 }
665
666 void ExpectInstallAttributes() {
667 install_attributes_.ExpectUsage();
668 }
669
670 void ExpectMockSignedSettings(chromeos::SignedSettings::ReturnCode code,
671 int expected_retrieves) {
672 install_attributes_.ExpectUsage();
673 EXPECT_CALL(mock_signed_settings_helper_, StartStorePolicyOp(_, _))
674 .WillOnce(MockSignedSettingsHelperStorePolicy(code));
675 EXPECT_CALL(mock_signed_settings_helper_, CancelCallback(_))
676 .Times(1)
677 .RetiresOnSaturation();
678 EXPECT_CALL(mock_signed_settings_helper_,
679 StartRetrievePolicyOp(_)).Times(expected_retrieves);
680 }
681
682 const em::PolicyFetchResponse& response() {
683 return response_;
684 }
685
686 private:
687 void Init() {
688 data_store_.reset(CloudPolicyDataStore::CreateForUserPolicies());
689 device_policy_cache_.reset(new DevicePolicyCache(data_store_.get(),
690 install_attributes_.install_attributes(),
691 &mock_signed_settings_helper_));
692 data_store_->SetupForTesting("", "id", "user", "token", false);
gfeher 2011/07/20 11:56:22 Über-nit: "token" -> "gaia_token" And at all the s
Joao da Silva 2011/07/20 15:23:22 Über-done!
693 EXPECT_CALL(mock_signed_settings_helper_, CancelCallback(_)).Times(1);
694 }
695
696 chromeos::MockSignedSettingsHelper mock_signed_settings_helper_;
697 scoped_ptr<CloudPolicyDataStore> data_store_;
698 scoped_ptr<DevicePolicyCache> device_policy_cache_;
699 em::PolicyFetchResponse response_;
700 TestInstallAttributes install_attributes_;
701
702 DISALLOW_COPY_AND_ASSIGN(DevicePolicyCacheTestHelper);
703 };
704
705 TEST_F(EnterpriseMetricsTest, DevicePolicyNotFound) {
706 SetMetricName(kMetricPolicy);
707 DevicePolicyCacheTestHelper helper;
708
709 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
710 // No samples expected.
711 EXPECT_TRUE(CheckSamples());
712 }
713
714 TEST_F(EnterpriseMetricsTest, DevicePolicyBadData) {
715 SetMetricName(kMetricPolicy);
716 DevicePolicyCacheTestHelper helper;
717
718 helper.SetData("\xff");
719 helper.CompleteRetrieve(chromeos::SignedSettings::SUCCESS);
720 ExpectSample(kMetricPolicyLoadFailed);
721 EXPECT_TRUE(CheckSamples());
722 }
723
724 TEST_F(EnterpriseMetricsTest, DevicePolicyMoreBadData) {
725 SetMetricName(kMetricPolicy);
726 DevicePolicyCacheTestHelper helper;
727
728 em::PolicyData policy_data;
729 policy_data.set_request_token("token");
730 std::string data;
731 policy_data.SerializeToString(&data);
732 helper.SetData(data);
733 helper.CompleteRetrieve(chromeos::SignedSettings::SUCCESS);
734 ExpectSample(kMetricPolicyLoadFailed);
735 EXPECT_TRUE(CheckSamples());
736 }
737
738 TEST_F(EnterpriseMetricsTest, DevicePolicyLoad) {
739 SetMetricName(kMetricPolicy);
740 DevicePolicyCacheTestHelper helper;
741
742 helper.SetGoodData();
743 helper.CompleteRetrieve(chromeos::SignedSettings::SUCCESS);
744 ExpectSample(kMetricPolicyLoadSucceeded);
745 ExpectSample(kMetricPolicyFetchNotModified);
746 EXPECT_TRUE(CheckSamples());
747 }
748
749 TEST_F(EnterpriseMetricsTest, DevicePolicyStoreSuccess) {
750 SetMetricName(kMetricPolicy);
751 DevicePolicyCacheTestHelper helper;
752 helper.ExpectMockSignedSettings(chromeos::SignedSettings::SUCCESS, 1);
753 helper.SetGoodData();
754 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
755 helper.SetPolicy();
756 ExpectSample(kMetricPolicyStoreSucceeded);
757 EXPECT_TRUE(CheckSamples());
758 }
759
760 TEST_F(EnterpriseMetricsTest, DevicePolicyStoreBadSignature) {
761 SetMetricName(kMetricPolicy);
762 DevicePolicyCacheTestHelper helper;
763 helper.ExpectMockSignedSettings(chromeos::SignedSettings::BAD_SIGNATURE, 0);
764 helper.SetGoodData();
765 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
766 helper.SetPolicy();
767 ExpectSample(kMetricPolicyStoreFailed);
768 ExpectSample(kMetricPolicyFetchBadSignature);
769 EXPECT_TRUE(CheckSamples());
770 }
771
772 TEST_F(EnterpriseMetricsTest, DevicePolicyStoreOperationFailed) {
773 SetMetricName(kMetricPolicy);
774 DevicePolicyCacheTestHelper helper;
775 helper.ExpectMockSignedSettings(chromeos::SignedSettings::OPERATION_FAILED,
776 0);
777 helper.SetGoodData();
778 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
779 helper.SetPolicy();
780 ExpectSample(kMetricPolicyStoreFailed);
781 ExpectSample(kMetricPolicyFetchOtherFailed);
782 EXPECT_TRUE(CheckSamples());
783 }
784
785 TEST_F(EnterpriseMetricsTest, DevicePolicyNonEnterprise) {
786 SetMetricName(kMetricPolicy);
787 DevicePolicyCacheTestHelper helper;
788
789 scoped_ptr<CloudPolicyDataStore> data_store;
790 data_store.reset(CloudPolicyDataStore::CreateForUserPolicies());
791 EnterpriseInstallAttributes install_attributes(NULL);
792 DevicePolicyCache device_policy_cache(data_store.get(), &install_attributes);
793
794 data_store->SetupForTesting("", "id", "user", "token", false);
795 helper.SetGoodData();
796 device_policy_cache.OnRetrievePolicyCompleted(
797 chromeos::SignedSettings::NOT_FOUND, helper.response());
798
799 device_policy_cache.SetPolicy(helper.response());
800 ExpectSample(kMetricPolicyFetchNonEnterpriseDevice);
801 EXPECT_TRUE(CheckSamples());
802 }
803
804 TEST_F(EnterpriseMetricsTest, DevicePolicyUserMismatch) {
805 SetMetricName(kMetricPolicy);
806 DevicePolicyCacheTestHelper helper("bogus");
807 helper.ExpectInstallAttributes();
808 helper.SetGoodData();
809 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
810 helper.SetPolicy();
811 ExpectSample(kMetricPolicyFetchUserMismatch);
812 EXPECT_TRUE(CheckSamples());
813 }
814
815 TEST_F(EnterpriseMetricsTest, DevicePolicyBadSignature) {
816 SetMetricName(kMetricPolicy);
817 DevicePolicyCacheTestHelper helper;
818 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
819 helper.CompleteRetrieve(chromeos::SignedSettings::BAD_SIGNATURE);
820 ExpectSample(kMetricPolicyFetchBadSignature);
821 EXPECT_TRUE(CheckSamples());
822 }
823
824 TEST_F(EnterpriseMetricsTest, DevicePolicyOtherFailed) {
825 SetMetricName(kMetricPolicy);
826 DevicePolicyCacheTestHelper helper;
827 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
828 helper.CompleteRetrieve(chromeos::SignedSettings::OPERATION_FAILED);
829 ExpectSample(kMetricPolicyFetchOtherFailed);
830 EXPECT_TRUE(CheckSamples());
831 }
832
833 TEST_F(EnterpriseMetricsTest, DevicePolicyFetchInvalid) {
834 SetMetricName(kMetricPolicy);
835 DevicePolicyCacheTestHelper helper;
836
837 helper.ExpectInstallAttributes();
838 helper.CompleteRetrieve(chromeos::SignedSettings::NOT_FOUND);
839 helper.SetData("\xff");
840 helper.SetPolicy();
841 ExpectSample(kMetricPolicyFetchInvalidPolicy);
842 EXPECT_TRUE(CheckSamples());
843 }
844
845 #endif
846
847 } // namespace policy
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698