• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "update_engine/update_attempter.h"
18 
19 #include <stdint.h>
20 
21 #include <memory>
22 
23 #include <base/files/file_util.h>
24 #include <base/message_loop/message_loop.h>
25 #include <brillo/message_loops/base_message_loop.h>
26 #include <brillo/message_loops/message_loop.h>
27 #include <brillo/message_loops/message_loop_utils.h>
28 #include <gtest/gtest.h>
29 #include <policy/libpolicy.h>
30 #include <policy/mock_device_policy.h>
31 #include <policy/mock_libpolicy.h>
32 
33 #include "update_engine/common/dlcservice_interface.h"
34 #include "update_engine/common/fake_clock.h"
35 #include "update_engine/common/fake_prefs.h"
36 #include "update_engine/common/mock_action.h"
37 #include "update_engine/common/mock_action_processor.h"
38 #include "update_engine/common/mock_http_fetcher.h"
39 #include "update_engine/common/mock_prefs.h"
40 #include "update_engine/common/platform_constants.h"
41 #include "update_engine/common/prefs.h"
42 #include "update_engine/common/test_utils.h"
43 #include "update_engine/common/utils.h"
44 #include "update_engine/fake_system_state.h"
45 #include "update_engine/mock_p2p_manager.h"
46 #include "update_engine/mock_payload_state.h"
47 #include "update_engine/mock_service_observer.h"
48 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
49 #include "update_engine/payload_consumer/install_plan.h"
50 #include "update_engine/payload_consumer/payload_constants.h"
51 #include "update_engine/payload_consumer/postinstall_runner_action.h"
52 #include "update_engine/update_boot_flags_action.h"
53 
54 using base::Time;
55 using base::TimeDelta;
56 using chromeos_update_manager::EvalStatus;
57 using chromeos_update_manager::StagingSchedule;
58 using chromeos_update_manager::UpdateCheckParams;
59 using policy::DevicePolicy;
60 using std::string;
61 using std::unique_ptr;
62 using std::vector;
63 using testing::_;
64 using testing::DoAll;
65 using testing::Field;
66 using testing::InSequence;
67 using testing::Ne;
68 using testing::NiceMock;
69 using testing::Pointee;
70 using testing::Property;
71 using testing::Return;
72 using testing::ReturnPointee;
73 using testing::ReturnRef;
74 using testing::SaveArg;
75 using testing::SetArgPointee;
76 using update_engine::UpdateAttemptFlags;
77 using update_engine::UpdateEngineStatus;
78 using update_engine::UpdateStatus;
79 
80 namespace chromeos_update_engine {
81 
82 namespace {
83 
84 class MockDlcService : public DlcServiceInterface {
85  public:
86   MOCK_METHOD1(GetInstalled, bool(vector<string>*));
87 };
88 
89 }  // namespace
90 
91 const char kRollbackVersion[] = "10575.39.2";
92 
93 // Test a subclass rather than the main class directly so that we can mock out
94 // methods within the class. There're explicit unit tests for the mocked out
95 // methods.
96 class UpdateAttempterUnderTest : public UpdateAttempter {
97  public:
UpdateAttempterUnderTest(SystemState * system_state)98   explicit UpdateAttempterUnderTest(SystemState* system_state)
99       : UpdateAttempter(system_state, nullptr) {}
100 
101   // Wrap the update scheduling method, allowing us to opt out of scheduled
102   // updates for testing purposes.
ScheduleUpdates()103   bool ScheduleUpdates() override {
104     schedule_updates_called_ = true;
105     if (do_schedule_updates_) {
106       UpdateAttempter::ScheduleUpdates();
107     } else {
108       LOG(INFO) << "[TEST] Update scheduling disabled.";
109     }
110     return true;
111   }
EnableScheduleUpdates()112   void EnableScheduleUpdates() { do_schedule_updates_ = true; }
DisableScheduleUpdates()113   void DisableScheduleUpdates() { do_schedule_updates_ = false; }
114 
115   // Indicates whether ScheduleUpdates() was called.
schedule_updates_called() const116   bool schedule_updates_called() const { return schedule_updates_called_; }
117 
118   // Need to expose forced_omaha_url_ so we can test it.
forced_omaha_url() const119   const string& forced_omaha_url() const { return forced_omaha_url_; }
120 
121  private:
122   bool schedule_updates_called_ = false;
123   bool do_schedule_updates_ = true;
124 };
125 
126 class UpdateAttempterTest : public ::testing::Test {
127  protected:
UpdateAttempterTest()128   UpdateAttempterTest()
129       : certificate_checker_(fake_system_state_.mock_prefs(),
130                              &openssl_wrapper_) {
131     // Override system state members.
132     fake_system_state_.set_connection_manager(&mock_connection_manager);
133     fake_system_state_.set_update_attempter(&attempter_);
134     fake_system_state_.set_dlcservice(&mock_dlcservice_);
135     loop_.SetAsCurrent();
136 
137     certificate_checker_.Init();
138 
139     attempter_.set_forced_update_pending_callback(
140         new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
141     // Finish initializing the attempter.
142     attempter_.Init();
143   }
144 
SetUp()145   void SetUp() override {
146     EXPECT_NE(nullptr, attempter_.system_state_);
147     EXPECT_EQ(0, attempter_.http_response_code_);
148     EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
149     EXPECT_EQ(0.0, attempter_.download_progress_);
150     EXPECT_EQ(0, attempter_.last_checked_time_);
151     EXPECT_EQ("0.0.0.0", attempter_.new_version_);
152     EXPECT_EQ(0ULL, attempter_.new_payload_size_);
153     processor_ = new NiceMock<MockActionProcessor>();
154     attempter_.processor_.reset(processor_);  // Transfers ownership.
155     prefs_ = fake_system_state_.mock_prefs();
156 
157     // Set up store/load semantics of P2P properties via the mock PayloadState.
158     actual_using_p2p_for_downloading_ = false;
159     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
160                 SetUsingP2PForDownloading(_))
161         .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
162     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
163                 GetUsingP2PForDownloading())
164         .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
165     actual_using_p2p_for_sharing_ = false;
166     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
167                 SetUsingP2PForSharing(_))
168         .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
169     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
170                 GetUsingP2PForDownloading())
171         .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
172   }
173 
174  public:
175   void ScheduleQuitMainLoop();
176 
177   // Callbacks to run the different tests from the main loop.
178   void UpdateTestStart();
179   void UpdateTestVerify();
180   void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
181   void RollbackTestVerify();
182   void PingOmahaTestStart();
183   void ReadScatterFactorFromPolicyTestStart();
184   void DecrementUpdateCheckCountTestStart();
185   void NoScatteringDoneDuringManualUpdateTestStart();
186   void P2PNotEnabledStart();
187   void P2PEnabledStart();
188   void P2PEnabledInteractiveStart();
189   void P2PEnabledStartingFailsStart();
190   void P2PEnabledHousekeepingFailsStart();
191   void ResetRollbackHappenedStart(bool is_consumer,
192                                   bool is_policy_available,
193                                   bool expected_reset);
194   // Staging related callbacks.
195   void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
196   void CheckStagingOff();
197   void StagingSetsPrefsAndTurnsOffScatteringStart();
198   void StagingOffIfInteractiveStart();
199   void StagingOffIfOobeStart();
200 
actual_using_p2p_for_downloading()201   bool actual_using_p2p_for_downloading() {
202     return actual_using_p2p_for_downloading_;
203   }
actual_using_p2p_for_sharing()204   bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
205 
206   base::MessageLoopForIO base_loop_;
207   brillo::BaseMessageLoop loop_{&base_loop_};
208 
209   FakeSystemState fake_system_state_;
210   UpdateAttempterUnderTest attempter_{&fake_system_state_};
211   OpenSSLWrapper openssl_wrapper_;
212   CertificateChecker certificate_checker_;
213   MockDlcService mock_dlcservice_;
214 
215   NiceMock<MockActionProcessor>* processor_;
216   NiceMock<MockPrefs>* prefs_;  // Shortcut to fake_system_state_->mock_prefs().
217   NiceMock<MockConnectionManager> mock_connection_manager;
218 
219   bool actual_using_p2p_for_downloading_;
220   bool actual_using_p2p_for_sharing_;
221 };
222 
ScheduleQuitMainLoop()223 void UpdateAttempterTest::ScheduleQuitMainLoop() {
224   loop_.PostTask(
225       FROM_HERE,
226       base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
227                  base::Unretained(&loop_)));
228 }
229 
TEST_F(UpdateAttempterTest,ActionCompletedDownloadTest)230 TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
231   unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
232   fetcher->FailTransfer(503);  // Sets the HTTP response code.
233   DownloadAction action(prefs_,
234                         nullptr,
235                         nullptr,
236                         nullptr,
237                         fetcher.release(),
238                         false /* interactive */);
239   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
240   attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
241   EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
242   EXPECT_EQ(0.0, attempter_.download_progress_);
243   ASSERT_EQ(nullptr, attempter_.error_event_.get());
244 }
245 
TEST_F(UpdateAttempterTest,ActionCompletedErrorTest)246 TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
247   MockAction action;
248   EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
249   attempter_.status_ = UpdateStatus::DOWNLOADING;
250   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
251       .WillOnce(Return(false));
252   attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
253   ASSERT_NE(nullptr, attempter_.error_event_.get());
254 }
255 
TEST_F(UpdateAttempterTest,DownloadProgressAccumulationTest)256 TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
257   // Simple test case, where all the values match (nothing was skipped)
258   uint64_t bytes_progressed_1 = 1024 * 1024;  // 1MB
259   uint64_t bytes_progressed_2 = 1024 * 1024;  // 1MB
260   uint64_t bytes_received_1 = bytes_progressed_1;
261   uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
262   uint64_t bytes_total = 20 * 1024 * 1024;  // 20MB
263 
264   double progress_1 =
265       static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
266   double progress_2 =
267       static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
268 
269   EXPECT_EQ(0.0, attempter_.download_progress_);
270   // This is set via inspecting the InstallPlan payloads when the
271   // OmahaResponseAction is completed
272   attempter_.new_payload_size_ = bytes_total;
273   NiceMock<MockServiceObserver> observer;
274   EXPECT_CALL(observer,
275               SendStatusUpdate(AllOf(
276                   Field(&UpdateEngineStatus::progress, progress_1),
277                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
278                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
279   EXPECT_CALL(observer,
280               SendStatusUpdate(AllOf(
281                   Field(&UpdateEngineStatus::progress, progress_2),
282                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
283                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
284   attempter_.AddObserver(&observer);
285   attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
286   EXPECT_EQ(progress_1, attempter_.download_progress_);
287   // This iteration validates that a later set of updates to the variables are
288   // properly handled (so that |getStatus()| will return the same progress info
289   // as the callback is receiving.
290   attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
291   EXPECT_EQ(progress_2, attempter_.download_progress_);
292 }
293 
TEST_F(UpdateAttempterTest,ChangeToDownloadingOnReceivedBytesTest)294 TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
295   // The transition into UpdateStatus::DOWNLOADING happens when the
296   // first bytes are received.
297   uint64_t bytes_progressed = 1024 * 1024;    // 1MB
298   uint64_t bytes_received = 2 * 1024 * 1024;  // 2MB
299   uint64_t bytes_total = 20 * 1024 * 1024;    // 300MB
300   attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
301   // This is set via inspecting the InstallPlan payloads when the
302   // OmahaResponseAction is completed
303   attempter_.new_payload_size_ = bytes_total;
304   EXPECT_EQ(0.0, attempter_.download_progress_);
305   NiceMock<MockServiceObserver> observer;
306   EXPECT_CALL(observer,
307               SendStatusUpdate(AllOf(
308                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
309                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
310   attempter_.AddObserver(&observer);
311   attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
312   EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
313 }
314 
TEST_F(UpdateAttempterTest,BroadcastCompleteDownloadTest)315 TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
316   // There is a special case to ensure that at 100% downloaded,
317   // download_progress_ is updated and that value broadcast. This test confirms
318   // that.
319   uint64_t bytes_progressed = 0;              // ignored
320   uint64_t bytes_received = 5 * 1024 * 1024;  // ignored
321   uint64_t bytes_total = 5 * 1024 * 1024;     // 300MB
322   attempter_.status_ = UpdateStatus::DOWNLOADING;
323   attempter_.new_payload_size_ = bytes_total;
324   EXPECT_EQ(0.0, attempter_.download_progress_);
325   NiceMock<MockServiceObserver> observer;
326   EXPECT_CALL(observer,
327               SendStatusUpdate(AllOf(
328                   Field(&UpdateEngineStatus::progress, 1.0),
329                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
330                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
331   attempter_.AddObserver(&observer);
332   attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
333   EXPECT_EQ(1.0, attempter_.download_progress_);
334 }
335 
TEST_F(UpdateAttempterTest,ActionCompletedOmahaRequestTest)336 TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
337   unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
338   fetcher->FailTransfer(500);  // Sets the HTTP response code.
339   OmahaRequestAction action(
340       &fake_system_state_, nullptr, std::move(fetcher), false);
341   ObjectCollectorAction<OmahaResponse> collector_action;
342   BondActions(&action, &collector_action);
343   OmahaResponse response;
344   response.poll_interval = 234;
345   action.SetOutputObject(response);
346   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
347   attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
348   EXPECT_EQ(500, attempter_.http_response_code());
349   EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
350   EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
351   ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
352 }
353 
TEST_F(UpdateAttempterTest,ConstructWithUpdatedMarkerTest)354 TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
355   FakePrefs fake_prefs;
356   string boot_id;
357   EXPECT_TRUE(utils::GetBootId(&boot_id));
358   fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
359   fake_system_state_.set_prefs(&fake_prefs);
360   attempter_.Init();
361   EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
362 }
363 
TEST_F(UpdateAttempterTest,GetErrorCodeForActionTest)364 TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
365   EXPECT_EQ(ErrorCode::kSuccess,
366             GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
367 
368   FakeSystemState fake_system_state;
369   OmahaRequestAction omaha_request_action(
370       &fake_system_state, nullptr, nullptr, false);
371   EXPECT_EQ(ErrorCode::kOmahaRequestError,
372             GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
373   OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
374   EXPECT_EQ(
375       ErrorCode::kOmahaResponseHandlerError,
376       GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
377   FilesystemVerifierAction filesystem_verifier_action;
378   EXPECT_EQ(
379       ErrorCode::kFilesystemVerifierError,
380       GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
381   PostinstallRunnerAction postinstall_runner_action(
382       fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
383   EXPECT_EQ(
384       ErrorCode::kPostinstallRunnerError,
385       GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
386   MockAction action_mock;
387   EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
388   EXPECT_EQ(ErrorCode::kError,
389             GetErrorCodeForAction(&action_mock, ErrorCode::kError));
390 }
391 
TEST_F(UpdateAttempterTest,DisableDeltaUpdateIfNeededTest)392 TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
393   attempter_.omaha_request_params_->set_delta_okay(true);
394   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
395       .WillOnce(Return(false));
396   attempter_.DisableDeltaUpdateIfNeeded();
397   EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
398   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
399       .WillOnce(
400           DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
401                 Return(true)));
402   attempter_.DisableDeltaUpdateIfNeeded();
403   EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
404   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
405       .WillOnce(
406           DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
407                 Return(true)));
408   attempter_.DisableDeltaUpdateIfNeeded();
409   EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
410   EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
411   attempter_.DisableDeltaUpdateIfNeeded();
412   EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
413 }
414 
TEST_F(UpdateAttempterTest,MarkDeltaUpdateFailureTest)415 TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
416   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
417       .WillOnce(Return(false))
418       .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
419       .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
420       .WillOnce(
421           DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
422                 Return(true)));
423   EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
424       .WillRepeatedly(Return(true));
425   EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
426   EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
427   EXPECT_CALL(*prefs_,
428               SetInt64(kPrefsDeltaUpdateFailures,
429                        UpdateAttempter::kMaxDeltaUpdateFailures + 1));
430   for (int i = 0; i < 4; i++)
431     attempter_.MarkDeltaUpdateFailure();
432 }
433 
TEST_F(UpdateAttempterTest,ScheduleErrorEventActionNoEventTest)434 TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
435   EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
436   EXPECT_CALL(*processor_, StartProcessing()).Times(0);
437   EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
438       .Times(0);
439   OmahaResponse response;
440   string url1 = "http://url1";
441   response.packages.push_back({.payload_urls = {url1, "https://url"}});
442   EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
443       .WillRepeatedly(Return(url1));
444   fake_system_state_.mock_payload_state()->SetResponse(response);
445   attempter_.ScheduleErrorEventAction();
446   EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
447 }
448 
TEST_F(UpdateAttempterTest,ScheduleErrorEventActionTest)449 TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
450   EXPECT_CALL(*processor_,
451               EnqueueAction(Pointee(Property(
452                   &AbstractAction::Type, OmahaRequestAction::StaticType()))));
453   EXPECT_CALL(*processor_, StartProcessing());
454   ErrorCode err = ErrorCode::kError;
455   EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
456   attempter_.error_event_.reset(new OmahaEvent(
457       OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
458   attempter_.ScheduleErrorEventAction();
459   EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
460 }
461 
462 namespace {
463 // Actions that will be built as part of an update check.
464 const string kUpdateActionTypes[] = {  // NOLINT(runtime/string)
465     OmahaRequestAction::StaticType(),
466     OmahaResponseHandlerAction::StaticType(),
467     UpdateBootFlagsAction::StaticType(),
468     OmahaRequestAction::StaticType(),
469     DownloadAction::StaticType(),
470     OmahaRequestAction::StaticType(),
471     FilesystemVerifierAction::StaticType(),
472     PostinstallRunnerAction::StaticType(),
473     OmahaRequestAction::StaticType()};
474 
475 // Actions that will be built as part of a user-initiated rollback.
476 const string kRollbackActionTypes[] = {
477     // NOLINT(runtime/string)
478     InstallPlanAction::StaticType(),
479     PostinstallRunnerAction::StaticType(),
480 };
481 
482 const StagingSchedule kValidStagingSchedule = {
483     {4, 10}, {10, 40}, {19, 70}, {26, 100}};
484 
485 }  // namespace
486 
UpdateTestStart()487 void UpdateAttempterTest::UpdateTestStart() {
488   attempter_.set_http_response_code(200);
489 
490   // Expect that the device policy is loaded by the UpdateAttempter at some
491   // point by calling RefreshDevicePolicy.
492   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
493   EXPECT_CALL(*device_policy, LoadPolicy())
494       .Times(testing::AtLeast(1))
495       .WillRepeatedly(Return(true));
496   attempter_.policy_provider_.reset(
497       new policy::PolicyProvider(std::move(device_policy)));
498 
499   {
500     InSequence s;
501     for (size_t i = 0; i < arraysize(kUpdateActionTypes); ++i) {
502       EXPECT_CALL(*processor_,
503                   EnqueueAction(Pointee(
504                       Property(&AbstractAction::Type, kUpdateActionTypes[i]))));
505     }
506     EXPECT_CALL(*processor_, StartProcessing());
507   }
508 
509   attempter_.Update("", "", "", "", false, false, false);
510   loop_.PostTask(FROM_HERE,
511                  base::Bind(&UpdateAttempterTest::UpdateTestVerify,
512                             base::Unretained(this)));
513 }
514 
UpdateTestVerify()515 void UpdateAttempterTest::UpdateTestVerify() {
516   EXPECT_EQ(0, attempter_.http_response_code());
517   EXPECT_EQ(&attempter_, processor_->delegate());
518   EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
519   loop_.BreakLoop();
520 }
521 
RollbackTestStart(bool enterprise_rollback,bool valid_slot)522 void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
523                                             bool valid_slot) {
524   // Create a device policy so that we can change settings.
525   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
526   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
527   fake_system_state_.set_device_policy(device_policy.get());
528   if (enterprise_rollback) {
529     // We return an empty owner as this is an enterprise.
530     EXPECT_CALL(*device_policy, GetOwner(_))
531         .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
532   } else {
533     // We return a fake owner as this is an owned consumer device.
534     EXPECT_CALL(*device_policy, GetOwner(_))
535         .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
536                               Return(true)));
537   }
538 
539   attempter_.policy_provider_.reset(
540       new policy::PolicyProvider(std::move(device_policy)));
541 
542   if (valid_slot) {
543     BootControlInterface::Slot rollback_slot = 1;
544     LOG(INFO) << "Test Mark Bootable: "
545               << BootControlInterface::SlotName(rollback_slot);
546     fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
547                                                             true);
548   }
549 
550   bool is_rollback_allowed = false;
551 
552   // We only allow rollback on devices that are not enterprise enrolled and
553   // which have a valid slot to rollback to.
554   if (!enterprise_rollback && valid_slot) {
555     is_rollback_allowed = true;
556   }
557 
558   if (is_rollback_allowed) {
559     InSequence s;
560     for (size_t i = 0; i < arraysize(kRollbackActionTypes); ++i) {
561       EXPECT_CALL(*processor_,
562                   EnqueueAction(Pointee(Property(&AbstractAction::Type,
563                                                  kRollbackActionTypes[i]))));
564     }
565     EXPECT_CALL(*processor_, StartProcessing());
566 
567     EXPECT_TRUE(attempter_.Rollback(true));
568     loop_.PostTask(FROM_HERE,
569                    base::Bind(&UpdateAttempterTest::RollbackTestVerify,
570                               base::Unretained(this)));
571   } else {
572     EXPECT_FALSE(attempter_.Rollback(true));
573     loop_.BreakLoop();
574   }
575 }
576 
RollbackTestVerify()577 void UpdateAttempterTest::RollbackTestVerify() {
578   // Verifies the actions that were enqueued.
579   EXPECT_EQ(&attempter_, processor_->delegate());
580   EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
581   EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
582   EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
583   loop_.BreakLoop();
584 }
585 
TEST_F(UpdateAttempterTest,UpdateTest)586 TEST_F(UpdateAttempterTest, UpdateTest) {
587   UpdateTestStart();
588   loop_.Run();
589 }
590 
TEST_F(UpdateAttempterTest,RollbackTest)591 TEST_F(UpdateAttempterTest, RollbackTest) {
592   loop_.PostTask(FROM_HERE,
593                  base::Bind(&UpdateAttempterTest::RollbackTestStart,
594                             base::Unretained(this),
595                             false,
596                             true));
597   loop_.Run();
598 }
599 
TEST_F(UpdateAttempterTest,InvalidSlotRollbackTest)600 TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
601   loop_.PostTask(FROM_HERE,
602                  base::Bind(&UpdateAttempterTest::RollbackTestStart,
603                             base::Unretained(this),
604                             false,
605                             false));
606   loop_.Run();
607 }
608 
TEST_F(UpdateAttempterTest,EnterpriseRollbackTest)609 TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
610   loop_.PostTask(FROM_HERE,
611                  base::Bind(&UpdateAttempterTest::RollbackTestStart,
612                             base::Unretained(this),
613                             true,
614                             true));
615   loop_.Run();
616 }
617 
PingOmahaTestStart()618 void UpdateAttempterTest::PingOmahaTestStart() {
619   EXPECT_CALL(*processor_,
620               EnqueueAction(Pointee(Property(
621                   &AbstractAction::Type, OmahaRequestAction::StaticType()))));
622   EXPECT_CALL(*processor_, StartProcessing());
623   attempter_.PingOmaha();
624   ScheduleQuitMainLoop();
625 }
626 
TEST_F(UpdateAttempterTest,PingOmahaTest)627 TEST_F(UpdateAttempterTest, PingOmahaTest) {
628   EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
629   EXPECT_FALSE(attempter_.schedule_updates_called());
630   // Disable scheduling of subsequnet checks; we're using the DefaultPolicy in
631   // testing, which is more permissive than we want to handle here.
632   attempter_.DisableScheduleUpdates();
633   loop_.PostTask(FROM_HERE,
634                  base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
635                             base::Unretained(this)));
636   brillo::MessageLoopRunMaxIterations(&loop_, 100);
637   EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
638   EXPECT_TRUE(attempter_.schedule_updates_called());
639 }
640 
TEST_F(UpdateAttempterTest,CreatePendingErrorEventTest)641 TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
642   MockAction action;
643   const ErrorCode kCode = ErrorCode::kDownloadTransferError;
644   attempter_.CreatePendingErrorEvent(&action, kCode);
645   ASSERT_NE(nullptr, attempter_.error_event_.get());
646   EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
647   EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
648   EXPECT_EQ(
649       static_cast<ErrorCode>(static_cast<int>(kCode) |
650                              static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
651       attempter_.error_event_->error_code);
652 }
653 
TEST_F(UpdateAttempterTest,CreatePendingErrorEventResumedTest)654 TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
655   attempter_.install_plan_.reset(new InstallPlan);
656   attempter_.install_plan_->is_resume = true;
657   MockAction action;
658   const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
659   attempter_.CreatePendingErrorEvent(&action, kCode);
660   ASSERT_NE(nullptr, attempter_.error_event_.get());
661   EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
662   EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
663   EXPECT_EQ(
664       static_cast<ErrorCode>(static_cast<int>(kCode) |
665                              static_cast<int>(ErrorCode::kResumedFlag) |
666                              static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
667       attempter_.error_event_->error_code);
668 }
669 
TEST_F(UpdateAttempterTest,P2PNotStartedAtStartupWhenNotEnabled)670 TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
671   MockP2PManager mock_p2p_manager;
672   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
673   mock_p2p_manager.fake().SetP2PEnabled(false);
674   EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
675   attempter_.UpdateEngineStarted();
676 }
677 
TEST_F(UpdateAttempterTest,P2PNotStartedAtStartupWhenEnabledButNotSharing)678 TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
679   MockP2PManager mock_p2p_manager;
680   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
681   mock_p2p_manager.fake().SetP2PEnabled(true);
682   EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
683   attempter_.UpdateEngineStarted();
684 }
685 
TEST_F(UpdateAttempterTest,P2PStartedAtStartupWhenEnabledAndSharing)686 TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
687   MockP2PManager mock_p2p_manager;
688   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
689   mock_p2p_manager.fake().SetP2PEnabled(true);
690   mock_p2p_manager.fake().SetCountSharedFilesResult(1);
691   EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
692   attempter_.UpdateEngineStarted();
693 }
694 
TEST_F(UpdateAttempterTest,P2PNotEnabled)695 TEST_F(UpdateAttempterTest, P2PNotEnabled) {
696   loop_.PostTask(FROM_HERE,
697                  base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
698                             base::Unretained(this)));
699   loop_.Run();
700 }
701 
P2PNotEnabledStart()702 void UpdateAttempterTest::P2PNotEnabledStart() {
703   // If P2P is not enabled, check that we do not attempt housekeeping
704   // and do not convey that p2p is to be used.
705   MockP2PManager mock_p2p_manager;
706   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
707   mock_p2p_manager.fake().SetP2PEnabled(false);
708   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
709   attempter_.Update("", "", "", "", false, false, false);
710   EXPECT_FALSE(actual_using_p2p_for_downloading_);
711   EXPECT_FALSE(actual_using_p2p_for_sharing());
712   ScheduleQuitMainLoop();
713 }
714 
TEST_F(UpdateAttempterTest,P2PEnabledStartingFails)715 TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
716   loop_.PostTask(FROM_HERE,
717                  base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
718                             base::Unretained(this)));
719   loop_.Run();
720 }
721 
P2PEnabledStartingFailsStart()722 void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
723   // If p2p is enabled, but starting it fails ensure we don't do
724   // any housekeeping and do not convey that p2p should be used.
725   MockP2PManager mock_p2p_manager;
726   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
727   mock_p2p_manager.fake().SetP2PEnabled(true);
728   mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
729   mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
730   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
731   attempter_.Update("", "", "", "", false, false, false);
732   EXPECT_FALSE(actual_using_p2p_for_downloading());
733   EXPECT_FALSE(actual_using_p2p_for_sharing());
734   ScheduleQuitMainLoop();
735 }
736 
TEST_F(UpdateAttempterTest,P2PEnabledHousekeepingFails)737 TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
738   loop_.PostTask(
739       FROM_HERE,
740       base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
741                  base::Unretained(this)));
742   loop_.Run();
743 }
744 
P2PEnabledHousekeepingFailsStart()745 void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
746   // If p2p is enabled, starting it works but housekeeping fails, ensure
747   // we do not convey p2p is to be used.
748   MockP2PManager mock_p2p_manager;
749   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
750   mock_p2p_manager.fake().SetP2PEnabled(true);
751   mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
752   mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
753   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
754   attempter_.Update("", "", "", "", false, false, false);
755   EXPECT_FALSE(actual_using_p2p_for_downloading());
756   EXPECT_FALSE(actual_using_p2p_for_sharing());
757   ScheduleQuitMainLoop();
758 }
759 
TEST_F(UpdateAttempterTest,P2PEnabled)760 TEST_F(UpdateAttempterTest, P2PEnabled) {
761   loop_.PostTask(FROM_HERE,
762                  base::Bind(&UpdateAttempterTest::P2PEnabledStart,
763                             base::Unretained(this)));
764   loop_.Run();
765 }
766 
P2PEnabledStart()767 void UpdateAttempterTest::P2PEnabledStart() {
768   MockP2PManager mock_p2p_manager;
769   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
770   // If P2P is enabled and starting it works, check that we performed
771   // housekeeping and that we convey p2p should be used.
772   mock_p2p_manager.fake().SetP2PEnabled(true);
773   mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
774   mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
775   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
776   attempter_.Update("", "", "", "", false, false, false);
777   EXPECT_TRUE(actual_using_p2p_for_downloading());
778   EXPECT_TRUE(actual_using_p2p_for_sharing());
779   ScheduleQuitMainLoop();
780 }
781 
TEST_F(UpdateAttempterTest,P2PEnabledInteractive)782 TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
783   loop_.PostTask(FROM_HERE,
784                  base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
785                             base::Unretained(this)));
786   loop_.Run();
787 }
788 
P2PEnabledInteractiveStart()789 void UpdateAttempterTest::P2PEnabledInteractiveStart() {
790   MockP2PManager mock_p2p_manager;
791   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
792   // For an interactive check, if P2P is enabled and starting it
793   // works, check that we performed housekeeping and that we convey
794   // p2p should be used for sharing but NOT for downloading.
795   mock_p2p_manager.fake().SetP2PEnabled(true);
796   mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
797   mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
798   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
799   attempter_.Update("",
800                     "",
801                     "",
802                     "",
803                     false,
804                     false,
805                     /*interactive=*/true);
806   EXPECT_FALSE(actual_using_p2p_for_downloading());
807   EXPECT_TRUE(actual_using_p2p_for_sharing());
808   ScheduleQuitMainLoop();
809 }
810 
TEST_F(UpdateAttempterTest,ReadScatterFactorFromPolicy)811 TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
812   loop_.PostTask(
813       FROM_HERE,
814       base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
815                  base::Unretained(this)));
816   loop_.Run();
817 }
818 
819 // Tests that the scatter_factor_in_seconds value is properly fetched
820 // from the device policy.
ReadScatterFactorFromPolicyTestStart()821 void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
822   int64_t scatter_factor_in_seconds = 36000;
823 
824   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
825   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
826   fake_system_state_.set_device_policy(device_policy.get());
827 
828   EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
829       .WillRepeatedly(
830           DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
831 
832   attempter_.policy_provider_.reset(
833       new policy::PolicyProvider(std::move(device_policy)));
834 
835   attempter_.Update("", "", "", "", false, false, false);
836   EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
837 
838   ScheduleQuitMainLoop();
839 }
840 
TEST_F(UpdateAttempterTest,DecrementUpdateCheckCountTest)841 TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
842   loop_.PostTask(
843       FROM_HERE,
844       base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
845                  base::Unretained(this)));
846   loop_.Run();
847 }
848 
DecrementUpdateCheckCountTestStart()849 void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
850   // Tests that the scatter_factor_in_seconds value is properly fetched
851   // from the device policy and is decremented if value > 0.
852   int64_t initial_value = 5;
853   FakePrefs fake_prefs;
854   attempter_.prefs_ = &fake_prefs;
855 
856   fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
857 
858   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
859 
860   int64_t scatter_factor_in_seconds = 10;
861 
862   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
863   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
864   fake_system_state_.set_device_policy(device_policy.get());
865 
866   EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
867       .WillRepeatedly(
868           DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
869 
870   attempter_.policy_provider_.reset(
871       new policy::PolicyProvider(std::move(device_policy)));
872 
873   attempter_.Update("", "", "", "", false, false, false);
874   EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
875 
876   // Make sure the file still exists.
877   EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
878 
879   int64_t new_value;
880   EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
881   EXPECT_EQ(initial_value - 1, new_value);
882 
883   EXPECT_TRUE(
884       attempter_.omaha_request_params_->update_check_count_wait_enabled());
885 
886   // However, if the count is already 0, it's not decremented. Test that.
887   initial_value = 0;
888   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
889   attempter_.Update("", "", "", "", false, false, false);
890   EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
891   EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
892   EXPECT_EQ(initial_value, new_value);
893 
894   ScheduleQuitMainLoop();
895 }
896 
TEST_F(UpdateAttempterTest,NoScatteringDoneDuringManualUpdateTestStart)897 TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
898   loop_.PostTask(
899       FROM_HERE,
900       base::Bind(
901           &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
902           base::Unretained(this)));
903   loop_.Run();
904 }
905 
NoScatteringDoneDuringManualUpdateTestStart()906 void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
907   // Tests that no scattering logic is enabled if the update check
908   // is manually done (as opposed to a scheduled update check)
909   int64_t initial_value = 8;
910   FakePrefs fake_prefs;
911   attempter_.prefs_ = &fake_prefs;
912 
913   fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
914   fake_system_state_.set_prefs(&fake_prefs);
915 
916   EXPECT_TRUE(
917       fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
918   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
919 
920   // make sure scatter_factor is non-zero as scattering is disabled
921   // otherwise.
922   int64_t scatter_factor_in_seconds = 50;
923 
924   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
925   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
926   fake_system_state_.set_device_policy(device_policy.get());
927 
928   EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
929       .WillRepeatedly(
930           DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
931 
932   attempter_.policy_provider_.reset(
933       new policy::PolicyProvider(std::move(device_policy)));
934 
935   // Trigger an interactive check so we can test that scattering is disabled.
936   attempter_.Update("",
937                     "",
938                     "",
939                     "",
940                     false,
941                     false,
942                     /*interactive=*/true);
943   EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
944 
945   // Make sure scattering is disabled for manual (i.e. user initiated) update
946   // checks and all artifacts are removed.
947   EXPECT_FALSE(
948       attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
949   EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
950   EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
951   EXPECT_FALSE(
952       attempter_.omaha_request_params_->update_check_count_wait_enabled());
953   EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
954 
955   ScheduleQuitMainLoop();
956 }
957 
SetUpStagingTest(const StagingSchedule & schedule,FakePrefs * prefs)958 void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
959                                            FakePrefs* prefs) {
960   attempter_.prefs_ = prefs;
961   fake_system_state_.set_prefs(prefs);
962 
963   int64_t initial_value = 8;
964   EXPECT_TRUE(
965       prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
966   EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
967   attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
968 
969   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
970   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
971   fake_system_state_.set_device_policy(device_policy.get());
972   EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
973       .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
974 
975   attempter_.policy_provider_.reset(
976       new policy::PolicyProvider(std::move(device_policy)));
977 }
978 
TEST_F(UpdateAttempterTest,StagingSetsPrefsAndTurnsOffScattering)979 TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
980   loop_.PostTask(
981       FROM_HERE,
982       base::Bind(
983           &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
984           base::Unretained(this)));
985   loop_.Run();
986 }
987 
StagingSetsPrefsAndTurnsOffScatteringStart()988 void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
989   // Tests that staging sets its prefs properly and turns off scattering.
990   fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
991   FakePrefs fake_prefs;
992   SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
993 
994   attempter_.Update("", "", "", "", false, false, false);
995   // Check that prefs have the correct values.
996   int64_t update_count;
997   EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
998   int64_t waiting_time_days;
999   EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1000                                   &waiting_time_days));
1001   EXPECT_GT(waiting_time_days, 0);
1002   // Update count should have been decremented.
1003   EXPECT_EQ(7, update_count);
1004   // Check that Omaha parameters were updated correctly.
1005   EXPECT_TRUE(
1006       attempter_.omaha_request_params_->update_check_count_wait_enabled());
1007   EXPECT_TRUE(
1008       attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1009   EXPECT_EQ(waiting_time_days,
1010             attempter_.omaha_request_params_->waiting_period().InDays());
1011   // Check class variables.
1012   EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1013   EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1014   // Check that scattering is turned off
1015   EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1016   EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1017 
1018   ScheduleQuitMainLoop();
1019 }
1020 
CheckStagingOff()1021 void UpdateAttempterTest::CheckStagingOff() {
1022   // Check that all prefs were removed.
1023   EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1024   EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1025   EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1026   // Check that the Omaha parameters have the correct value.
1027   EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1028   EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1029             attempter_.staging_wait_time_);
1030   EXPECT_FALSE(
1031       attempter_.omaha_request_params_->update_check_count_wait_enabled());
1032   EXPECT_FALSE(
1033       attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1034   // Check that scattering is turned off too.
1035   EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1036 }
1037 
TEST_F(UpdateAttempterTest,StagingOffIfInteractive)1038 TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1039   loop_.PostTask(FROM_HERE,
1040                  base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1041                             base::Unretained(this)));
1042   loop_.Run();
1043 }
1044 
StagingOffIfInteractiveStart()1045 void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1046   // Tests that staging is turned off when an interactive update is requested.
1047   fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1048   FakePrefs fake_prefs;
1049   SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1050 
1051   attempter_.Update("", "", "", "", false, false, /* interactive = */ true);
1052   CheckStagingOff();
1053 
1054   ScheduleQuitMainLoop();
1055 }
1056 
TEST_F(UpdateAttempterTest,StagingOffIfOobe)1057 TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1058   loop_.PostTask(FROM_HERE,
1059                  base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1060                             base::Unretained(this)));
1061   loop_.Run();
1062 }
1063 
StagingOffIfOobeStart()1064 void UpdateAttempterTest::StagingOffIfOobeStart() {
1065   // Tests that staging is turned off if OOBE hasn't been completed.
1066   fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1067   fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1068   FakePrefs fake_prefs;
1069   SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1070 
1071   attempter_.Update("", "", "", "", false, false, /* interactive = */ true);
1072   CheckStagingOff();
1073 
1074   ScheduleQuitMainLoop();
1075 }
1076 
1077 // Checks that we only report daily metrics at most every 24 hours.
TEST_F(UpdateAttempterTest,ReportDailyMetrics)1078 TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1079   FakeClock fake_clock;
1080   FakePrefs fake_prefs;
1081 
1082   fake_system_state_.set_clock(&fake_clock);
1083   fake_system_state_.set_prefs(&fake_prefs);
1084 
1085   Time epoch = Time::FromInternalValue(0);
1086   fake_clock.SetWallclockTime(epoch);
1087 
1088   // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1089   // we should report.
1090   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1091   // We should not report again if no time has passed.
1092   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1093 
1094   // We should not report if only 10 hours has passed.
1095   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1096   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1097 
1098   // We should not report if only 24 hours - 1 sec has passed.
1099   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1100                               TimeDelta::FromSeconds(1));
1101   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1102 
1103   // We should report if 24 hours has passed.
1104   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1105   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1106 
1107   // But then we should not report again..
1108   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1109 
1110   // .. until another 24 hours has passed
1111   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1112   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1113   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1114   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1115   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1116 
1117   // .. and another 24 hours
1118   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1119   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1120   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1121   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1122   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1123 
1124   // If the span between time of reporting and present time is
1125   // negative, we report. This is in order to reset the timestamp and
1126   // avoid an edge condition whereby a distant point in the future is
1127   // in the state variable resulting in us never ever reporting again.
1128   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1129   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1130   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1131 
1132   // In this case we should not update until the clock reads 71 + 24 = 95.
1133   // Check that.
1134   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1135   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1136   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1137   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1138   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1139 }
1140 
TEST_F(UpdateAttempterTest,BootTimeInUpdateMarkerFile)1141 TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
1142   FakeClock fake_clock;
1143   fake_clock.SetBootTime(Time::FromTimeT(42));
1144   fake_system_state_.set_clock(&fake_clock);
1145   FakePrefs fake_prefs;
1146   fake_system_state_.set_prefs(&fake_prefs);
1147   attempter_.Init();
1148 
1149   Time boot_time;
1150   EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
1151 
1152   attempter_.WriteUpdateCompletedMarker();
1153 
1154   EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
1155   EXPECT_EQ(boot_time.ToTimeT(), 42);
1156 }
1157 
TEST_F(UpdateAttempterTest,AnyUpdateSourceAllowedUnofficial)1158 TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1159   fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1160   EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1161 }
1162 
TEST_F(UpdateAttempterTest,AnyUpdateSourceAllowedOfficialDevmode)1163 TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1164   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1165   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
1166   EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1167 }
1168 
TEST_F(UpdateAttempterTest,AnyUpdateSourceDisallowedOfficialNormal)1169 TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1170   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1171   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1172   EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1173 }
1174 
TEST_F(UpdateAttempterTest,CheckForUpdateAUDlcTest)1175 TEST_F(UpdateAttempterTest, CheckForUpdateAUDlcTest) {
1176   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1177   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1178 
1179   const string dlc_module_id = "a_dlc_module_id";
1180   vector<string> dlc_module_ids = {dlc_module_id};
1181   ON_CALL(mock_dlcservice_, GetInstalled(testing::_))
1182       .WillByDefault(DoAll(testing::SetArgPointee<0>(dlc_module_ids),
1183                            testing::Return(true)));
1184 
1185   attempter_.CheckForUpdate("", "autest", UpdateAttemptFlags::kNone);
1186   EXPECT_EQ(attempter_.dlc_module_ids_.size(), 1);
1187   EXPECT_EQ(attempter_.dlc_module_ids_[0], dlc_module_id);
1188 }
1189 
TEST_F(UpdateAttempterTest,CheckForUpdateAUTest)1190 TEST_F(UpdateAttempterTest, CheckForUpdateAUTest) {
1191   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1192   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1193   attempter_.CheckForUpdate("", "autest", UpdateAttemptFlags::kNone);
1194   EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1195 }
1196 
TEST_F(UpdateAttempterTest,CheckForUpdateScheduledAUTest)1197 TEST_F(UpdateAttempterTest, CheckForUpdateScheduledAUTest) {
1198   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1199   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1200   attempter_.CheckForUpdate("", "autest-scheduled", UpdateAttemptFlags::kNone);
1201   EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1202 }
1203 
TEST_F(UpdateAttempterTest,CheckForInstallTest)1204 TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1205   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1206   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1207   attempter_.CheckForInstall({}, "autest");
1208   EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1209 
1210   attempter_.CheckForInstall({}, "autest-scheduled");
1211   EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1212 
1213   attempter_.CheckForInstall({}, "http://omaha.phishing");
1214   EXPECT_EQ("", attempter_.forced_omaha_url());
1215 }
1216 
TEST_F(UpdateAttempterTest,InstallSetsStatusIdle)1217 TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1218   attempter_.CheckForInstall({}, "http://foo.bar");
1219   attempter_.status_ = UpdateStatus::DOWNLOADING;
1220   EXPECT_TRUE(attempter_.is_install_);
1221   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1222   UpdateEngineStatus status;
1223   attempter_.GetStatus(&status);
1224   // Should set status to idle after an install operation.
1225   EXPECT_EQ(UpdateStatus::IDLE, status.status);
1226 }
1227 
TEST_F(UpdateAttempterTest,RollbackAfterInstall)1228 TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1229   attempter_.is_install_ = true;
1230   attempter_.Rollback(false);
1231   EXPECT_FALSE(attempter_.is_install_);
1232 }
1233 
TEST_F(UpdateAttempterTest,UpdateAfterInstall)1234 TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1235   attempter_.is_install_ = true;
1236   attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1237   EXPECT_FALSE(attempter_.is_install_);
1238 }
1239 
TEST_F(UpdateAttempterTest,TargetVersionPrefixSetAndReset)1240 TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
1241   attempter_.CalculateUpdateParams("", "", "", "1234", false, false, false);
1242   EXPECT_EQ("1234",
1243             fake_system_state_.request_params()->target_version_prefix());
1244 
1245   attempter_.CalculateUpdateParams("", "", "", "", false, false, false);
1246   EXPECT_TRUE(
1247       fake_system_state_.request_params()->target_version_prefix().empty());
1248 }
1249 
TEST_F(UpdateAttempterTest,RollbackAllowedSetAndReset)1250 TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1251   attempter_.CalculateUpdateParams("",
1252                                    "",
1253                                    "",
1254                                    "1234",
1255                                    /*rollback_allowed=*/true,
1256                                    false,
1257                                    false);
1258   EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1259 
1260   attempter_.CalculateUpdateParams("",
1261                                    "",
1262                                    "",
1263                                    "1234",
1264                                    /*rollback_allowed=*/false,
1265                                    false,
1266                                    false);
1267   EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1268 }
1269 
TEST_F(UpdateAttempterTest,UpdateDeferredByPolicyTest)1270 TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1271   // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1272   // but the update is being deferred by the Policy.
1273   OmahaResponseHandlerAction response_action(&fake_system_state_);
1274   response_action.install_plan_.version = "a.b.c.d";
1275   response_action.install_plan_.system_version = "b.c.d.e";
1276   response_action.install_plan_.payloads.push_back(
1277       {.size = 1234ULL, .type = InstallPayloadType::kFull});
1278   // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1279   // completed, with the deferred-update error code.
1280   attempter_.ActionCompleted(
1281       nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1282   {
1283     UpdateEngineStatus status;
1284     attempter_.GetStatus(&status);
1285     EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
1286     EXPECT_TRUE(attempter_.install_plan_);
1287     EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
1288     EXPECT_EQ(attempter_.install_plan_->system_version,
1289               status.new_system_version);
1290     EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
1291               status.new_size_bytes);
1292   }
1293   // An "error" event should have been created to tell Omaha that the update is
1294   // being deferred.
1295   EXPECT_TRUE(nullptr != attempter_.error_event_);
1296   EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1297   EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1298   ErrorCode expected_code = static_cast<ErrorCode>(
1299       static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1300       static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1301   EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1302   // End the processing
1303   attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1304   // Validate the state of the attempter.
1305   {
1306     UpdateEngineStatus status;
1307     attempter_.GetStatus(&status);
1308     EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
1309     EXPECT_EQ(response_action.install_plan_.version, status.new_version);
1310     EXPECT_EQ(response_action.install_plan_.system_version,
1311               status.new_system_version);
1312     EXPECT_EQ(response_action.install_plan_.payloads[0].size,
1313               status.new_size_bytes);
1314   }
1315 }
1316 
TEST_F(UpdateAttempterTest,UpdateIsNotRunningWhenUpdateAvailable)1317 TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
1318   EXPECT_FALSE(attempter_.IsUpdateRunningOrScheduled());
1319   // Verify in-progress update with UPDATE_AVAILABLE is running
1320   attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
1321   EXPECT_TRUE(attempter_.IsUpdateRunningOrScheduled());
1322 }
1323 
TEST_F(UpdateAttempterTest,UpdateAttemptFlagsCachedAtUpdateStart)1324 TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1325   attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1326 
1327   UpdateCheckParams params = {.updates_enabled = true};
1328   attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1329 
1330   EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1331             attempter_.GetCurrentUpdateAttemptFlags());
1332 }
1333 
TEST_F(UpdateAttempterTest,RollbackNotAllowed)1334 TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1335   UpdateCheckParams params = {.updates_enabled = true,
1336                               .rollback_allowed = false};
1337   attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1338   EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1339 }
1340 
TEST_F(UpdateAttempterTest,RollbackAllowed)1341 TEST_F(UpdateAttempterTest, RollbackAllowed) {
1342   UpdateCheckParams params = {.updates_enabled = true,
1343                               .rollback_allowed = true};
1344   attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1345   EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1346 }
1347 
TEST_F(UpdateAttempterTest,InteractiveUpdateUsesPassedRestrictions)1348 TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1349   attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1350 
1351   attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1352   EXPECT_EQ(UpdateAttemptFlags::kNone,
1353             attempter_.GetCurrentUpdateAttemptFlags());
1354 }
1355 
TEST_F(UpdateAttempterTest,NonInteractiveUpdateUsesSetRestrictions)1356 TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1357   attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1358 
1359   // This tests that when CheckForUpdate() is called with the non-interactive
1360   // flag set, that it doesn't change the current UpdateAttemptFlags.
1361   attempter_.CheckForUpdate("",
1362                             "",
1363                             UpdateAttemptFlags::kFlagNonInteractive |
1364                                 UpdateAttemptFlags::kFlagRestrictDownload);
1365   EXPECT_EQ(UpdateAttemptFlags::kNone,
1366             attempter_.GetCurrentUpdateAttemptFlags());
1367 }
1368 
ResetRollbackHappenedStart(bool is_consumer,bool is_policy_loaded,bool expected_reset)1369 void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1370                                                      bool is_policy_loaded,
1371                                                      bool expected_reset) {
1372   EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1373       .WillRepeatedly(Return(true));
1374   auto mock_policy_provider =
1375       std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1376   EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1377       .WillRepeatedly(Return(is_consumer));
1378   EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1379       .WillRepeatedly(Return(is_policy_loaded));
1380   const policy::MockDevicePolicy device_policy;
1381   EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1382       .WillRepeatedly(ReturnRef(device_policy));
1383   EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1384               SetRollbackHappened(false))
1385       .Times(expected_reset ? 1 : 0);
1386   attempter_.policy_provider_ = std::move(mock_policy_provider);
1387   attempter_.Update("", "", "", "", false, false, false);
1388   ScheduleQuitMainLoop();
1389 }
1390 
TEST_F(UpdateAttempterTest,ResetRollbackHappenedOobe)1391 TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1392   loop_.PostTask(FROM_HERE,
1393                  base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1394                             base::Unretained(this),
1395                             /*is_consumer=*/false,
1396                             /*is_policy_loaded=*/false,
1397                             /*expected_reset=*/false));
1398   loop_.Run();
1399 }
1400 
TEST_F(UpdateAttempterTest,ResetRollbackHappenedConsumer)1401 TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1402   loop_.PostTask(FROM_HERE,
1403                  base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1404                             base::Unretained(this),
1405                             /*is_consumer=*/true,
1406                             /*is_policy_loaded=*/false,
1407                             /*expected_reset=*/true));
1408   loop_.Run();
1409 }
1410 
TEST_F(UpdateAttempterTest,ResetRollbackHappenedEnterprise)1411 TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1412   loop_.PostTask(FROM_HERE,
1413                  base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1414                             base::Unretained(this),
1415                             /*is_consumer=*/false,
1416                             /*is_policy_loaded=*/true,
1417                             /*expected_reset=*/true));
1418   loop_.Run();
1419 }
1420 
TEST_F(UpdateAttempterTest,SetRollbackHappenedRollback)1421 TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
1422   attempter_.install_plan_.reset(new InstallPlan);
1423   attempter_.install_plan_->is_rollback = true;
1424 
1425   EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1426               SetRollbackHappened(true))
1427       .Times(1);
1428   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1429 }
1430 
TEST_F(UpdateAttempterTest,SetRollbackHappenedNotRollback)1431 TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
1432   attempter_.install_plan_.reset(new InstallPlan);
1433   attempter_.install_plan_->is_rollback = false;
1434 
1435   EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1436               SetRollbackHappened(true))
1437       .Times(0);
1438   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1439 }
1440 
TEST_F(UpdateAttempterTest,RollbackMetricsRollbackSuccess)1441 TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
1442   attempter_.install_plan_.reset(new InstallPlan);
1443   attempter_.install_plan_->is_rollback = true;
1444   attempter_.install_plan_->version = kRollbackVersion;
1445 
1446   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1447               ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1448       .Times(1);
1449   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1450 }
1451 
TEST_F(UpdateAttempterTest,RollbackMetricsNotRollbackSuccess)1452 TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
1453   attempter_.install_plan_.reset(new InstallPlan);
1454   attempter_.install_plan_->is_rollback = false;
1455   attempter_.install_plan_->version = kRollbackVersion;
1456 
1457   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1458               ReportEnterpriseRollbackMetrics(_, _))
1459       .Times(0);
1460   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1461 }
1462 
TEST_F(UpdateAttempterTest,RollbackMetricsRollbackFailure)1463 TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
1464   attempter_.install_plan_.reset(new InstallPlan);
1465   attempter_.install_plan_->is_rollback = true;
1466   attempter_.install_plan_->version = kRollbackVersion;
1467 
1468   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1469               ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1470       .Times(1);
1471   MockAction action;
1472   attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1473   attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1474 }
1475 
TEST_F(UpdateAttempterTest,RollbackMetricsNotRollbackFailure)1476 TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
1477   attempter_.install_plan_.reset(new InstallPlan);
1478   attempter_.install_plan_->is_rollback = false;
1479   attempter_.install_plan_->version = kRollbackVersion;
1480 
1481   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1482               ReportEnterpriseRollbackMetrics(_, _))
1483       .Times(0);
1484   MockAction action;
1485   attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1486   attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1487 }
1488 
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedMetricFailure)1489 TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1490   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1491               ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1492       .Times(0);
1493   attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1494 }
1495 
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedOnNonEnterprise)1496 TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1497   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1498   fake_system_state_.set_device_policy(device_policy.get());
1499   // Make device policy return that this is not enterprise enrolled
1500   EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1501 
1502   // Ensure that the metric is not recorded.
1503   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1504               ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1505       .Times(0);
1506   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1507 }
1508 
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedWithTimeRestrictionMetricSuccess)1509 TEST_F(UpdateAttempterTest,
1510        TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1511   constexpr int kDaysToUpdate = 15;
1512   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1513   fake_system_state_.set_device_policy(device_policy.get());
1514   // Make device policy return that this is enterprise enrolled
1515   EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1516   // Pretend that there's a time restriction policy in place
1517   EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1518       .WillOnce(Return(true));
1519 
1520   FakePrefs fake_prefs;
1521   Time update_first_seen_at = Time::Now();
1522   fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1523                       update_first_seen_at.ToInternalValue());
1524 
1525   FakeClock fake_clock;
1526   Time update_finished_at =
1527       update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1528   fake_clock.SetWallclockTime(update_finished_at);
1529 
1530   fake_system_state_.set_clock(&fake_clock);
1531   fake_system_state_.set_prefs(&fake_prefs);
1532 
1533   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1534               ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1535       .Times(1);
1536   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1537 }
1538 
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess)1539 TEST_F(UpdateAttempterTest,
1540        TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1541   constexpr int kDaysToUpdate = 15;
1542   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1543   fake_system_state_.set_device_policy(device_policy.get());
1544   // Make device policy return that this is enterprise enrolled
1545   EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1546   // Pretend that there's no time restriction policy in place
1547   EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1548       .WillOnce(Return(false));
1549 
1550   FakePrefs fake_prefs;
1551   Time update_first_seen_at = Time::Now();
1552   fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1553                       update_first_seen_at.ToInternalValue());
1554 
1555   FakeClock fake_clock;
1556   Time update_finished_at =
1557       update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1558   fake_clock.SetWallclockTime(update_finished_at);
1559 
1560   fake_system_state_.set_clock(&fake_clock);
1561   fake_system_state_.set_prefs(&fake_prefs);
1562 
1563   EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1564               ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1565       .Times(1);
1566   attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1567 }
1568 
1569 }  // namespace chromeos_update_engine
1570