blob: 354416eb5f296b4817de136540f05f5267d360c9 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
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//
Darin Petkovf42cc1c2010-09-01 09:03:02 -070016
Alex Deymo2c0db7b2014-11-04 12:23:39 -080017#include "update_engine/update_attempter.h"
18
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
Jae Hoon Kim051627a2019-09-03 12:56:32 -070021#include <limits>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070022#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023#include <memory>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070024#include <string>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070025#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026
Ben Chan06c76a42014-09-05 08:21:06 -070027#include <base/files/file_util.h>
Alex Deymo0b3db6b2015-08-10 15:19:37 -070028#include <base/message_loop/message_loop.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070029#include <brillo/message_loops/base_message_loop.h>
30#include <brillo/message_loops/message_loop.h>
31#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070032#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020033#include <policy/libpolicy.h>
34#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020035#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070036
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070037#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080038#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080039#include "update_engine/common/fake_clock.h"
40#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080041#include "update_engine/common/mock_action.h"
42#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080043#include "update_engine/common/mock_http_fetcher.h"
44#include "update_engine/common/mock_prefs.h"
45#include "update_engine/common/platform_constants.h"
46#include "update_engine/common/prefs.h"
47#include "update_engine/common/test_utils.h"
48#include "update_engine/common/utils.h"
Gilad Arnold5bb4c902014-04-10 12:32:13 -070049#include "update_engine/fake_system_state.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070050#include "update_engine/libcurl_http_fetcher.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070051#include "update_engine/mock_p2p_manager.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080052#include "update_engine/mock_payload_state.h"
Aaron Wood9321f502017-09-07 11:18:54 -070053#include "update_engine/mock_service_observer.h"
Jae Hoon Kim051627a2019-09-03 12:56:32 -070054#include "update_engine/omaha_utils.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080055#include "update_engine/payload_consumer/filesystem_verifier_action.h"
56#include "update_engine/payload_consumer/install_plan.h"
57#include "update_engine/payload_consumer/payload_constants.h"
58#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070059#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070060#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070061
David Zeuthen985b1122013-10-09 12:13:15 -070062using base::Time;
63using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070064using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070065using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070066using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070067using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070068using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070069using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070070using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070071using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070072using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070073using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070074using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070075using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070076using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070077using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070078using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070079using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070080using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070081using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080082using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070083using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070084using testing::Property;
85using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070086using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020087using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080088using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070089using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070090using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070091using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070092using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070093
94namespace chromeos_update_engine {
95
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080096namespace {
97
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070098const UpdateStatus kNonIdleUpdateStatuses[] = {
99 UpdateStatus::CHECKING_FOR_UPDATE,
100 UpdateStatus::UPDATE_AVAILABLE,
101 UpdateStatus::DOWNLOADING,
102 UpdateStatus::VERIFYING,
103 UpdateStatus::FINALIZING,
104 UpdateStatus::UPDATED_NEED_REBOOT,
105 UpdateStatus::REPORTING_ERROR_EVENT,
106 UpdateStatus::ATTEMPTING_ROLLBACK,
107 UpdateStatus::DISABLED,
108 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
109};
110
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700111struct CheckForUpdateTestParams {
112 // Setups + Inputs:
113 UpdateStatus status = UpdateStatus::IDLE;
114 string app_version = "fake_app_version";
115 string omaha_url = "fake_omaha_url";
116 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
117 bool is_official_build = true;
118 bool are_dev_features_enabled = false;
119
120 // Expects:
121 string expected_forced_app_version = "";
122 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700123 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700124 bool expected_result = true;
125};
126
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700127struct OnUpdateScheduledTestParams {
128 // Setups + Inputs:
129 UpdateCheckParams params = {};
130 EvalStatus status = EvalStatus::kFailed;
131 // Expects:
132 UpdateStatus exit_status = UpdateStatus::IDLE;
133 bool should_schedule_updates_be_called = false;
134 bool should_update_be_called = false;
135};
136
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700137struct ProcessingDoneTestParams {
138 // Setups + Inputs:
139 bool is_install = false;
140 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
141 ActionProcessor* processor = nullptr;
142 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700143 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700144
145 // Expects:
146 const bool kExpectedIsInstall = false;
147 bool should_schedule_updates_be_called = true;
148 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700149 bool should_install_completed_be_called = false;
150 bool should_update_completed_be_called = false;
151 vector<string> args_to_install_completed;
152 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700153};
154
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800155class MockDlcService : public DlcServiceInterface {
156 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700157 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700158 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
159 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800160};
161
162} // namespace
163
Marton Hunyadya0302682018-05-16 18:52:13 +0200164const char kRollbackVersion[] = "10575.39.2";
165
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700166// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700167// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700168// methods.
169class UpdateAttempterUnderTest : public UpdateAttempter {
170 public:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700171 explicit UpdateAttempterUnderTest(SystemState* system_state)
172 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700173
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700174 void Update(const std::string& app_version,
175 const std::string& omaha_url,
176 const std::string& target_channel,
Amin Hassani37b67232020-08-13 09:29:48 -0700177 const std::string& lts_tag,
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700178 const std::string& target_version_prefix,
179 bool rollback_allowed,
180 bool rollback_data_save_requested,
181 int rollback_allowed_milestones,
182 bool obey_proxies,
183 bool interactive) override {
184 update_called_ = true;
185 if (do_update_) {
186 UpdateAttempter::Update(app_version,
187 omaha_url,
188 target_channel,
Amin Hassani37b67232020-08-13 09:29:48 -0700189 lts_tag,
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700190 target_version_prefix,
191 rollback_allowed,
192 rollback_data_save_requested,
193 rollback_allowed_milestones,
194 obey_proxies,
195 interactive);
196 return;
197 }
198 LOG(INFO) << "[TEST] Update() disabled.";
199 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
200 }
201
202 void DisableUpdate() { do_update_ = false; }
203
204 bool WasUpdateCalled() const { return update_called_; }
205
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700206 // Wrap the update scheduling method, allowing us to opt out of scheduled
207 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700208 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700209 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700210 if (do_schedule_updates_)
211 return UpdateAttempter::ScheduleUpdates();
212 LOG(INFO) << "[TEST] Update scheduling disabled.";
213 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700214 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700215 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700216
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700217 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
218
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700219 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700220 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700221
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700222 // Need to expose following private members of |UpdateAttempter| for tests.
223 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700224 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800225
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700226 // Need to expose |waiting_for_scheduled_check_| for testing.
227 void SetWaitingForScheduledCheck(bool waiting) {
228 waiting_for_scheduled_check_ = waiting;
229 }
230
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700231 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700232 // Used for overrides of |Update()|.
233 bool update_called_ = false;
234 bool do_update_ = true;
235
236 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700237 bool schedule_updates_called_ = false;
238 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700239};
240
241class UpdateAttempterTest : public ::testing::Test {
242 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700243 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600244 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300245 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700246 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700247 fake_system_state_.set_connection_manager(&mock_connection_manager);
248 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800249 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700250 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700251 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700252
Alex Deymo33e91e72015-12-01 18:26:08 -0300253 certificate_checker_.Init();
254
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800255 attempter_.set_forced_update_pending_callback(
256 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700257 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700258 attempter_.Init();
Jay Srinivasan43488792012-06-19 00:25:31 -0700259 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700260
Alex Deymo610277e2014-11-11 21:18:11 -0800261 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700262 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700263 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700264 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700265 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700266 EXPECT_EQ(0.0, attempter_.download_progress_);
267 EXPECT_EQ(0, attempter_.last_checked_time_);
268 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700269 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800270 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700271 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700272 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700273
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700274 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700275 actual_using_p2p_for_downloading_ = false;
276 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
277 SetUsingP2PForDownloading(_))
278 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
279 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
280 GetUsingP2PForDownloading())
281 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
282 actual_using_p2p_for_sharing_ = false;
283 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
284 SetUsingP2PForSharing(_))
285 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
286 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
287 GetUsingP2PForDownloading())
288 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700289 }
290
Alex Deymo60ca1a72015-06-18 18:19:15 -0700291 public:
292 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200293
Alex Deymo60ca1a72015-06-18 18:19:15 -0700294 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800295 void UpdateTestStart();
296 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700297 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700298 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700299 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700300 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700301 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700302 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700303 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700304 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700305 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700306 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700307 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700308 void SessionIdTestChange();
309 void SessionIdTestEnforceEmptyStrPingOmaha();
310 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700311 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200312 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200313 void ResetRollbackHappenedStart(bool is_consumer,
314 bool is_policy_available,
315 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700316 // Staging related callbacks.
317 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
318 void CheckStagingOff();
319 void StagingSetsPrefsAndTurnsOffScatteringStart();
320 void StagingOffIfInteractiveStart();
321 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700322
Gilad Arnold74b5f552014-10-07 08:17:16 -0700323 bool actual_using_p2p_for_downloading() {
324 return actual_using_p2p_for_downloading_;
325 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800326 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700327
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700328 // |CheckForUpdate()| related member functions.
329 void TestCheckForUpdate();
330
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700331 // |OnUpdateScheduled()| related member functions.
332 void TestOnUpdateScheduled();
333
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700334 // |ProcessingDone()| related member functions.
335 void TestProcessingDone();
336
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700337 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700338 brillo::BaseMessageLoop loop_{&base_loop_};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700339
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700340 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700341 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300342 OpenSSLWrapper openssl_wrapper_;
343 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800344 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700345 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700346
Alex Deymo8427b4a2014-11-05 14:00:32 -0800347 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700348 NiceMock<MockPrefs>*
349 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800350 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700351
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700352 // |CheckForUpdate()| test params.
353 CheckForUpdateTestParams cfu_params_;
354
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700355 // |OnUpdateScheduled()| test params.
356 OnUpdateScheduledTestParams ous_params_;
357
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700358 // |ProcessingDone()| test params.
359 ProcessingDoneTestParams pd_params_;
360
Gilad Arnold74b5f552014-10-07 08:17:16 -0700361 bool actual_using_p2p_for_downloading_;
362 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700363};
364
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700365void UpdateAttempterTest::TestCheckForUpdate() {
366 // Setup
367 attempter_.status_ = cfu_params_.status;
368 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
369 cfu_params_.is_official_build);
370 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
371 cfu_params_.are_dev_features_enabled);
372
373 // Invocation
374 EXPECT_EQ(
375 cfu_params_.expected_result,
376 attempter_.CheckForUpdate(
377 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
378
379 // Verify
380 EXPECT_EQ(cfu_params_.expected_forced_app_version,
381 attempter_.forced_app_version());
382 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
383 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700384 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
385 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700386}
387
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700388void UpdateAttempterTest::TestProcessingDone() {
389 // Setup
390 attempter_.DisableScheduleUpdates();
391 attempter_.is_install_ = pd_params_.is_install;
392 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700393 attempter_.omaha_request_params_->set_dlc_apps_params(
394 pd_params_.dlc_apps_params);
395
396 // Expects
397 if (pd_params_.should_install_completed_be_called)
398 EXPECT_CALL(mock_dlcservice_,
399 InstallCompleted(pd_params_.args_to_install_completed))
400 .WillOnce(Return(true));
401 else
402 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
403 if (pd_params_.should_update_completed_be_called)
404 EXPECT_CALL(mock_dlcservice_,
405 UpdateCompleted(pd_params_.args_to_update_completed))
406 .WillOnce(Return(true));
407 else
408 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700409
410 // Invocation
411 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
412
413 // Verify
414 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
415 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
416 attempter_.WasScheduleUpdatesCalled());
417 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
418}
419
Alex Deymo60ca1a72015-06-18 18:19:15 -0700420void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700421 loop_.PostTask(
422 FROM_HERE,
423 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
424 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700425}
426
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700427void UpdateAttempterTest::SessionIdTestChange() {
428 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
429 const auto old_session_id = attempter_.session_id_;
Amin Hassani37b67232020-08-13 09:29:48 -0700430 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700431 EXPECT_NE(old_session_id, attempter_.session_id_);
432 ScheduleQuitMainLoop();
433}
434
435TEST_F(UpdateAttempterTest, SessionIdTestChange) {
436 loop_.PostTask(FROM_HERE,
437 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
438 base::Unretained(this)));
439 loop_.Run();
440}
441
442void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
443 // The |session_id_| should not be changed and should remain as an empty
444 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
445 // and |PingOmaha()| is called.
446 attempter_.DisableScheduleUpdates();
447 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
448 const auto old_session_id = attempter_.session_id_;
449 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
450 if (aa->Type() == OmahaRequestAction::StaticType()) {
451 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
452 }
453 };
454 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
455 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
456 EXPECT_CALL(*processor_, StartProcessing());
457 attempter_.PingOmaha();
458 EXPECT_EQ(old_session_id, attempter_.session_id_);
459 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
460 ScheduleQuitMainLoop();
461}
462
463TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
464 loop_.PostTask(
465 FROM_HERE,
466 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
467 base::Unretained(this)));
468 loop_.Run();
469}
470
471void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
472 // All session IDs passed into |OmahaRequestActions| should be enforced to
473 // have the same value in |BuildUpdateActions()|.
474 unordered_set<string> session_ids;
475 // Gather all the session IDs being passed to |OmahaRequestActions|.
476 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
477 if (aa->Type() == OmahaRequestAction::StaticType())
478 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
479 };
480 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
481 .WillRepeatedly(Invoke(CheckSessionId));
482 attempter_.BuildUpdateActions(false);
483 // Validate that all the session IDs are the same.
484 EXPECT_EQ(1, session_ids.size());
485 ScheduleQuitMainLoop();
486}
487
488TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
489 loop_.PostTask(
490 FROM_HERE,
491 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
492 base::Unretained(this)));
493 loop_.Run();
494}
495
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700496void UpdateAttempterTest::SessionIdTestInDownloadAction() {
497 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
498 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
499 string header_value;
500 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
501 if (aa->Type() == DownloadAction::StaticType()) {
502 DownloadAction* da = static_cast<DownloadAction*>(aa);
503 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
504 &header_value));
505 }
506 };
507 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
508 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
509 attempter_.BuildUpdateActions(false);
510 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
511 EXPECT_EQ(attempter_.session_id_, header_value);
512 ScheduleQuitMainLoop();
513}
514
515TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
516 loop_.PostTask(FROM_HERE,
517 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
518 base::Unretained(this)));
519 loop_.Run();
520}
521
Darin Petkov1b003102010-11-30 10:18:36 -0800522TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700523 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800524 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700525 DownloadAction action(prefs_,
526 nullptr,
527 nullptr,
528 nullptr,
529 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700530 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800531 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700532 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700533 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700534 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700535 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800536}
537
538TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800539 MockAction action;
540 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700541 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800542 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800543 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700544 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
545 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800546}
547
Aaron Wood9321f502017-09-07 11:18:54 -0700548TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
549 // Simple test case, where all the values match (nothing was skipped)
550 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
551 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
552 uint64_t bytes_received_1 = bytes_progressed_1;
553 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
554 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
555
556 double progress_1 =
557 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
558 double progress_2 =
559 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
560
561 EXPECT_EQ(0.0, attempter_.download_progress_);
562 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700563 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700564 attempter_.new_payload_size_ = bytes_total;
565 NiceMock<MockServiceObserver> observer;
566 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700567 SendStatusUpdate(AllOf(
568 Field(&UpdateEngineStatus::progress, progress_1),
569 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
570 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700571 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700572 SendStatusUpdate(AllOf(
573 Field(&UpdateEngineStatus::progress, progress_2),
574 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
575 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700576 attempter_.AddObserver(&observer);
577 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
578 EXPECT_EQ(progress_1, attempter_.download_progress_);
579 // This iteration validates that a later set of updates to the variables are
580 // properly handled (so that |getStatus()| will return the same progress info
581 // as the callback is receiving.
582 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
583 EXPECT_EQ(progress_2, attempter_.download_progress_);
584}
585
586TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700587 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700588 // first bytes are received.
589 uint64_t bytes_progressed = 1024 * 1024; // 1MB
590 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
591 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
592 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
593 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700594 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700595 attempter_.new_payload_size_ = bytes_total;
596 EXPECT_EQ(0.0, attempter_.download_progress_);
597 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700598 EXPECT_CALL(observer,
599 SendStatusUpdate(AllOf(
600 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
601 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700602 attempter_.AddObserver(&observer);
603 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
604 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
605}
606
607TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
608 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700609 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700610 uint64_t bytes_progressed = 0; // ignored
611 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
612 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
613 attempter_.status_ = UpdateStatus::DOWNLOADING;
614 attempter_.new_payload_size_ = bytes_total;
615 EXPECT_EQ(0.0, attempter_.download_progress_);
616 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700617 EXPECT_CALL(observer,
618 SendStatusUpdate(AllOf(
619 Field(&UpdateEngineStatus::progress, 1.0),
620 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
621 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700622 attempter_.AddObserver(&observer);
623 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
624 EXPECT_EQ(1.0, attempter_.download_progress_);
625}
626
Darin Petkov1b003102010-11-30 10:18:36 -0800627TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700628 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800629 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800630 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700631 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800632 ObjectCollectorAction<OmahaResponse> collector_action;
633 BondActions(&action, &collector_action);
634 OmahaResponse response;
635 response.poll_interval = 234;
636 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800637 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700638 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800639 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700640 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800641 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700642 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800643}
644
Alex Deymo30534502015-07-20 15:06:33 -0700645TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700646 FakePrefs fake_prefs;
647 string boot_id;
648 EXPECT_TRUE(utils::GetBootId(&boot_id));
649 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
650 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700651 attempter_.Init();
652 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700653}
654
655TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700656 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700657 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700658
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700659 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800660 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700661 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700662 EXPECT_EQ(ErrorCode::kOmahaRequestError,
663 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700664 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800665 EXPECT_EQ(
666 ErrorCode::kOmahaResponseHandlerError,
667 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700668 DynamicPartitionControlStub dynamic_control_stub;
669 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800670 EXPECT_EQ(
671 ErrorCode::kFilesystemVerifierError,
672 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300673 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700674 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800675 EXPECT_EQ(
676 ErrorCode::kPostinstallRunnerError,
677 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800678 MockAction action_mock;
679 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700680 EXPECT_EQ(ErrorCode::kError,
681 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700682}
683
Darin Petkov36275772010-10-01 11:40:57 -0700684TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700685 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800686 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700687 .WillOnce(Return(false));
688 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700689 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800690 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800691 .WillOnce(
692 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
693 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700694 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700695 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800696 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800697 .WillOnce(
698 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
699 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700700 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700701 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800702 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700703 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700704 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700705}
706
707TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800708 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700709 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700710 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
711 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800712 .WillOnce(
713 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
714 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800715 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700716 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800717 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700718 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800719 EXPECT_CALL(*prefs_,
720 SetInt64(kPrefsDeltaUpdateFailures,
721 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
722 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700723 attempter_.MarkDeltaUpdateFailure();
724}
725
Darin Petkov1b003102010-11-30 10:18:36 -0800726TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
727 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
728 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700729 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800730 .Times(0);
731 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700732 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800733 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700734 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700735 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700736 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800737 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700738 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800739}
740
741TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
742 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700743 EnqueueAction(Pointee(Property(
744 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700745 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700746 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700747 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800748 attempter_.error_event_.reset(new OmahaEvent(
749 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800750 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700751 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800752}
753
Darin Petkove6ef2f82011-03-07 17:31:11 -0800754namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700755// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200756vector<string> GetUpdateActionTypes() {
757 return {OmahaRequestAction::StaticType(),
758 OmahaResponseHandlerAction::StaticType(),
759 UpdateBootFlagsAction::StaticType(),
760 OmahaRequestAction::StaticType(),
761 DownloadAction::StaticType(),
762 OmahaRequestAction::StaticType(),
763 FilesystemVerifierAction::StaticType(),
764 PostinstallRunnerAction::StaticType(),
765 OmahaRequestAction::StaticType()};
766}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700767
768// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200769vector<string> GetRollbackActionTypes() {
770 return {InstallPlanAction::StaticType(),
771 PostinstallRunnerAction::StaticType()};
772}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700773
Adolfo Victoria497044c2018-07-18 07:51:42 -0700774const StagingSchedule kValidStagingSchedule = {
775 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
776
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700777} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800778
779void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700780 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700781
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700782 // Expect that the device policy is loaded by the |UpdateAttempter| at some
783 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100784 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700785 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800786 .Times(testing::AtLeast(1))
787 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100788 attempter_.policy_provider_.reset(
789 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700790
791 {
792 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200793 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700794 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700795 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200796 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700797 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700798 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700799 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700800
Amin Hassani37b67232020-08-13 09:29:48 -0700801 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700802 loop_.PostTask(FROM_HERE,
803 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
804 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800805}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700806
Darin Petkove6ef2f82011-03-07 17:31:11 -0800807void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700808 EXPECT_EQ(0, attempter_.http_response_code());
809 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700810 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700811 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800812}
813
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800814void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
815 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700816 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100817 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700818 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100819 fake_system_state_.set_device_policy(device_policy.get());
820 if (enterprise_rollback) {
821 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800822 EXPECT_CALL(*device_policy, GetOwner(_))
823 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100824 } else {
825 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800826 EXPECT_CALL(*device_policy, GetOwner(_))
827 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
828 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100829 }
830
831 attempter_.policy_provider_.reset(
832 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700833
Alex Deymo763e7db2015-08-27 21:08:08 -0700834 if (valid_slot) {
835 BootControlInterface::Slot rollback_slot = 1;
836 LOG(INFO) << "Test Mark Bootable: "
837 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700838 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
839 true);
Don Garrett6646b442013-11-13 15:29:11 -0800840 }
841
Chris Sosa28e479c2013-07-12 11:39:53 -0700842 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700843
Chris Sosad38b1132014-03-25 10:43:59 -0700844 // We only allow rollback on devices that are not enterprise enrolled and
845 // which have a valid slot to rollback to.
846 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800847 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700848 }
849
Chris Sosa28e479c2013-07-12 11:39:53 -0700850 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700851 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200852 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700853 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200854 EnqueueAction(Pointee(
855 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700856 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700857 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700858
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700859 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700860 loop_.PostTask(FROM_HERE,
861 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
862 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700863 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700864 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700865 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700866 }
867}
868
869void UpdateAttempterTest::RollbackTestVerify() {
870 // Verifies the actions that were enqueued.
871 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700872 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700873 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
874 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700875 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700876}
877
Darin Petkove6ef2f82011-03-07 17:31:11 -0800878TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700879 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700880 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700881}
882
Chris Sosa76a29ae2013-07-11 17:59:24 -0700883TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700884 loop_.PostTask(FROM_HERE,
885 base::Bind(&UpdateAttempterTest::RollbackTestStart,
886 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800887 false,
888 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700889 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700890}
891
Don Garrett6646b442013-11-13 15:29:11 -0800892TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700893 loop_.PostTask(FROM_HERE,
894 base::Bind(&UpdateAttempterTest::RollbackTestStart,
895 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800896 false,
897 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700898 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800899}
900
Chris Sosa76a29ae2013-07-11 17:59:24 -0700901TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700902 loop_.PostTask(FROM_HERE,
903 base::Bind(&UpdateAttempterTest::RollbackTestStart,
904 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800905 true,
906 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700907 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700908}
909
Thieu Le116fda32011-04-19 11:01:54 -0700910void UpdateAttempterTest::PingOmahaTestStart() {
911 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700912 EnqueueAction(Pointee(Property(
913 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700914 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700915 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700916 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700917}
918
919TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700920 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700921 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700922 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700923 // testing, which is more permissive than we want to handle here.
924 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700925 loop_.PostTask(FROM_HERE,
926 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
927 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700928 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700929 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700930 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700931}
932
Darin Petkov18c7bce2011-06-16 14:07:00 -0700933TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800934 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700935 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700936 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700937 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700938 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
939 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700940 EXPECT_EQ(
941 static_cast<ErrorCode>(static_cast<int>(kCode) |
942 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
943 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700944}
945
946TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700947 attempter_.install_plan_.reset(new InstallPlan);
948 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800949 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700950 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700951 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700952 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700953 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
954 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700955 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800956 static_cast<ErrorCode>(static_cast<int>(kCode) |
957 static_cast<int>(ErrorCode::kResumedFlag) |
958 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700959 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700960}
961
David Zeuthen8f191b22013-08-06 12:27:50 -0700962TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
963 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700964 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700965 mock_p2p_manager.fake().SetP2PEnabled(false);
966 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
967 attempter_.UpdateEngineStarted();
968}
969
970TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
971 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700972 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700973 mock_p2p_manager.fake().SetP2PEnabled(true);
974 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
975 attempter_.UpdateEngineStarted();
976}
977
978TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
979 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700980 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700981 mock_p2p_manager.fake().SetP2PEnabled(true);
982 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700983 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700984 attempter_.UpdateEngineStarted();
985}
986
987TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700988 loop_.PostTask(FROM_HERE,
989 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
990 base::Unretained(this)));
991 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700992}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700993
David Zeuthen8f191b22013-08-06 12:27:50 -0700994void UpdateAttempterTest::P2PNotEnabledStart() {
995 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700996 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700997 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700998 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700999 mock_p2p_manager.fake().SetP2PEnabled(false);
1000 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassani37b67232020-08-13 09:29:48 -07001001 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -07001002 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001003 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001004 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001005}
1006
1007TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001008 loop_.PostTask(FROM_HERE,
1009 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
1010 base::Unretained(this)));
1011 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001012}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001013
David Zeuthen8f191b22013-08-06 12:27:50 -07001014void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001015 // If P2P is enabled, but starting it fails ensure we don't do
1016 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001017 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001018 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001019 mock_p2p_manager.fake().SetP2PEnabled(true);
1020 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
1021 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1022 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassani37b67232020-08-13 09:29:48 -07001023 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001024 EXPECT_FALSE(actual_using_p2p_for_downloading());
1025 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001026 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001027}
1028
1029TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001030 loop_.PostTask(
1031 FROM_HERE,
1032 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1033 base::Unretained(this)));
1034 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001035}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001036
David Zeuthen8f191b22013-08-06 12:27:50 -07001037void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001038 // If P2P is enabled, starting it works but housekeeping fails, ensure
1039 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001040 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001041 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001042 mock_p2p_manager.fake().SetP2PEnabled(true);
1043 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1044 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001045 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassani37b67232020-08-13 09:29:48 -07001046 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001047 EXPECT_FALSE(actual_using_p2p_for_downloading());
1048 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001049 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001050}
1051
1052TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001053 loop_.PostTask(FROM_HERE,
1054 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1055 base::Unretained(this)));
1056 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001057}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001058
David Zeuthen8f191b22013-08-06 12:27:50 -07001059void UpdateAttempterTest::P2PEnabledStart() {
1060 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001061 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001062 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001063 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001064 mock_p2p_manager.fake().SetP2PEnabled(true);
1065 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1066 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001067 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassani37b67232020-08-13 09:29:48 -07001068 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001069 EXPECT_TRUE(actual_using_p2p_for_downloading());
1070 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001071 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001072}
1073
1074TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001075 loop_.PostTask(FROM_HERE,
1076 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1077 base::Unretained(this)));
1078 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001079}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001080
David Zeuthen8f191b22013-08-06 12:27:50 -07001081void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1082 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001083 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001084 // For an interactive check, if P2P is enabled and starting it
1085 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001086 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 mock_p2p_manager.fake().SetP2PEnabled(true);
1088 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1089 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001090 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001091 attempter_.Update("",
1092 "",
1093 "",
1094 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001095 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001096 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001097 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001098 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001099 false,
1100 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001101 EXPECT_FALSE(actual_using_p2p_for_downloading());
1102 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001103 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001104}
1105
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001106TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001107 loop_.PostTask(
1108 FROM_HERE,
1109 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1110 base::Unretained(this)));
1111 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001112}
1113
1114// Tests that the scatter_factor_in_seconds value is properly fetched
1115// from the device policy.
1116void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001117 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001118
Igor9fd76b62017-12-11 15:24:18 +01001119 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001121 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122
1123 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001124 .WillRepeatedly(
1125 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126
Igor9fd76b62017-12-11 15:24:18 +01001127 attempter_.policy_provider_.reset(
1128 new policy::PolicyProvider(std::move(device_policy)));
1129
Amin Hassani37b67232020-08-13 09:29:48 -07001130 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001131 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1132
Alex Deymo60ca1a72015-06-18 18:19:15 -07001133 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001134}
1135
1136TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001137 loop_.PostTask(
1138 FROM_HERE,
1139 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1140 base::Unretained(this)));
1141 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001142}
1143
1144void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1145 // Tests that the scatter_factor_in_seconds value is properly fetched
1146 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001147 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001148 FakePrefs fake_prefs;
1149 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001150
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001151 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001152
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001153 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154
Ben Chan9abb7632014-08-07 00:10:53 -07001155 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001156
Igor9fd76b62017-12-11 15:24:18 +01001157 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001158 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001159 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160
1161 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001162 .WillRepeatedly(
1163 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001164
Igor9fd76b62017-12-11 15:24:18 +01001165 attempter_.policy_provider_.reset(
1166 new policy::PolicyProvider(std::move(device_policy)));
1167
Amin Hassani37b67232020-08-13 09:29:48 -07001168 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001169 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1170
1171 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001172 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001173
Ben Chan9abb7632014-08-07 00:10:53 -07001174 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001175 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001176 EXPECT_EQ(initial_value - 1, new_value);
1177
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001178 EXPECT_TRUE(
1179 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001180
1181 // However, if the count is already 0, it's not decremented. Test that.
1182 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001183 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassani37b67232020-08-13 09:29:48 -07001184 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001185 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1186 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001187 EXPECT_EQ(initial_value, new_value);
1188
Alex Deymo60ca1a72015-06-18 18:19:15 -07001189 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001190}
1191
Jay Srinivasan08fce042012-06-07 16:31:01 -07001192TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001193 loop_.PostTask(
1194 FROM_HERE,
1195 base::Bind(
1196 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1197 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001198 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001199}
1200
1201void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1202 // Tests that no scattering logic is enabled if the update check
1203 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001204 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001205 FakePrefs fake_prefs;
1206 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001207
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001208 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001209 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001210
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001211 EXPECT_TRUE(
1212 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001213 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001214
1215 // make sure scatter_factor is non-zero as scattering is disabled
1216 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001217 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001218
Igor9fd76b62017-12-11 15:24:18 +01001219 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001220 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001221 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001222
1223 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001224 .WillRepeatedly(
1225 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001226
Igor9fd76b62017-12-11 15:24:18 +01001227 attempter_.policy_provider_.reset(
1228 new policy::PolicyProvider(std::move(device_policy)));
1229
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001230 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001231 attempter_.Update("",
1232 "",
1233 "",
1234 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001235 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001236 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001237 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001238 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001239 false,
1240 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001241 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1242
1243 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001244 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001245 EXPECT_FALSE(
1246 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001247 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001248 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1249 EXPECT_FALSE(
1250 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001251 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001252
Alex Deymo60ca1a72015-06-18 18:19:15 -07001253 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001254}
1255
Adolfo Victoria497044c2018-07-18 07:51:42 -07001256void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1257 FakePrefs* prefs) {
1258 attempter_.prefs_ = prefs;
1259 fake_system_state_.set_prefs(prefs);
1260
1261 int64_t initial_value = 8;
1262 EXPECT_TRUE(
1263 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1264 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1265 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1266
1267 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1268 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1269 fake_system_state_.set_device_policy(device_policy.get());
1270 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1271 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1272
1273 attempter_.policy_provider_.reset(
1274 new policy::PolicyProvider(std::move(device_policy)));
1275}
1276
1277TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1278 loop_.PostTask(
1279 FROM_HERE,
1280 base::Bind(
1281 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1282 base::Unretained(this)));
1283 loop_.Run();
1284}
1285
1286void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1287 // Tests that staging sets its prefs properly and turns off scattering.
1288 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1289 FakePrefs fake_prefs;
1290 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1291
Amin Hassani37b67232020-08-13 09:29:48 -07001292 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001293 // Check that prefs have the correct values.
1294 int64_t update_count;
1295 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1296 int64_t waiting_time_days;
1297 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1298 &waiting_time_days));
1299 EXPECT_GT(waiting_time_days, 0);
1300 // Update count should have been decremented.
1301 EXPECT_EQ(7, update_count);
1302 // Check that Omaha parameters were updated correctly.
1303 EXPECT_TRUE(
1304 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1305 EXPECT_TRUE(
1306 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1307 EXPECT_EQ(waiting_time_days,
1308 attempter_.omaha_request_params_->waiting_period().InDays());
1309 // Check class variables.
1310 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1311 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1312 // Check that scattering is turned off
1313 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1314 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1315
1316 ScheduleQuitMainLoop();
1317}
1318
1319void UpdateAttempterTest::CheckStagingOff() {
1320 // Check that all prefs were removed.
1321 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1322 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1323 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1324 // Check that the Omaha parameters have the correct value.
1325 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1326 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1327 attempter_.staging_wait_time_);
1328 EXPECT_FALSE(
1329 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1330 EXPECT_FALSE(
1331 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1332 // Check that scattering is turned off too.
1333 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1334}
1335
1336TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1337 loop_.PostTask(FROM_HERE,
1338 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1339 base::Unretained(this)));
1340 loop_.Run();
1341}
1342
1343void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1344 // Tests that staging is turned off when an interactive update is requested.
1345 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1346 FakePrefs fake_prefs;
1347 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1348
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001349 attempter_.Update(
Amin Hassani37b67232020-08-13 09:29:48 -07001350 "", "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001351 CheckStagingOff();
1352
1353 ScheduleQuitMainLoop();
1354}
1355
1356TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1357 loop_.PostTask(FROM_HERE,
1358 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1359 base::Unretained(this)));
1360 loop_.Run();
1361}
1362
1363void UpdateAttempterTest::StagingOffIfOobeStart() {
1364 // Tests that staging is turned off if OOBE hasn't been completed.
1365 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1366 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1367 FakePrefs fake_prefs;
1368 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1369
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001370 attempter_.Update(
Amin Hassani37b67232020-08-13 09:29:48 -07001371 "", "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001372 CheckStagingOff();
1373
1374 ScheduleQuitMainLoop();
1375}
1376
David Zeuthen985b1122013-10-09 12:13:15 -07001377// Checks that we only report daily metrics at most every 24 hours.
1378TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1379 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001380 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001381
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001382 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001383 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001384
1385 Time epoch = Time::FromInternalValue(0);
1386 fake_clock.SetWallclockTime(epoch);
1387
1388 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1389 // we should report.
1390 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1391 // We should not report again if no time has passed.
1392 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1393
1394 // We should not report if only 10 hours has passed.
1395 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1396 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1397
1398 // We should not report if only 24 hours - 1 sec has passed.
1399 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1400 TimeDelta::FromSeconds(1));
1401 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1402
1403 // We should report if 24 hours has passed.
1404 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1405 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1406
1407 // But then we should not report again..
1408 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1409
1410 // .. until another 24 hours has passed
1411 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1412 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1413 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1414 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1415 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1416
1417 // .. and another 24 hours
1418 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1419 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1420 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1421 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1422 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1423
1424 // If the span between time of reporting and present time is
1425 // negative, we report. This is in order to reset the timestamp and
1426 // avoid an edge condition whereby a distant point in the future is
1427 // in the state variable resulting in us never ever reporting again.
1428 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1429 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1430 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1431
1432 // In this case we should not update until the clock reads 71 + 24 = 95.
1433 // Check that.
1434 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1435 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1436 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1437 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1438 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001439}
1440
David Zeuthen3c55abd2013-10-14 12:48:03 -07001441TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001442 FakeClock fake_clock;
1443 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001444 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001445 FakePrefs fake_prefs;
1446 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001447 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001448
1449 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001450 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001451
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001452 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001453
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001454 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001455 EXPECT_EQ(boot_time.ToTimeT(), 42);
1456}
1457
David Pursell02c18642014-11-06 11:26:11 -08001458TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1459 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1460 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1461}
1462
1463TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1464 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001465 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001466 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1467}
1468
1469TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1470 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001471 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001472 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1473}
1474
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001475// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1476// When adding, remove older tests related to |CheckForInstall()|.
1477TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1478 for (const auto status : kNonIdleUpdateStatuses) {
1479 // GIVEN a non-idle status.
1480 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001481
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001482 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1483 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001484}
1485
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001486TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1487 for (const auto status : kNonIdleUpdateStatuses) {
1488 // GIVEN a non-idle status.
1489 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001490
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001491 // THEN |ScheduleUpdates()| should not be called.
1492 cfu_params_.should_schedule_updates_be_called = false;
1493 // THEN result should indicate failure.
1494 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001495
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001496 TestCheckForUpdate();
1497 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001498}
1499
1500TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1501 // GIVEN a official build.
1502
1503 // THEN we except forced app version + forced omaha url to be cleared.
1504
1505 TestCheckForUpdate();
1506}
1507
1508TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001509 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001510 cfu_params_.is_official_build = false;
1511 cfu_params_.are_dev_features_enabled = true;
1512
1513 // THEN the forced app version + forced omaha url changes based on input.
1514 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1515 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1516
1517 TestCheckForUpdate();
1518}
1519
1520TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1521 // GIVEN a scheduled autest omaha url.
1522 cfu_params_.omaha_url = "autest-scheduled";
1523
1524 // THEN forced app version is cleared.
1525 // THEN forced omaha url changes to default constant.
1526 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1527
1528 TestCheckForUpdate();
1529}
1530
1531TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1532 // GIVEN a scheduled autest omaha url.
1533 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001534 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001535 cfu_params_.is_official_build = false;
1536 cfu_params_.are_dev_features_enabled = true;
1537
1538 // THEN forced app version changes based on input.
1539 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1540 // THEN forced omaha url changes to default constant.
1541 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1542
1543 TestCheckForUpdate();
1544}
1545
1546TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1547 // GIVEN a autest omaha url.
1548 cfu_params_.omaha_url = "autest";
1549
1550 // THEN forced app version is cleared.
1551 // THEN forced omaha url changes to default constant.
1552 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1553
1554 TestCheckForUpdate();
1555}
1556
1557TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1558 // GIVEN a autest omha url.
1559 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001560 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001561 cfu_params_.is_official_build = false;
1562 cfu_params_.are_dev_features_enabled = true;
1563
1564 // THEN forced app version changes based on input.
1565 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1566 // THEN forced omaha url changes to default constant.
1567 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1568
1569 TestCheckForUpdate();
1570}
1571
1572TEST_F(UpdateAttempterTest,
1573 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1574 // GIVEN a scheduled autest omaha url.
1575 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001576 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001577 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1578
1579 // THEN forced app version is cleared.
1580 // THEN forced omaha url changes to default constant.
1581 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1582
1583 TestCheckForUpdate();
1584}
1585
1586TEST_F(UpdateAttempterTest,
1587 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1588 // GIVEN a scheduled autest omaha url.
1589 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001590 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001591 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001592 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001593 cfu_params_.is_official_build = false;
1594 cfu_params_.are_dev_features_enabled = true;
1595
1596 // THEN forced app version changes based on input.
1597 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1598 // THEN forced omaha url changes to default constant.
1599 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1600
1601 TestCheckForUpdate();
1602}
1603
1604TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1605 // GIVEN a autest omaha url.
1606 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001607 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001608 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1609
1610 // THEN forced app version is cleared.
1611 // THEN forced omaha url changes to default constant.
1612 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1613
1614 TestCheckForUpdate();
1615}
1616
1617TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1618 // GIVEN a autest omaha url.
1619 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001620 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001621 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001622 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001623 cfu_params_.is_official_build = false;
1624 cfu_params_.are_dev_features_enabled = true;
1625
1626 // THEN forced app version changes based on input.
1627 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1628 // THEN forced omaha url changes to default constant.
1629 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1630
1631 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001632}
1633
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001634TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1635 // GIVEN a official build.
1636 // GIVEN forced callback is not set.
1637 attempter_.set_forced_update_pending_callback(nullptr);
1638
1639 // THEN we except forced app version + forced omaha url to be cleared.
1640 // THEN |ScheduleUpdates()| should not be called.
1641 cfu_params_.should_schedule_updates_be_called = false;
1642
1643 TestCheckForUpdate();
1644}
1645
1646TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001647 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001648 cfu_params_.is_official_build = false;
1649 cfu_params_.are_dev_features_enabled = true;
1650 // GIVEN forced callback is not set.
1651 attempter_.set_forced_update_pending_callback(nullptr);
1652
1653 // THEN the forced app version + forced omaha url changes based on input.
1654 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1655 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1656 // THEN |ScheduleUpdates()| should not be called.
1657 cfu_params_.should_schedule_updates_be_called = false;
1658
1659 TestCheckForUpdate();
1660}
1661
Xiaochu Liu88d90382018-08-29 16:09:11 -07001662TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1663 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1664 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1665 attempter_.CheckForInstall({}, "autest");
1666 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1667
1668 attempter_.CheckForInstall({}, "autest-scheduled");
1669 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1670
1671 attempter_.CheckForInstall({}, "http://omaha.phishing");
1672 EXPECT_EQ("", attempter_.forced_omaha_url());
1673}
1674
Colin Howesac170d92018-11-20 16:29:28 -08001675TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1676 attempter_.CheckForInstall({}, "http://foo.bar");
1677 attempter_.status_ = UpdateStatus::DOWNLOADING;
1678 EXPECT_TRUE(attempter_.is_install_);
1679 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1680 UpdateEngineStatus status;
1681 attempter_.GetStatus(&status);
1682 // Should set status to idle after an install operation.
1683 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1684}
1685
Colin Howes978c1082018-12-03 11:46:12 -08001686TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1687 attempter_.is_install_ = true;
1688 attempter_.Rollback(false);
1689 EXPECT_FALSE(attempter_.is_install_);
1690}
1691
1692TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1693 attempter_.is_install_ = true;
1694 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1695 EXPECT_FALSE(attempter_.is_install_);
1696}
1697
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001698TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001699 attempter_.CalculateUpdateParams(
Amin Hassani37b67232020-08-13 09:29:48 -07001700 "", "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001701 EXPECT_EQ("1234",
1702 fake_system_state_.request_params()->target_version_prefix());
1703
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001704 attempter_.CalculateUpdateParams(
Amin Hassani37b67232020-08-13 09:29:48 -07001705 "", "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001706 EXPECT_TRUE(
1707 fake_system_state_.request_params()->target_version_prefix().empty());
1708}
1709
Amin Hassani37b67232020-08-13 09:29:48 -07001710TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
1711 attempter_.CalculateUpdateParams(
1712 "", "", "", "hint", "", false, false, 4, false, false);
1713 EXPECT_EQ("hint", fake_system_state_.request_params()->lts_tag());
1714
1715 attempter_.CalculateUpdateParams(
1716 "", "", "", "", "", false, 4, false, false, false);
1717 EXPECT_TRUE(fake_system_state_.request_params()->lts_tag().empty());
1718}
1719
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001720TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1721 attempter_.CalculateUpdateParams("",
1722 "",
1723 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001724 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001725 "1234",
1726 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001727 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001728 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001729 false,
1730 false);
1731 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001732 EXPECT_EQ(4,
1733 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001734
1735 attempter_.CalculateUpdateParams("",
1736 "",
1737 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001738 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001739 "1234",
1740 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001741 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001742 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001743 false,
1744 false);
1745 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001746 EXPECT_EQ(4,
1747 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001748}
1749
Aaron Wood23bd3392017-10-06 14:48:25 -07001750TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1751 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1752 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001753 OmahaResponseHandlerAction response_action(&fake_system_state_);
1754 response_action.install_plan_.version = "a.b.c.d";
1755 response_action.install_plan_.system_version = "b.c.d.e";
1756 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001757 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001758 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1759 // completed, with the deferred-update error code.
1760 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001761 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001762 {
1763 UpdateEngineStatus status;
1764 attempter_.GetStatus(&status);
1765 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001766 EXPECT_TRUE(attempter_.install_plan_);
1767 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001768 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001769 status.new_size_bytes);
1770 }
1771 // An "error" event should have been created to tell Omaha that the update is
1772 // being deferred.
1773 EXPECT_TRUE(nullptr != attempter_.error_event_);
1774 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1775 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1776 ErrorCode expected_code = static_cast<ErrorCode>(
1777 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1778 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1779 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1780 // End the processing
1781 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1782 // Validate the state of the attempter.
1783 {
1784 UpdateEngineStatus status;
1785 attempter_.GetStatus(&status);
1786 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001787 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001788 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001789 status.new_size_bytes);
1790 }
1791}
1792
1793TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001794 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001795 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001796 // Verify in-progress update with UPDATE_AVAILABLE is running
1797 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001798 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001799}
1800
Aaron Woodbf5a2522017-10-04 10:58:36 -07001801TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1802 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1803
1804 UpdateCheckParams params = {.updates_enabled = true};
1805 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1806
1807 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1808 attempter_.GetCurrentUpdateAttemptFlags());
1809}
1810
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001811TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1812 UpdateCheckParams params = {.updates_enabled = true,
1813 .rollback_allowed = false};
1814 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1815 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1816}
1817
1818TEST_F(UpdateAttempterTest, RollbackAllowed) {
1819 UpdateCheckParams params = {.updates_enabled = true,
1820 .rollback_allowed = true};
1821 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1822 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1823}
1824
Aaron Wood081c0232017-10-19 17:14:58 -07001825TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1826 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1827
1828 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1829 EXPECT_EQ(UpdateAttemptFlags::kNone,
1830 attempter_.GetCurrentUpdateAttemptFlags());
1831}
1832
1833TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1834 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1835
1836 // This tests that when CheckForUpdate() is called with the non-interactive
1837 // flag set, that it doesn't change the current UpdateAttemptFlags.
1838 attempter_.CheckForUpdate("",
1839 "",
1840 UpdateAttemptFlags::kFlagNonInteractive |
1841 UpdateAttemptFlags::kFlagRestrictDownload);
1842 EXPECT_EQ(UpdateAttemptFlags::kNone,
1843 attempter_.GetCurrentUpdateAttemptFlags());
1844}
1845
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001846void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1847 bool is_policy_loaded,
1848 bool expected_reset) {
1849 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1850 .WillRepeatedly(Return(true));
1851 auto mock_policy_provider =
1852 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1853 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1854 .WillRepeatedly(Return(is_consumer));
1855 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1856 .WillRepeatedly(Return(is_policy_loaded));
1857 const policy::MockDevicePolicy device_policy;
1858 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1859 .WillRepeatedly(ReturnRef(device_policy));
1860 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1861 SetRollbackHappened(false))
1862 .Times(expected_reset ? 1 : 0);
1863 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassani37b67232020-08-13 09:29:48 -07001864 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001865 ScheduleQuitMainLoop();
1866}
1867
1868TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1869 loop_.PostTask(FROM_HERE,
1870 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1871 base::Unretained(this),
1872 /*is_consumer=*/false,
1873 /*is_policy_loaded=*/false,
1874 /*expected_reset=*/false));
1875 loop_.Run();
1876}
1877
1878TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1879 loop_.PostTask(FROM_HERE,
1880 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1881 base::Unretained(this),
1882 /*is_consumer=*/true,
1883 /*is_policy_loaded=*/false,
1884 /*expected_reset=*/true));
1885 loop_.Run();
1886}
1887
1888TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1889 loop_.PostTask(FROM_HERE,
1890 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1891 base::Unretained(this),
1892 /*is_consumer=*/false,
1893 /*is_policy_loaded=*/true,
1894 /*expected_reset=*/true));
1895 loop_.Run();
1896}
1897
Marton Hunyady199152d2018-05-07 19:08:48 +02001898TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001899 attempter_.install_plan_.reset(new InstallPlan);
1900 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001901
1902 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1903 SetRollbackHappened(true))
1904 .Times(1);
1905 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1906}
1907
1908TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001909 attempter_.install_plan_.reset(new InstallPlan);
1910 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001911
1912 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1913 SetRollbackHappened(true))
1914 .Times(0);
1915 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1916}
1917
Marton Hunyadya0302682018-05-16 18:52:13 +02001918TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001919 attempter_.install_plan_.reset(new InstallPlan);
1920 attempter_.install_plan_->is_rollback = true;
1921 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001922
1923 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1924 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1925 .Times(1);
1926 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1927}
1928
1929TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001930 attempter_.install_plan_.reset(new InstallPlan);
1931 attempter_.install_plan_->is_rollback = false;
1932 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001933
1934 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1935 ReportEnterpriseRollbackMetrics(_, _))
1936 .Times(0);
1937 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1938}
1939
1940TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001941 attempter_.install_plan_.reset(new InstallPlan);
1942 attempter_.install_plan_->is_rollback = true;
1943 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001944
1945 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1946 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1947 .Times(1);
1948 MockAction action;
1949 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1950 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1951}
1952
1953TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001954 attempter_.install_plan_.reset(new InstallPlan);
1955 attempter_.install_plan_->is_rollback = false;
1956 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001957
1958 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1959 ReportEnterpriseRollbackMetrics(_, _))
1960 .Times(0);
1961 MockAction action;
1962 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1963 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1964}
1965
May Lippert60aa3ca2018-08-15 16:55:29 -07001966TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1967 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1968 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1969 .Times(0);
1970 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1971}
1972
1973TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1974 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1975 fake_system_state_.set_device_policy(device_policy.get());
1976 // Make device policy return that this is not enterprise enrolled
1977 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1978
1979 // Ensure that the metric is not recorded.
1980 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1981 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1982 .Times(0);
1983 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1984}
1985
1986TEST_F(UpdateAttempterTest,
1987 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1988 constexpr int kDaysToUpdate = 15;
1989 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1990 fake_system_state_.set_device_policy(device_policy.get());
1991 // Make device policy return that this is enterprise enrolled
1992 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1993 // Pretend that there's a time restriction policy in place
1994 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1995 .WillOnce(Return(true));
1996
1997 FakePrefs fake_prefs;
1998 Time update_first_seen_at = Time::Now();
1999 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2000 update_first_seen_at.ToInternalValue());
2001
2002 FakeClock fake_clock;
2003 Time update_finished_at =
2004 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2005 fake_clock.SetWallclockTime(update_finished_at);
2006
2007 fake_system_state_.set_clock(&fake_clock);
2008 fake_system_state_.set_prefs(&fake_prefs);
2009
2010 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2011 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
2012 .Times(1);
2013 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2014}
2015
2016TEST_F(UpdateAttempterTest,
2017 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
2018 constexpr int kDaysToUpdate = 15;
2019 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2020 fake_system_state_.set_device_policy(device_policy.get());
2021 // Make device policy return that this is enterprise enrolled
2022 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
2023 // Pretend that there's no time restriction policy in place
2024 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
2025 .WillOnce(Return(false));
2026
2027 FakePrefs fake_prefs;
2028 Time update_first_seen_at = Time::Now();
2029 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2030 update_first_seen_at.ToInternalValue());
2031
2032 FakeClock fake_clock;
2033 Time update_finished_at =
2034 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2035 fake_clock.SetWallclockTime(update_finished_at);
2036
2037 fake_system_state_.set_clock(&fake_clock);
2038 fake_system_state_.set_prefs(&fake_prefs);
2039
2040 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2041 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2042 .Times(1);
2043 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2044}
2045
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002046TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2047 // GIVEN an update finished.
2048
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002049 // THEN update_engine should call update completion.
2050 pd_params_.should_update_completed_be_called = true;
2051 // THEN need reboot since update applied.
2052 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2053 // THEN install indication should be false.
2054
2055 TestProcessingDone();
2056}
2057
2058TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2059 // GIVEN an update finished.
2060 // GIVEN DLC |AppParams| list.
2061 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2062 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2063 {dlc_2, {.name = dlc_2}}};
2064
2065 // THEN update_engine should call update completion.
2066 pd_params_.should_update_completed_be_called = true;
2067 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002068 // THEN need reboot since update applied.
2069 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2070 // THEN install indication should be false.
2071
2072 TestProcessingDone();
2073}
2074
2075TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2076 // GIVEN an install finished.
2077 pd_params_.is_install = true;
2078
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002079 // THEN update_engine should call install completion.
2080 pd_params_.should_install_completed_be_called = true;
2081 // THEN go idle.
2082 // THEN install indication should be false.
2083
2084 TestProcessingDone();
2085}
2086
2087TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2088 // GIVEN an install finished.
2089 pd_params_.is_install = true;
2090 // GIVEN DLC |AppParams| list.
2091 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2092 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2093 {dlc_2, {.name = dlc_2}}};
2094
2095 // THEN update_engine should call install completion.
2096 pd_params_.should_install_completed_be_called = true;
2097 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002098 // THEN go idle.
2099 // THEN install indication should be false.
2100
2101 TestProcessingDone();
2102}
2103
2104TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2105 // GIVEN an install finished.
2106 pd_params_.is_install = true;
2107 // GIVEN a reporting error occurred.
2108 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2109
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002110 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002111 // THEN go idle.
2112 // THEN install indication should be false.
2113
2114 TestProcessingDone();
2115}
2116
2117TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2118 // GIVEN an update finished.
2119 // GIVEN an action error occured.
2120 pd_params_.code = ErrorCode::kNoUpdate;
2121
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002122 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002123 // THEN go idle.
2124 // THEN install indication should be false.
2125
2126 TestProcessingDone();
2127}
2128
2129TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2130 // GIVEN an install finished.
2131 pd_params_.is_install = true;
2132 // GIVEN an action error occured.
2133 pd_params_.code = ErrorCode::kNoUpdate;
2134
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002135 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002136 // THEN go idle.
2137 // THEN install indication should be false.
2138
2139 TestProcessingDone();
2140}
2141
2142TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2143 // GIVEN an update finished.
2144 // GIVEN an action error occured.
2145 pd_params_.code = ErrorCode::kError;
2146 // GIVEN an event error is set.
2147 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2148 OmahaEvent::kResultError,
2149 ErrorCode::kError));
2150
2151 // THEN indicate a error event.
2152 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2153 // THEN install indication should be false.
2154
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002155 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002156 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2157 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2158 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2159 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2160 pd_params_.should_schedule_updates_be_called = false;
2161
2162 TestProcessingDone();
2163}
2164
2165TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2166 // GIVEN an install finished.
2167 pd_params_.is_install = true;
2168 // GIVEN an action error occured.
2169 pd_params_.code = ErrorCode::kError;
2170 // GIVEN an event error is set.
2171 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2172 OmahaEvent::kResultError,
2173 ErrorCode::kError));
2174
2175 // THEN indicate a error event.
2176 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2177 // THEN install indication should be false.
2178
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002179 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002180 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2181 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2182 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2183 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2184 pd_params_.should_schedule_updates_be_called = false;
2185
2186 TestProcessingDone();
2187}
2188
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002189void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2190 // Tests that checks if |device_quick_fix_build_token| arrives when
2191 // policy is set and the device is enterprise enrolled based on |set_token|.
2192 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002193 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2194 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002195 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002196
2197 if (set_token)
2198 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2199 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2200 else
2201 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2202 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002203 attempter_.policy_provider_.reset(
2204 new policy::PolicyProvider(std::move(device_policy)));
Amin Hassani37b67232020-08-13 09:29:48 -07002205 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Askar Aitzhan570ca872019-04-24 11:16:12 +02002206
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002207 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002208 ScheduleQuitMainLoop();
2209}
2210
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002211TEST_F(UpdateAttempterTest,
2212 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002213 loop_.PostTask(FROM_HERE,
2214 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002215 base::Unretained(this),
2216 /*set_token=*/true));
2217 loop_.Run();
2218}
2219
2220TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2221 loop_.PostTask(FROM_HERE,
2222 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2223 base::Unretained(this),
2224 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002225 loop_.Run();
2226}
2227
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002228TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2229 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2230 .Times(1);
2231 EXPECT_TRUE(attempter_.ScheduleUpdates());
2232 // Now there is an update scheduled which means that all subsequent
2233 // |ScheduleUpdates()| should fail.
2234 EXPECT_FALSE(attempter_.ScheduleUpdates());
2235 EXPECT_FALSE(attempter_.ScheduleUpdates());
2236 EXPECT_FALSE(attempter_.ScheduleUpdates());
2237}
2238
2239// Critical tests to always make sure that an update is scheduled. The following
2240// unittest(s) try and cover the correctness in synergy between
2241// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2242// actions that happen in the flow when |UpdateAttempter| get callbacked on
2243// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2244void UpdateAttempterTest::TestOnUpdateScheduled() {
2245 // Setup
2246 attempter_.SetWaitingForScheduledCheck(true);
2247 attempter_.DisableUpdate();
2248 attempter_.DisableScheduleUpdates();
2249
2250 // Invocation
2251 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2252
2253 // Verify
2254 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2255 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2256 attempter_.WasScheduleUpdatesCalled());
2257 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2258}
2259
2260TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2261 // GIVEN failed status.
2262
2263 // THEN update should be scheduled.
2264 ous_params_.should_schedule_updates_be_called = true;
2265
2266 TestOnUpdateScheduled();
2267}
2268
2269TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2270 // GIVEN ask me again later status.
2271 ous_params_.status = EvalStatus::kAskMeAgainLater;
2272
2273 // THEN update should be scheduled.
2274 ous_params_.should_schedule_updates_be_called = true;
2275
2276 TestOnUpdateScheduled();
2277}
2278
2279TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2280 // GIVEN continue status.
2281 ous_params_.status = EvalStatus::kContinue;
2282
2283 // THEN update should be scheduled.
2284 ous_params_.should_schedule_updates_be_called = true;
2285
2286 TestOnUpdateScheduled();
2287}
2288
2289TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2290 // GIVEN updates disabled.
2291 ous_params_.params = {.updates_enabled = false};
2292 // GIVEN succeeded status.
2293 ous_params_.status = EvalStatus::kSucceeded;
2294
2295 // THEN update should not be scheduled.
2296
2297 TestOnUpdateScheduled();
2298}
2299
2300TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2301 // GIVEN updates enabled.
2302 ous_params_.params = {.updates_enabled = true};
2303 // GIVEN succeeded status.
2304 ous_params_.status = EvalStatus::kSucceeded;
2305
2306 // THEN update should be called indicating status change.
2307 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2308 ous_params_.should_update_be_called = true;
2309
2310 TestOnUpdateScheduled();
2311}
2312
Amin Hassani9be122e2019-08-29 09:20:12 -07002313TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2314 UpdateEngineStatus status;
2315 attempter_.GetStatus(&status);
2316 EXPECT_FALSE(status.is_enterprise_rollback);
2317}
2318
2319TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2320 attempter_.install_plan_.reset(new InstallPlan);
2321 attempter_.install_plan_->is_rollback = false;
2322
2323 UpdateEngineStatus status;
2324 attempter_.GetStatus(&status);
2325 EXPECT_FALSE(status.is_enterprise_rollback);
2326}
2327
2328TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2329 attempter_.install_plan_.reset(new InstallPlan);
2330 attempter_.install_plan_->is_rollback = true;
2331
2332 UpdateEngineStatus status;
2333 attempter_.GetStatus(&status);
2334 EXPECT_TRUE(status.is_enterprise_rollback);
2335}
2336
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002337TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2338 UpdateEngineStatus status;
2339 attempter_.GetStatus(&status);
2340 EXPECT_FALSE(status.will_powerwash_after_reboot);
2341}
2342
2343TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2344 attempter_.install_plan_.reset(new InstallPlan);
2345 attempter_.install_plan_->powerwash_required = true;
2346
2347 UpdateEngineStatus status;
2348 attempter_.GetStatus(&status);
2349 EXPECT_TRUE(status.will_powerwash_after_reboot);
2350}
2351
2352TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2353 attempter_.install_plan_.reset(new InstallPlan);
2354 attempter_.install_plan_->is_rollback = true;
2355
2356 UpdateEngineStatus status;
2357 attempter_.GetStatus(&status);
2358 EXPECT_TRUE(status.will_powerwash_after_reboot);
2359}
2360
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002361TEST_F(UpdateAttempterTest, FutureEolTest) {
2362 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002363 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002364 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2365 .WillOnce(
2366 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2367
2368 UpdateEngineStatus status;
2369 attempter_.GetStatus(&status);
2370 EXPECT_EQ(eol_date, status.eol_date);
2371}
2372
2373TEST_F(UpdateAttempterTest, PastEolTest) {
2374 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002375 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002376 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2377 .WillOnce(
2378 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2379
2380 UpdateEngineStatus status;
2381 attempter_.GetStatus(&status);
2382 EXPECT_EQ(eol_date, status.eol_date);
2383}
2384
2385TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002386 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002387 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2388 .WillOnce(Return(false));
2389
2390 UpdateEngineStatus status;
2391 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002392 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2393}
2394
2395TEST_F(UpdateAttempterTest, MissingEolTest) {
2396 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2397
2398 UpdateEngineStatus status;
2399 attempter_.GetStatus(&status);
2400 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002401}
2402
Andrewe045aef2020-01-08 16:29:22 -08002403TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002404 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002405 FakePrefs fake_prefs;
2406 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002407 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002408 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002409 attempter_.CalculateDlcParams();
2410
2411 OmahaRequestParams* params = fake_system_state_.request_params();
2412 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2413 OmahaRequestParams::AppParams dlc_app_params =
2414 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2415 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2416 EXPECT_EQ(false, dlc_app_params.send_ping);
2417 // When the DLC gets installed, a ping is not sent, therefore we don't store
2418 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002419 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002420 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002421 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2422 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002423 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002424 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002425}
2426
2427TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002428 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002429 FakePrefs fake_prefs;
2430 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002431 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002432 .WillOnce(
2433 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2434
2435 attempter_.is_install_ = false;
2436 attempter_.CalculateDlcParams();
2437
2438 OmahaRequestParams* params = fake_system_state_.request_params();
2439 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2440 OmahaRequestParams::AppParams dlc_app_params =
2441 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2442 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2443
2444 EXPECT_EQ(true, dlc_app_params.send_ping);
2445 EXPECT_EQ(0, dlc_app_params.ping_active);
2446 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2447 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2448}
2449
2450TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002451 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002452 MemoryPrefs prefs;
2453 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002454 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002455 .WillOnce(
2456 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2457
2458 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002459 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002460 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002461 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002462 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002463 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002464 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002465 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2466 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2467 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002468 attempter_.is_install_ = false;
2469 attempter_.CalculateDlcParams();
2470
2471 OmahaRequestParams* params = fake_system_state_.request_params();
2472 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2473 OmahaRequestParams::AppParams dlc_app_params =
2474 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2475 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2476
2477 EXPECT_EQ(true, dlc_app_params.send_ping);
2478 EXPECT_EQ(0, dlc_app_params.ping_active);
2479 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2480 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2481}
2482
2483TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002484 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002485 MemoryPrefs fake_prefs;
2486 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002487 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002488 .WillOnce(
2489 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2490
2491 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002492 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002493 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002494 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002495 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002496 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002497 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002498
2499 fake_system_state_.prefs()->SetInt64(active_key, 1);
2500 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2501 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002502 attempter_.is_install_ = false;
2503 attempter_.CalculateDlcParams();
2504
2505 OmahaRequestParams* params = fake_system_state_.request_params();
2506 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2507 OmahaRequestParams::AppParams dlc_app_params =
2508 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2509 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2510
2511 EXPECT_EQ(true, dlc_app_params.send_ping);
2512 EXPECT_EQ(1, dlc_app_params.ping_active);
2513 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2514 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2515}
Andrewa8d7df32020-03-15 20:10:01 -07002516
2517TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002518 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002519 FakePrefs fake_prefs;
2520 fake_system_state_.set_prefs(&fake_prefs);
2521 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002522 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002523 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002524 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002525 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002526 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002527 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2528 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2529 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2530 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2531 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2532 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002533
Andrew065d78d2020-04-07 15:43:07 -07002534 attempter_.dlc_ids_ = {dlc_id};
2535 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002536 attempter_.CalculateDlcParams();
2537
Andrew065d78d2020-04-07 15:43:07 -07002538 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2539 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2540 // Active key is set on install.
2541 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2542 int64_t temp_int;
2543 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2544 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002545}
2546
2547TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002548 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002549 FakePrefs fake_prefs;
2550 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002551 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002552 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002553 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002554 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002555 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2556 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002557 EXPECT_EQ(temp_int, kPingActiveValue);
2558}
2559
2560TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002561 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002562 MemoryPrefs fake_prefs;
2563 fake_system_state_.set_prefs(&fake_prefs);
2564 auto sub_keys = {
2565 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2566 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002567 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002568 fake_system_state_.prefs()->SetInt64(key, 1);
2569 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2570 }
Andrewa8d7df32020-03-15 20:10:01 -07002571 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002572 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002573 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002574 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2575 }
Andrewa8d7df32020-03-15 20:10:01 -07002576}
2577
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002578TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2579 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2580 attempter_.omaha_request_params_->set_dlc_apps_params(
2581 {{dlc_1, {.name = dlc_1, .updated = false}},
2582 {dlc_2, {.name = dlc_2}},
2583 {dlc_3, {.name = dlc_3, .updated = false}}});
2584 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2585}
2586
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002587} // namespace chromeos_update_engine