Home | History | Annotate | Download | only in update_engine
      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 
     32 #include "update_engine/common/fake_clock.h"
     33 #include "update_engine/common/fake_prefs.h"
     34 #include "update_engine/common/mock_action.h"
     35 #include "update_engine/common/mock_action_processor.h"
     36 #include "update_engine/common/mock_http_fetcher.h"
     37 #include "update_engine/common/mock_prefs.h"
     38 #include "update_engine/common/platform_constants.h"
     39 #include "update_engine/common/prefs.h"
     40 #include "update_engine/common/test_utils.h"
     41 #include "update_engine/common/utils.h"
     42 #include "update_engine/fake_system_state.h"
     43 #include "update_engine/mock_p2p_manager.h"
     44 #include "update_engine/mock_payload_state.h"
     45 #include "update_engine/mock_service_observer.h"
     46 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
     47 #include "update_engine/payload_consumer/install_plan.h"
     48 #include "update_engine/payload_consumer/payload_constants.h"
     49 #include "update_engine/payload_consumer/postinstall_runner_action.h"
     50 
     51 using base::Time;
     52 using base::TimeDelta;
     53 using chromeos_update_manager::EvalStatus;
     54 using chromeos_update_manager::UpdateCheckParams;
     55 using std::string;
     56 using std::unique_ptr;
     57 using testing::_;
     58 using testing::DoAll;
     59 using testing::Field;
     60 using testing::InSequence;
     61 using testing::Ne;
     62 using testing::NiceMock;
     63 using testing::Property;
     64 using testing::Return;
     65 using testing::ReturnPointee;
     66 using testing::SaveArg;
     67 using testing::SetArgPointee;
     68 using update_engine::UpdateAttemptFlags;
     69 using update_engine::UpdateEngineStatus;
     70 using update_engine::UpdateStatus;
     71 
     72 namespace chromeos_update_engine {
     73 
     74 // Test a subclass rather than the main class directly so that we can mock out
     75 // methods within the class. There're explicit unit tests for the mocked out
     76 // methods.
     77 class UpdateAttempterUnderTest : public UpdateAttempter {
     78  public:
     79   explicit UpdateAttempterUnderTest(SystemState* system_state)
     80       : UpdateAttempter(system_state, nullptr) {}
     81 
     82   // Wrap the update scheduling method, allowing us to opt out of scheduled
     83   // updates for testing purposes.
     84   void ScheduleUpdates() override {
     85     schedule_updates_called_ = true;
     86     if (do_schedule_updates_) {
     87       UpdateAttempter::ScheduleUpdates();
     88     } else {
     89       LOG(INFO) << "[TEST] Update scheduling disabled.";
     90     }
     91   }
     92   void EnableScheduleUpdates() { do_schedule_updates_ = true; }
     93   void DisableScheduleUpdates() { do_schedule_updates_ = false; }
     94 
     95   // Indicates whether ScheduleUpdates() was called.
     96   bool schedule_updates_called() const { return schedule_updates_called_; }
     97 
     98   // Need to expose forced_omaha_url_ so we can test it.
     99   const string& forced_omaha_url() const { return forced_omaha_url_; }
    100 
    101  private:
    102   bool schedule_updates_called_ = false;
    103   bool do_schedule_updates_ = true;
    104 };
    105 
    106 class UpdateAttempterTest : public ::testing::Test {
    107  protected:
    108   UpdateAttempterTest()
    109       : certificate_checker_(fake_system_state_.mock_prefs(),
    110                              &openssl_wrapper_) {
    111     // Override system state members.
    112     fake_system_state_.set_connection_manager(&mock_connection_manager);
    113     fake_system_state_.set_update_attempter(&attempter_);
    114     loop_.SetAsCurrent();
    115 
    116     certificate_checker_.Init();
    117 
    118     // Finish initializing the attempter.
    119     attempter_.Init();
    120   }
    121 
    122   void SetUp() override {
    123     EXPECT_NE(nullptr, attempter_.system_state_);
    124     EXPECT_EQ(0, attempter_.http_response_code_);
    125     EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
    126     EXPECT_EQ(0.0, attempter_.download_progress_);
    127     EXPECT_EQ(0, attempter_.last_checked_time_);
    128     EXPECT_EQ("0.0.0.0", attempter_.new_version_);
    129     EXPECT_EQ(0ULL, attempter_.new_payload_size_);
    130     processor_ = new NiceMock<MockActionProcessor>();
    131     attempter_.processor_.reset(processor_);  // Transfers ownership.
    132     prefs_ = fake_system_state_.mock_prefs();
    133 
    134     // Set up store/load semantics of P2P properties via the mock PayloadState.
    135     actual_using_p2p_for_downloading_ = false;
    136     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
    137                 SetUsingP2PForDownloading(_))
    138         .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
    139     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
    140                 GetUsingP2PForDownloading())
    141         .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
    142     actual_using_p2p_for_sharing_ = false;
    143     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
    144                 SetUsingP2PForSharing(_))
    145         .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
    146     EXPECT_CALL(*fake_system_state_.mock_payload_state(),
    147                 GetUsingP2PForDownloading())
    148         .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
    149   }
    150 
    151  public:
    152   void ScheduleQuitMainLoop();
    153 
    154   // Callbacks to run the different tests from the main loop.
    155   void UpdateTestStart();
    156   void UpdateTestVerify();
    157   void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
    158   void RollbackTestVerify();
    159   void PingOmahaTestStart();
    160   void ReadScatterFactorFromPolicyTestStart();
    161   void DecrementUpdateCheckCountTestStart();
    162   void NoScatteringDoneDuringManualUpdateTestStart();
    163   void P2PNotEnabledStart();
    164   void P2PEnabledStart();
    165   void P2PEnabledInteractiveStart();
    166   void P2PEnabledStartingFailsStart();
    167   void P2PEnabledHousekeepingFailsStart();
    168 
    169   bool actual_using_p2p_for_downloading() {
    170     return actual_using_p2p_for_downloading_;
    171   }
    172   bool actual_using_p2p_for_sharing() {
    173     return actual_using_p2p_for_sharing_;
    174   }
    175 
    176   base::MessageLoopForIO base_loop_;
    177   brillo::BaseMessageLoop loop_{&base_loop_};
    178 
    179   FakeSystemState fake_system_state_;
    180   UpdateAttempterUnderTest attempter_{&fake_system_state_};
    181   OpenSSLWrapper openssl_wrapper_;
    182   CertificateChecker certificate_checker_;
    183 
    184   NiceMock<MockActionProcessor>* processor_;
    185   NiceMock<MockPrefs>* prefs_;  // Shortcut to fake_system_state_->mock_prefs().
    186   NiceMock<MockConnectionManager> mock_connection_manager;
    187 
    188   bool actual_using_p2p_for_downloading_;
    189   bool actual_using_p2p_for_sharing_;
    190 };
    191 
    192 void UpdateAttempterTest::ScheduleQuitMainLoop() {
    193   loop_.PostTask(
    194       FROM_HERE,
    195       base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
    196                  base::Unretained(&loop_)));
    197 }
    198 
    199 TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
    200   unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
    201   fetcher->FailTransfer(503);  // Sets the HTTP response code.
    202   DownloadAction action(prefs_,
    203                         nullptr,
    204                         nullptr,
    205                         nullptr,
    206                         fetcher.release(),
    207                         false /* is_interactive */);
    208   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
    209   attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
    210   EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
    211   EXPECT_EQ(0.0, attempter_.download_progress_);
    212   ASSERT_EQ(nullptr, attempter_.error_event_.get());
    213 }
    214 
    215 TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
    216   MockAction action;
    217   EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
    218   attempter_.status_ = UpdateStatus::DOWNLOADING;
    219   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
    220       .WillOnce(Return(false));
    221   attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
    222   ASSERT_NE(nullptr, attempter_.error_event_.get());
    223 }
    224 
    225 TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
    226   // Simple test case, where all the values match (nothing was skipped)
    227   uint64_t bytes_progressed_1 = 1024 * 1024;  // 1MB
    228   uint64_t bytes_progressed_2 = 1024 * 1024;  // 1MB
    229   uint64_t bytes_received_1 = bytes_progressed_1;
    230   uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
    231   uint64_t bytes_total = 20 * 1024 * 1024;  // 20MB
    232 
    233   double progress_1 =
    234       static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
    235   double progress_2 =
    236       static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
    237 
    238   EXPECT_EQ(0.0, attempter_.download_progress_);
    239   // This is set via inspecting the InstallPlan payloads when the
    240   // OmahaResponseAction is completed
    241   attempter_.new_payload_size_ = bytes_total;
    242   NiceMock<MockServiceObserver> observer;
    243   EXPECT_CALL(observer,
    244               SendStatusUpdate(AllOf(
    245                   Field(&UpdateEngineStatus::progress, progress_1),
    246                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
    247                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
    248   EXPECT_CALL(observer,
    249               SendStatusUpdate(AllOf(
    250                   Field(&UpdateEngineStatus::progress, progress_2),
    251                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
    252                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
    253   attempter_.AddObserver(&observer);
    254   attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
    255   EXPECT_EQ(progress_1, attempter_.download_progress_);
    256   // This iteration validates that a later set of updates to the variables are
    257   // properly handled (so that |getStatus()| will return the same progress info
    258   // as the callback is receiving.
    259   attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
    260   EXPECT_EQ(progress_2, attempter_.download_progress_);
    261 }
    262 
    263 TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
    264   // The transition into UpdateStatus::DOWNLOADING happens when the
    265   // first bytes are received.
    266   uint64_t bytes_progressed = 1024 * 1024;    // 1MB
    267   uint64_t bytes_received = 2 * 1024 * 1024;  // 2MB
    268   uint64_t bytes_total = 20 * 1024 * 1024;    // 300MB
    269   attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
    270   // This is set via inspecting the InstallPlan payloads when the
    271   // OmahaResponseAction is completed
    272   attempter_.new_payload_size_ = bytes_total;
    273   EXPECT_EQ(0.0, attempter_.download_progress_);
    274   NiceMock<MockServiceObserver> observer;
    275   EXPECT_CALL(observer,
    276               SendStatusUpdate(AllOf(
    277                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
    278                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
    279   attempter_.AddObserver(&observer);
    280   attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
    281   EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
    282 }
    283 
    284 TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
    285   // There is a special case to ensure that at 100% downloaded,
    286   // download_progress_ is updated and that value broadcast. This test confirms
    287   // that.
    288   uint64_t bytes_progressed = 0;              // ignored
    289   uint64_t bytes_received = 5 * 1024 * 1024;  // ignored
    290   uint64_t bytes_total = 5 * 1024 * 1024;     // 300MB
    291   attempter_.status_ = UpdateStatus::DOWNLOADING;
    292   attempter_.new_payload_size_ = bytes_total;
    293   EXPECT_EQ(0.0, attempter_.download_progress_);
    294   NiceMock<MockServiceObserver> observer;
    295   EXPECT_CALL(observer,
    296               SendStatusUpdate(AllOf(
    297                   Field(&UpdateEngineStatus::progress, 1.0),
    298                   Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
    299                   Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
    300   attempter_.AddObserver(&observer);
    301   attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
    302   EXPECT_EQ(1.0, attempter_.download_progress_);
    303 }
    304 
    305 TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
    306   unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
    307   fetcher->FailTransfer(500);  // Sets the HTTP response code.
    308   OmahaRequestAction action(&fake_system_state_, nullptr,
    309                             std::move(fetcher), false);
    310   ObjectCollectorAction<OmahaResponse> collector_action;
    311   BondActions(&action, &collector_action);
    312   OmahaResponse response;
    313   response.poll_interval = 234;
    314   action.SetOutputObject(response);
    315   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
    316   attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
    317   EXPECT_EQ(500, attempter_.http_response_code());
    318   EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
    319   EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
    320   ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
    321 }
    322 
    323 TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
    324   FakePrefs fake_prefs;
    325   string boot_id;
    326   EXPECT_TRUE(utils::GetBootId(&boot_id));
    327   fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
    328   fake_system_state_.set_prefs(&fake_prefs);
    329   attempter_.Init();
    330   EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
    331 }
    332 
    333 TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
    334   extern ErrorCode GetErrorCodeForAction(AbstractAction* action,
    335                                               ErrorCode code);
    336   EXPECT_EQ(ErrorCode::kSuccess,
    337             GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
    338 
    339   FakeSystemState fake_system_state;
    340   OmahaRequestAction omaha_request_action(&fake_system_state, nullptr,
    341                                           nullptr, false);
    342   EXPECT_EQ(ErrorCode::kOmahaRequestError,
    343             GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
    344   OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
    345   EXPECT_EQ(ErrorCode::kOmahaResponseHandlerError,
    346             GetErrorCodeForAction(&omaha_response_handler_action,
    347                                   ErrorCode::kError));
    348   FilesystemVerifierAction filesystem_verifier_action;
    349   EXPECT_EQ(ErrorCode::kFilesystemVerifierError,
    350             GetErrorCodeForAction(&filesystem_verifier_action,
    351                                   ErrorCode::kError));
    352   PostinstallRunnerAction postinstall_runner_action(
    353       fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
    354   EXPECT_EQ(ErrorCode::kPostinstallRunnerError,
    355             GetErrorCodeForAction(&postinstall_runner_action,
    356                                   ErrorCode::kError));
    357   MockAction action_mock;
    358   EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
    359   EXPECT_EQ(ErrorCode::kError,
    360             GetErrorCodeForAction(&action_mock, ErrorCode::kError));
    361 }
    362 
    363 TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
    364   attempter_.omaha_request_params_->set_delta_okay(true);
    365   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
    366       .WillOnce(Return(false));
    367   attempter_.DisableDeltaUpdateIfNeeded();
    368   EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
    369   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
    370       .WillOnce(DoAll(
    371           SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
    372           Return(true)));
    373   attempter_.DisableDeltaUpdateIfNeeded();
    374   EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
    375   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
    376       .WillOnce(DoAll(
    377           SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
    378           Return(true)));
    379   attempter_.DisableDeltaUpdateIfNeeded();
    380   EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
    381   EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
    382   attempter_.DisableDeltaUpdateIfNeeded();
    383   EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
    384 }
    385 
    386 TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
    387   EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
    388       .WillOnce(Return(false))
    389       .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
    390       .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
    391       .WillOnce(DoAll(
    392           SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
    393           Return(true)));
    394   EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
    395       .WillRepeatedly(Return(true));
    396   EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
    397   EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
    398   EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures,
    399                                UpdateAttempter::kMaxDeltaUpdateFailures + 1));
    400   for (int i = 0; i < 4; i ++)
    401     attempter_.MarkDeltaUpdateFailure();
    402 }
    403 
    404 TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
    405   EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
    406   EXPECT_CALL(*processor_, StartProcessing()).Times(0);
    407   EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
    408       .Times(0);
    409   OmahaResponse response;
    410   string url1 = "http://url1";
    411   response.packages.push_back({.payload_urls = {url1, "https://url"}});
    412   EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
    413       .WillRepeatedly(Return(url1));
    414   fake_system_state_.mock_payload_state()->SetResponse(response);
    415   attempter_.ScheduleErrorEventAction();
    416   EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
    417 }
    418 
    419 TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
    420   EXPECT_CALL(*processor_,
    421               EnqueueAction(Property(&AbstractAction::Type,
    422                                      OmahaRequestAction::StaticType())));
    423   EXPECT_CALL(*processor_, StartProcessing());
    424   ErrorCode err = ErrorCode::kError;
    425   EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
    426   attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
    427                                                OmahaEvent::kResultError,
    428                                                err));
    429   attempter_.ScheduleErrorEventAction();
    430   EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
    431 }
    432 
    433 namespace {
    434 // Actions that will be built as part of an update check.
    435 const string kUpdateActionTypes[] = {  // NOLINT(runtime/string)
    436   OmahaRequestAction::StaticType(),
    437   OmahaResponseHandlerAction::StaticType(),
    438   OmahaRequestAction::StaticType(),
    439   DownloadAction::StaticType(),
    440   OmahaRequestAction::StaticType(),
    441   FilesystemVerifierAction::StaticType(),
    442   PostinstallRunnerAction::StaticType(),
    443   OmahaRequestAction::StaticType()
    444 };
    445 
    446 // Actions that will be built as part of a user-initiated rollback.
    447 const string kRollbackActionTypes[] = {  // NOLINT(runtime/string)
    448   InstallPlanAction::StaticType(),
    449   PostinstallRunnerAction::StaticType(),
    450 };
    451 
    452 }  // namespace
    453 
    454 void UpdateAttempterTest::UpdateTestStart() {
    455   attempter_.set_http_response_code(200);
    456 
    457   // Expect that the device policy is loaded by the UpdateAttempter at some
    458   // point by calling RefreshDevicePolicy.
    459   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
    460   EXPECT_CALL(*device_policy, LoadPolicy())
    461       .Times(testing::AtLeast(1)).WillRepeatedly(Return(true));
    462   attempter_.policy_provider_.reset(
    463       new policy::PolicyProvider(std::move(device_policy)));
    464 
    465   {
    466     InSequence s;
    467     for (size_t i = 0; i < arraysize(kUpdateActionTypes); ++i) {
    468       EXPECT_CALL(*processor_,
    469                   EnqueueAction(Property(&AbstractAction::Type,
    470                                          kUpdateActionTypes[i])));
    471     }
    472     EXPECT_CALL(*processor_, StartProcessing());
    473   }
    474 
    475   attempter_.Update("", "", "", "", false, false);
    476   loop_.PostTask(FROM_HERE,
    477                  base::Bind(&UpdateAttempterTest::UpdateTestVerify,
    478                             base::Unretained(this)));
    479 }
    480 
    481 void UpdateAttempterTest::UpdateTestVerify() {
    482   EXPECT_EQ(0, attempter_.http_response_code());
    483   EXPECT_EQ(&attempter_, processor_->delegate());
    484   EXPECT_EQ(arraysize(kUpdateActionTypes), attempter_.actions_.size());
    485   for (size_t i = 0; i < arraysize(kUpdateActionTypes); ++i) {
    486     EXPECT_EQ(kUpdateActionTypes[i], attempter_.actions_[i]->Type());
    487   }
    488   EXPECT_EQ(attempter_.response_handler_action_.get(),
    489             attempter_.actions_[1].get());
    490   AbstractAction* action_3 = attempter_.actions_[3].get();
    491   ASSERT_NE(nullptr, action_3);
    492   ASSERT_EQ(DownloadAction::StaticType(), action_3->Type());
    493   DownloadAction* download_action = static_cast<DownloadAction*>(action_3);
    494   EXPECT_EQ(&attempter_, download_action->delegate());
    495   EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
    496   loop_.BreakLoop();
    497 }
    498 
    499 void UpdateAttempterTest::RollbackTestStart(
    500     bool enterprise_rollback, bool valid_slot) {
    501   // Create a device policy so that we can change settings.
    502   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
    503   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
    504   fake_system_state_.set_device_policy(device_policy.get());
    505   if (enterprise_rollback) {
    506     // We return an empty owner as this is an enterprise.
    507     EXPECT_CALL(*device_policy, GetOwner(_)).WillRepeatedly(
    508         DoAll(SetArgPointee<0>(string("")),
    509         Return(true)));
    510   } else {
    511     // We return a fake owner as this is an owned consumer device.
    512     EXPECT_CALL(*device_policy, GetOwner(_)).WillRepeatedly(
    513         DoAll(SetArgPointee<0>(string("fake.mail (at) fake.com")),
    514         Return(true)));
    515   }
    516 
    517   attempter_.policy_provider_.reset(
    518       new policy::PolicyProvider(std::move(device_policy)));
    519 
    520   if (valid_slot) {
    521     BootControlInterface::Slot rollback_slot = 1;
    522     LOG(INFO) << "Test Mark Bootable: "
    523               << BootControlInterface::SlotName(rollback_slot);
    524     fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
    525                                                             true);
    526   }
    527 
    528   bool is_rollback_allowed = false;
    529 
    530   // We only allow rollback on devices that are not enterprise enrolled and
    531   // which have a valid slot to rollback to.
    532   if (!enterprise_rollback && valid_slot) {
    533      is_rollback_allowed = true;
    534   }
    535 
    536   if (is_rollback_allowed) {
    537     InSequence s;
    538     for (size_t i = 0; i < arraysize(kRollbackActionTypes); ++i) {
    539       EXPECT_CALL(*processor_,
    540                   EnqueueAction(Property(&AbstractAction::Type,
    541                                          kRollbackActionTypes[i])));
    542     }
    543     EXPECT_CALL(*processor_, StartProcessing());
    544 
    545     EXPECT_TRUE(attempter_.Rollback(true));
    546     loop_.PostTask(FROM_HERE,
    547                    base::Bind(&UpdateAttempterTest::RollbackTestVerify,
    548                               base::Unretained(this)));
    549   } else {
    550     EXPECT_FALSE(attempter_.Rollback(true));
    551     loop_.BreakLoop();
    552   }
    553 }
    554 
    555 void UpdateAttempterTest::RollbackTestVerify() {
    556   // Verifies the actions that were enqueued.
    557   EXPECT_EQ(&attempter_, processor_->delegate());
    558   EXPECT_EQ(arraysize(kRollbackActionTypes), attempter_.actions_.size());
    559   for (size_t i = 0; i < arraysize(kRollbackActionTypes); ++i) {
    560     EXPECT_EQ(kRollbackActionTypes[i], attempter_.actions_[i]->Type());
    561   }
    562   EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
    563   AbstractAction* action_0 = attempter_.actions_[0].get();
    564   ASSERT_NE(nullptr, action_0);
    565   ASSERT_EQ(InstallPlanAction::StaticType(), action_0->Type());
    566   InstallPlanAction* install_plan_action =
    567       static_cast<InstallPlanAction*>(action_0);
    568   InstallPlan* install_plan = install_plan_action->install_plan();
    569   EXPECT_EQ(0U, install_plan->partitions.size());
    570   EXPECT_EQ(install_plan->powerwash_required, true);
    571   loop_.BreakLoop();
    572 }
    573 
    574 TEST_F(UpdateAttempterTest, UpdateTest) {
    575   UpdateTestStart();
    576   loop_.Run();
    577 }
    578 
    579 TEST_F(UpdateAttempterTest, RollbackTest) {
    580   loop_.PostTask(FROM_HERE,
    581                  base::Bind(&UpdateAttempterTest::RollbackTestStart,
    582                             base::Unretained(this),
    583                             false, true));
    584   loop_.Run();
    585 }
    586 
    587 TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
    588   loop_.PostTask(FROM_HERE,
    589                  base::Bind(&UpdateAttempterTest::RollbackTestStart,
    590                             base::Unretained(this),
    591                             false, false));
    592   loop_.Run();
    593 }
    594 
    595 TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
    596   loop_.PostTask(FROM_HERE,
    597                  base::Bind(&UpdateAttempterTest::RollbackTestStart,
    598                             base::Unretained(this),
    599                             true, true));
    600   loop_.Run();
    601 }
    602 
    603 void UpdateAttempterTest::PingOmahaTestStart() {
    604   EXPECT_CALL(*processor_,
    605               EnqueueAction(Property(&AbstractAction::Type,
    606                                      OmahaRequestAction::StaticType())));
    607   EXPECT_CALL(*processor_, StartProcessing());
    608   attempter_.PingOmaha();
    609   ScheduleQuitMainLoop();
    610 }
    611 
    612 TEST_F(UpdateAttempterTest, PingOmahaTest) {
    613   EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
    614   EXPECT_FALSE(attempter_.schedule_updates_called());
    615   // Disable scheduling of subsequnet checks; we're using the DefaultPolicy in
    616   // testing, which is more permissive than we want to handle here.
    617   attempter_.DisableScheduleUpdates();
    618   loop_.PostTask(FROM_HERE,
    619                  base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
    620                             base::Unretained(this)));
    621   brillo::MessageLoopRunMaxIterations(&loop_, 100);
    622   EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
    623   EXPECT_TRUE(attempter_.schedule_updates_called());
    624 }
    625 
    626 TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
    627   MockAction action;
    628   const ErrorCode kCode = ErrorCode::kDownloadTransferError;
    629   attempter_.CreatePendingErrorEvent(&action, kCode);
    630   ASSERT_NE(nullptr, attempter_.error_event_.get());
    631   EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
    632   EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
    633   EXPECT_EQ(
    634       static_cast<ErrorCode>(static_cast<int>(kCode) |
    635                              static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
    636       attempter_.error_event_->error_code);
    637 }
    638 
    639 TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
    640   OmahaResponseHandlerAction *response_action =
    641       new OmahaResponseHandlerAction(&fake_system_state_);
    642   response_action->install_plan_.is_resume = true;
    643   attempter_.response_handler_action_.reset(response_action);
    644   MockAction action;
    645   const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
    646   attempter_.CreatePendingErrorEvent(&action, kCode);
    647   ASSERT_NE(nullptr, attempter_.error_event_.get());
    648   EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
    649   EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
    650   EXPECT_EQ(
    651       static_cast<ErrorCode>(
    652           static_cast<int>(kCode) |
    653           static_cast<int>(ErrorCode::kResumedFlag) |
    654           static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
    655       attempter_.error_event_->error_code);
    656 }
    657 
    658 TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
    659   MockP2PManager mock_p2p_manager;
    660   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    661   mock_p2p_manager.fake().SetP2PEnabled(false);
    662   EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
    663   attempter_.UpdateEngineStarted();
    664 }
    665 
    666 TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
    667   MockP2PManager mock_p2p_manager;
    668   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    669   mock_p2p_manager.fake().SetP2PEnabled(true);
    670   EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
    671   attempter_.UpdateEngineStarted();
    672 }
    673 
    674 TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
    675   MockP2PManager mock_p2p_manager;
    676   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    677   mock_p2p_manager.fake().SetP2PEnabled(true);
    678   mock_p2p_manager.fake().SetCountSharedFilesResult(1);
    679   EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
    680   attempter_.UpdateEngineStarted();
    681 }
    682 
    683 TEST_F(UpdateAttempterTest, P2PNotEnabled) {
    684   loop_.PostTask(FROM_HERE,
    685                  base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
    686                             base::Unretained(this)));
    687   loop_.Run();
    688 }
    689 
    690 void UpdateAttempterTest::P2PNotEnabledStart() {
    691   // If P2P is not enabled, check that we do not attempt housekeeping
    692   // and do not convey that p2p is to be used.
    693   MockP2PManager mock_p2p_manager;
    694   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    695   mock_p2p_manager.fake().SetP2PEnabled(false);
    696   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
    697   attempter_.Update("", "", "", "", false, false);
    698   EXPECT_FALSE(actual_using_p2p_for_downloading_);
    699   EXPECT_FALSE(actual_using_p2p_for_sharing());
    700   ScheduleQuitMainLoop();
    701 }
    702 
    703 TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
    704   loop_.PostTask(FROM_HERE,
    705                  base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
    706                             base::Unretained(this)));
    707   loop_.Run();
    708 }
    709 
    710 void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
    711   // If p2p is enabled, but starting it fails ensure we don't do
    712   // any housekeeping and do not convey that p2p should be used.
    713   MockP2PManager mock_p2p_manager;
    714   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    715   mock_p2p_manager.fake().SetP2PEnabled(true);
    716   mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
    717   mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
    718   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
    719   attempter_.Update("", "", "", "", false, false);
    720   EXPECT_FALSE(actual_using_p2p_for_downloading());
    721   EXPECT_FALSE(actual_using_p2p_for_sharing());
    722   ScheduleQuitMainLoop();
    723 }
    724 
    725 TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
    726   loop_.PostTask(
    727       FROM_HERE,
    728       base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
    729                  base::Unretained(this)));
    730   loop_.Run();
    731 }
    732 
    733 void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
    734   // If p2p is enabled, starting it works but housekeeping fails, ensure
    735   // we do not convey p2p is to be used.
    736   MockP2PManager mock_p2p_manager;
    737   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    738   mock_p2p_manager.fake().SetP2PEnabled(true);
    739   mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
    740   mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
    741   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
    742   attempter_.Update("", "", "", "", false, false);
    743   EXPECT_FALSE(actual_using_p2p_for_downloading());
    744   EXPECT_FALSE(actual_using_p2p_for_sharing());
    745   ScheduleQuitMainLoop();
    746 }
    747 
    748 TEST_F(UpdateAttempterTest, P2PEnabled) {
    749   loop_.PostTask(FROM_HERE,
    750                  base::Bind(&UpdateAttempterTest::P2PEnabledStart,
    751                             base::Unretained(this)));
    752   loop_.Run();
    753 }
    754 
    755 void UpdateAttempterTest::P2PEnabledStart() {
    756   MockP2PManager mock_p2p_manager;
    757   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    758   // If P2P is enabled and starting it works, check that we performed
    759   // housekeeping and that we convey p2p should be used.
    760   mock_p2p_manager.fake().SetP2PEnabled(true);
    761   mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
    762   mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
    763   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
    764   attempter_.Update("", "", "", "", false, false);
    765   EXPECT_TRUE(actual_using_p2p_for_downloading());
    766   EXPECT_TRUE(actual_using_p2p_for_sharing());
    767   ScheduleQuitMainLoop();
    768 }
    769 
    770 TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
    771   loop_.PostTask(FROM_HERE,
    772                  base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
    773                             base::Unretained(this)));
    774   loop_.Run();
    775 }
    776 
    777 void UpdateAttempterTest::P2PEnabledInteractiveStart() {
    778   MockP2PManager mock_p2p_manager;
    779   fake_system_state_.set_p2p_manager(&mock_p2p_manager);
    780   // For an interactive check, if P2P is enabled and starting it
    781   // works, check that we performed housekeeping and that we convey
    782   // p2p should be used for sharing but NOT for downloading.
    783   mock_p2p_manager.fake().SetP2PEnabled(true);
    784   mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
    785   mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
    786   EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
    787   attempter_.Update("", "", "", "", false, true /* interactive */);
    788   EXPECT_FALSE(actual_using_p2p_for_downloading());
    789   EXPECT_TRUE(actual_using_p2p_for_sharing());
    790   ScheduleQuitMainLoop();
    791 }
    792 
    793 TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
    794   loop_.PostTask(
    795       FROM_HERE,
    796       base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
    797                  base::Unretained(this)));
    798   loop_.Run();
    799 }
    800 
    801 // Tests that the scatter_factor_in_seconds value is properly fetched
    802 // from the device policy.
    803 void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
    804   int64_t scatter_factor_in_seconds = 36000;
    805 
    806   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
    807   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
    808   fake_system_state_.set_device_policy(device_policy.get());
    809 
    810   EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
    811       .WillRepeatedly(DoAll(
    812           SetArgPointee<0>(scatter_factor_in_seconds),
    813           Return(true)));
    814 
    815   attempter_.policy_provider_.reset(
    816       new policy::PolicyProvider(std::move(device_policy)));
    817 
    818   attempter_.Update("", "", "", "", false, false);
    819   EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
    820 
    821   ScheduleQuitMainLoop();
    822 }
    823 
    824 TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
    825   loop_.PostTask(
    826       FROM_HERE,
    827       base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
    828                  base::Unretained(this)));
    829   loop_.Run();
    830 }
    831 
    832 void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
    833   // Tests that the scatter_factor_in_seconds value is properly fetched
    834   // from the device policy and is decremented if value > 0.
    835   int64_t initial_value = 5;
    836   FakePrefs fake_prefs;
    837   attempter_.prefs_ = &fake_prefs;
    838 
    839   fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
    840 
    841   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
    842 
    843   int64_t scatter_factor_in_seconds = 10;
    844 
    845   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
    846   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
    847   fake_system_state_.set_device_policy(device_policy.get());
    848 
    849   EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
    850       .WillRepeatedly(DoAll(
    851           SetArgPointee<0>(scatter_factor_in_seconds),
    852           Return(true)));
    853 
    854   attempter_.policy_provider_.reset(
    855       new policy::PolicyProvider(std::move(device_policy)));
    856 
    857   attempter_.Update("", "", "", "", false, false);
    858   EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
    859 
    860   // Make sure the file still exists.
    861   EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
    862 
    863   int64_t new_value;
    864   EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
    865   EXPECT_EQ(initial_value - 1, new_value);
    866 
    867   EXPECT_TRUE(
    868       attempter_.omaha_request_params_->update_check_count_wait_enabled());
    869 
    870   // However, if the count is already 0, it's not decremented. Test that.
    871   initial_value = 0;
    872   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
    873   attempter_.Update("", "", "", "", false, false);
    874   EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
    875   EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
    876   EXPECT_EQ(initial_value, new_value);
    877 
    878   ScheduleQuitMainLoop();
    879 }
    880 
    881 TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
    882   loop_.PostTask(FROM_HERE, base::Bind(
    883       &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
    884       base::Unretained(this)));
    885   loop_.Run();
    886 }
    887 
    888 void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
    889   // Tests that no scattering logic is enabled if the update check
    890   // is manually done (as opposed to a scheduled update check)
    891   int64_t initial_value = 8;
    892   FakePrefs fake_prefs;
    893   attempter_.prefs_ = &fake_prefs;
    894 
    895   fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
    896   fake_system_state_.set_prefs(&fake_prefs);
    897 
    898   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsWallClockWaitPeriod, initial_value));
    899   EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
    900 
    901   // make sure scatter_factor is non-zero as scattering is disabled
    902   // otherwise.
    903   int64_t scatter_factor_in_seconds = 50;
    904 
    905   auto device_policy = std::make_unique<policy::MockDevicePolicy>();
    906   EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
    907   fake_system_state_.set_device_policy(device_policy.get());
    908 
    909   EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
    910       .WillRepeatedly(DoAll(
    911           SetArgPointee<0>(scatter_factor_in_seconds),
    912           Return(true)));
    913 
    914   attempter_.policy_provider_.reset(
    915       new policy::PolicyProvider(std::move(device_policy)));
    916 
    917   // Trigger an interactive check so we can test that scattering is disabled.
    918   attempter_.Update("", "", "", "", false, true);
    919   EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
    920 
    921   // Make sure scattering is disabled for manual (i.e. user initiated) update
    922   // checks and all artifacts are removed.
    923   EXPECT_FALSE(
    924       attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
    925   EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockWaitPeriod));
    926   EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
    927   EXPECT_FALSE(
    928       attempter_.omaha_request_params_->update_check_count_wait_enabled());
    929   EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
    930 
    931   ScheduleQuitMainLoop();
    932 }
    933 
    934 // Checks that we only report daily metrics at most every 24 hours.
    935 TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
    936   FakeClock fake_clock;
    937   FakePrefs fake_prefs;
    938 
    939   fake_system_state_.set_clock(&fake_clock);
    940   fake_system_state_.set_prefs(&fake_prefs);
    941 
    942   Time epoch = Time::FromInternalValue(0);
    943   fake_clock.SetWallclockTime(epoch);
    944 
    945   // If there is no kPrefsDailyMetricsLastReportedAt state variable,
    946   // we should report.
    947   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
    948   // We should not report again if no time has passed.
    949   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    950 
    951   // We should not report if only 10 hours has passed.
    952   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
    953   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    954 
    955   // We should not report if only 24 hours - 1 sec has passed.
    956   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
    957                               TimeDelta::FromSeconds(1));
    958   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    959 
    960   // We should report if 24 hours has passed.
    961   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
    962   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
    963 
    964   // But then we should not report again..
    965   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    966 
    967   // .. until another 24 hours has passed
    968   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
    969   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    970   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
    971   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
    972   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    973 
    974   // .. and another 24 hours
    975   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
    976   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    977   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
    978   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
    979   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    980 
    981   // If the span between time of reporting and present time is
    982   // negative, we report. This is in order to reset the timestamp and
    983   // avoid an edge condition whereby a distant point in the future is
    984   // in the state variable resulting in us never ever reporting again.
    985   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
    986   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
    987   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    988 
    989   // In this case we should not update until the clock reads 71 + 24 = 95.
    990   // Check that.
    991   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
    992   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    993   fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
    994   EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
    995   EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
    996 }
    997 
    998 TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
    999   FakeClock fake_clock;
   1000   fake_clock.SetBootTime(Time::FromTimeT(42));
   1001   fake_system_state_.set_clock(&fake_clock);
   1002   FakePrefs fake_prefs;
   1003   fake_system_state_.set_prefs(&fake_prefs);
   1004   attempter_.Init();
   1005 
   1006   Time boot_time;
   1007   EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
   1008 
   1009   attempter_.WriteUpdateCompletedMarker();
   1010 
   1011   EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
   1012   EXPECT_EQ(boot_time.ToTimeT(), 42);
   1013 }
   1014 
   1015 TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
   1016   fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
   1017   EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
   1018 }
   1019 
   1020 TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
   1021   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
   1022   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
   1023   EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
   1024 }
   1025 
   1026 TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
   1027   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
   1028   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
   1029   EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
   1030 }
   1031 
   1032 TEST_F(UpdateAttempterTest, CheckForUpdateAUTest) {
   1033   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
   1034   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
   1035   attempter_.CheckForUpdate("", "autest", UpdateAttemptFlags::kNone);
   1036   EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
   1037 }
   1038 
   1039 TEST_F(UpdateAttempterTest, CheckForUpdateScheduledAUTest) {
   1040   fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
   1041   fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
   1042   attempter_.CheckForUpdate("", "autest-scheduled", UpdateAttemptFlags::kNone);
   1043   EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
   1044 }
   1045 
   1046 TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
   1047   attempter_.CalculateUpdateParams("", "", "", "1234", false, false);
   1048   EXPECT_EQ("1234",
   1049             fake_system_state_.request_params()->target_version_prefix());
   1050 
   1051   attempter_.CalculateUpdateParams("", "", "", "", false, false);
   1052   EXPECT_TRUE(
   1053       fake_system_state_.request_params()->target_version_prefix().empty());
   1054 }
   1055 
   1056 TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
   1057   // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
   1058   // but the update is being deferred by the Policy.
   1059   OmahaResponseHandlerAction* response_action =
   1060       new OmahaResponseHandlerAction(&fake_system_state_);
   1061   response_action->install_plan_.version = "a.b.c.d";
   1062   response_action->install_plan_.system_version = "b.c.d.e";
   1063   response_action->install_plan_.payloads.push_back(
   1064       {.size = 1234ULL, .type = InstallPayloadType::kFull});
   1065   attempter_.response_handler_action_.reset(response_action);
   1066   // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
   1067   // completed, with the deferred-update error code.
   1068   attempter_.ActionCompleted(
   1069       nullptr, response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
   1070   {
   1071     UpdateEngineStatus status;
   1072     attempter_.GetStatus(&status);
   1073     EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
   1074     EXPECT_EQ(response_action->install_plan_.version, status.new_version);
   1075     EXPECT_EQ(response_action->install_plan_.system_version,
   1076               status.new_system_version);
   1077     EXPECT_EQ(response_action->install_plan_.payloads[0].size,
   1078               status.new_size_bytes);
   1079   }
   1080   // An "error" event should have been created to tell Omaha that the update is
   1081   // being deferred.
   1082   EXPECT_TRUE(nullptr != attempter_.error_event_);
   1083   EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
   1084   EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
   1085   ErrorCode expected_code = static_cast<ErrorCode>(
   1086       static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
   1087       static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
   1088   EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
   1089   // End the processing
   1090   attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
   1091   // Validate the state of the attempter.
   1092   {
   1093     UpdateEngineStatus status;
   1094     attempter_.GetStatus(&status);
   1095     EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
   1096     EXPECT_EQ(response_action->install_plan_.version, status.new_version);
   1097     EXPECT_EQ(response_action->install_plan_.system_version,
   1098               status.new_system_version);
   1099     EXPECT_EQ(response_action->install_plan_.payloads[0].size,
   1100               status.new_size_bytes);
   1101   }
   1102 }
   1103 
   1104 TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
   1105   EXPECT_FALSE(attempter_.IsUpdateRunningOrScheduled());
   1106   // Verify in-progress update with UPDATE_AVAILABLE is running
   1107   attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
   1108   EXPECT_TRUE(attempter_.IsUpdateRunningOrScheduled());
   1109 }
   1110 
   1111 TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
   1112   attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
   1113 
   1114   UpdateCheckParams params = {.updates_enabled = true};
   1115   attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
   1116 
   1117   EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
   1118             attempter_.GetCurrentUpdateAttemptFlags());
   1119 }
   1120 
   1121 TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
   1122   attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
   1123 
   1124   attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
   1125   EXPECT_EQ(UpdateAttemptFlags::kNone,
   1126             attempter_.GetCurrentUpdateAttemptFlags());
   1127 }
   1128 
   1129 TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
   1130   attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
   1131 
   1132   // This tests that when CheckForUpdate() is called with the non-interactive
   1133   // flag set, that it doesn't change the current UpdateAttemptFlags.
   1134   attempter_.CheckForUpdate("",
   1135                             "",
   1136                             UpdateAttemptFlags::kFlagNonInteractive |
   1137                                 UpdateAttemptFlags::kFlagRestrictDownload);
   1138   EXPECT_EQ(UpdateAttemptFlags::kNone,
   1139             attempter_.GetCurrentUpdateAttemptFlags());
   1140 }
   1141 
   1142 }  // namespace chromeos_update_engine
   1143