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

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

Powered by Google App Engine
This is Rietveld 408576698