blob: 7466aba55a296d04a75c9683fcde56bb2321ab31 [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));
Sen Jiange6e4bb92016-04-05 14:59:12 -0700668 FilesystemVerifierAction filesystem_verifier_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800669 EXPECT_EQ(
670 ErrorCode::kFilesystemVerifierError,
671 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300672 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700673 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800674 EXPECT_EQ(
675 ErrorCode::kPostinstallRunnerError,
676 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800677 MockAction action_mock;
678 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700679 EXPECT_EQ(ErrorCode::kError,
680 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700681}
682
Darin Petkov36275772010-10-01 11:40:57 -0700683TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700684 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800685 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700686 .WillOnce(Return(false));
687 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700688 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800689 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800690 .WillOnce(
691 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
692 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700693 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700694 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800695 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800696 .WillOnce(
697 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
698 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700699 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700700 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800701 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700702 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700703 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700704}
705
706TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800707 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700708 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700709 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
710 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800711 .WillOnce(
712 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
713 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800714 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700715 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800716 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700717 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800718 EXPECT_CALL(*prefs_,
719 SetInt64(kPrefsDeltaUpdateFailures,
720 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
721 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700722 attempter_.MarkDeltaUpdateFailure();
723}
724
Darin Petkov1b003102010-11-30 10:18:36 -0800725TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
726 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
727 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700728 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800729 .Times(0);
730 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700731 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800732 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700733 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700734 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700735 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800736 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700737 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800738}
739
740TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
741 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700742 EnqueueAction(Pointee(Property(
743 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700744 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700745 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700746 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800747 attempter_.error_event_.reset(new OmahaEvent(
748 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800749 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700750 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800751}
752
Darin Petkove6ef2f82011-03-07 17:31:11 -0800753namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700754// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200755vector<string> GetUpdateActionTypes() {
756 return {OmahaRequestAction::StaticType(),
757 OmahaResponseHandlerAction::StaticType(),
758 UpdateBootFlagsAction::StaticType(),
759 OmahaRequestAction::StaticType(),
760 DownloadAction::StaticType(),
761 OmahaRequestAction::StaticType(),
762 FilesystemVerifierAction::StaticType(),
763 PostinstallRunnerAction::StaticType(),
764 OmahaRequestAction::StaticType()};
765}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700766
767// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200768vector<string> GetRollbackActionTypes() {
769 return {InstallPlanAction::StaticType(),
770 PostinstallRunnerAction::StaticType()};
771}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700772
Adolfo Victoria497044c2018-07-18 07:51:42 -0700773const StagingSchedule kValidStagingSchedule = {
774 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
775
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700776} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800777
778void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700779 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700780
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700781 // Expect that the device policy is loaded by the |UpdateAttempter| at some
782 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100783 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700784 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800785 .Times(testing::AtLeast(1))
786 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100787 attempter_.policy_provider_.reset(
788 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700789
790 {
791 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200792 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700793 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700794 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200795 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700796 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700797 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700798 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700799
Amin Hassani37b67232020-08-13 09:29:48 -0700800 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700801 loop_.PostTask(FROM_HERE,
802 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
803 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800804}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700805
Darin Petkove6ef2f82011-03-07 17:31:11 -0800806void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700807 EXPECT_EQ(0, attempter_.http_response_code());
808 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700809 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700810 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800811}
812
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800813void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
814 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700815 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100816 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700817 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100818 fake_system_state_.set_device_policy(device_policy.get());
819 if (enterprise_rollback) {
820 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800821 EXPECT_CALL(*device_policy, GetOwner(_))
822 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100823 } else {
824 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800825 EXPECT_CALL(*device_policy, GetOwner(_))
826 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
827 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100828 }
829
830 attempter_.policy_provider_.reset(
831 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700832
Alex Deymo763e7db2015-08-27 21:08:08 -0700833 if (valid_slot) {
834 BootControlInterface::Slot rollback_slot = 1;
835 LOG(INFO) << "Test Mark Bootable: "
836 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700837 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
838 true);
Don Garrett6646b442013-11-13 15:29:11 -0800839 }
840
Chris Sosa28e479c2013-07-12 11:39:53 -0700841 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700842
Chris Sosad38b1132014-03-25 10:43:59 -0700843 // We only allow rollback on devices that are not enterprise enrolled and
844 // which have a valid slot to rollback to.
845 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800846 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700847 }
848
Chris Sosa28e479c2013-07-12 11:39:53 -0700849 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700850 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200851 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700852 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200853 EnqueueAction(Pointee(
854 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700855 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700856 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700857
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700858 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700859 loop_.PostTask(FROM_HERE,
860 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
861 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700862 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700863 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700864 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700865 }
866}
867
868void UpdateAttempterTest::RollbackTestVerify() {
869 // Verifies the actions that were enqueued.
870 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700871 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700872 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
873 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700874 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700875}
876
Darin Petkove6ef2f82011-03-07 17:31:11 -0800877TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700878 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700879 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700880}
881
Chris Sosa76a29ae2013-07-11 17:59:24 -0700882TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700883 loop_.PostTask(FROM_HERE,
884 base::Bind(&UpdateAttempterTest::RollbackTestStart,
885 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800886 false,
887 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700888 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700889}
890
Don Garrett6646b442013-11-13 15:29:11 -0800891TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700892 loop_.PostTask(FROM_HERE,
893 base::Bind(&UpdateAttempterTest::RollbackTestStart,
894 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800895 false,
896 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700897 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800898}
899
Chris Sosa76a29ae2013-07-11 17:59:24 -0700900TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700901 loop_.PostTask(FROM_HERE,
902 base::Bind(&UpdateAttempterTest::RollbackTestStart,
903 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800904 true,
905 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700906 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700907}
908
Thieu Le116fda32011-04-19 11:01:54 -0700909void UpdateAttempterTest::PingOmahaTestStart() {
910 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700911 EnqueueAction(Pointee(Property(
912 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700913 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700914 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700915 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700916}
917
918TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700919 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700920 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700921 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700922 // testing, which is more permissive than we want to handle here.
923 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700924 loop_.PostTask(FROM_HERE,
925 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
926 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700927 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700928 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700929 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700930}
931
Darin Petkov18c7bce2011-06-16 14:07:00 -0700932TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800933 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700934 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700935 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700936 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700937 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
938 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700939 EXPECT_EQ(
940 static_cast<ErrorCode>(static_cast<int>(kCode) |
941 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
942 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700943}
944
945TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700946 attempter_.install_plan_.reset(new InstallPlan);
947 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800948 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700949 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700950 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700951 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700952 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
953 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700954 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800955 static_cast<ErrorCode>(static_cast<int>(kCode) |
956 static_cast<int>(ErrorCode::kResumedFlag) |
957 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700958 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700959}
960
David Zeuthen8f191b22013-08-06 12:27:50 -0700961TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
962 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700963 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700964 mock_p2p_manager.fake().SetP2PEnabled(false);
965 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
966 attempter_.UpdateEngineStarted();
967}
968
969TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
970 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700971 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700972 mock_p2p_manager.fake().SetP2PEnabled(true);
973 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
974 attempter_.UpdateEngineStarted();
975}
976
977TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
978 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700979 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700980 mock_p2p_manager.fake().SetP2PEnabled(true);
981 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700982 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700983 attempter_.UpdateEngineStarted();
984}
985
986TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700987 loop_.PostTask(FROM_HERE,
988 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
989 base::Unretained(this)));
990 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700991}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700992
David Zeuthen8f191b22013-08-06 12:27:50 -0700993void UpdateAttempterTest::P2PNotEnabledStart() {
994 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700995 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700996 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700997 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700998 mock_p2p_manager.fake().SetP2PEnabled(false);
999 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassani37b67232020-08-13 09:29:48 -07001000 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -07001001 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001002 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001003 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001004}
1005
1006TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001007 loop_.PostTask(FROM_HERE,
1008 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
1009 base::Unretained(this)));
1010 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001011}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001012
David Zeuthen8f191b22013-08-06 12:27:50 -07001013void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001014 // If P2P is enabled, but starting it fails ensure we don't do
1015 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001017 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001018 mock_p2p_manager.fake().SetP2PEnabled(true);
1019 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
1020 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1021 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassani37b67232020-08-13 09:29:48 -07001022 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001023 EXPECT_FALSE(actual_using_p2p_for_downloading());
1024 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001025 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001026}
1027
1028TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001029 loop_.PostTask(
1030 FROM_HERE,
1031 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1032 base::Unretained(this)));
1033 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001034}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001035
David Zeuthen8f191b22013-08-06 12:27:50 -07001036void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001037 // If P2P is enabled, starting it works but housekeeping fails, ensure
1038 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001039 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001040 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001041 mock_p2p_manager.fake().SetP2PEnabled(true);
1042 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1043 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001044 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassani37b67232020-08-13 09:29:48 -07001045 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001046 EXPECT_FALSE(actual_using_p2p_for_downloading());
1047 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001048 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001049}
1050
1051TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001052 loop_.PostTask(FROM_HERE,
1053 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1054 base::Unretained(this)));
1055 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001056}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001057
David Zeuthen8f191b22013-08-06 12:27:50 -07001058void UpdateAttempterTest::P2PEnabledStart() {
1059 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001060 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001061 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001062 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001063 mock_p2p_manager.fake().SetP2PEnabled(true);
1064 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1065 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001066 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassani37b67232020-08-13 09:29:48 -07001067 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001068 EXPECT_TRUE(actual_using_p2p_for_downloading());
1069 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001070 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001071}
1072
1073TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001074 loop_.PostTask(FROM_HERE,
1075 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1076 base::Unretained(this)));
1077 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001078}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001079
David Zeuthen8f191b22013-08-06 12:27:50 -07001080void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1081 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001082 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001083 // For an interactive check, if P2P is enabled and starting it
1084 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001085 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001086 mock_p2p_manager.fake().SetP2PEnabled(true);
1087 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1088 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001089 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001090 attempter_.Update("",
1091 "",
1092 "",
1093 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001094 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001095 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001096 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001097 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001098 false,
1099 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001100 EXPECT_FALSE(actual_using_p2p_for_downloading());
1101 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001102 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001103}
1104
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001105TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001106 loop_.PostTask(
1107 FROM_HERE,
1108 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1109 base::Unretained(this)));
1110 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001111}
1112
1113// Tests that the scatter_factor_in_seconds value is properly fetched
1114// from the device policy.
1115void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001116 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001117
Igor9fd76b62017-12-11 15:24:18 +01001118 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001119 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001120 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001121
1122 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001123 .WillRepeatedly(
1124 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001125
Igor9fd76b62017-12-11 15:24:18 +01001126 attempter_.policy_provider_.reset(
1127 new policy::PolicyProvider(std::move(device_policy)));
1128
Amin Hassani37b67232020-08-13 09:29:48 -07001129 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1131
Alex Deymo60ca1a72015-06-18 18:19:15 -07001132 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001133}
1134
1135TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001136 loop_.PostTask(
1137 FROM_HERE,
1138 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1139 base::Unretained(this)));
1140 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001141}
1142
1143void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1144 // Tests that the scatter_factor_in_seconds value is properly fetched
1145 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001146 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001147 FakePrefs fake_prefs;
1148 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001149
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001150 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001151
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001152 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153
Ben Chan9abb7632014-08-07 00:10:53 -07001154 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155
Igor9fd76b62017-12-11 15:24:18 +01001156 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001157 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001158 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001159
1160 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001161 .WillRepeatedly(
1162 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001163
Igor9fd76b62017-12-11 15:24:18 +01001164 attempter_.policy_provider_.reset(
1165 new policy::PolicyProvider(std::move(device_policy)));
1166
Amin Hassani37b67232020-08-13 09:29:48 -07001167 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001168 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1169
1170 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001171 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001172
Ben Chan9abb7632014-08-07 00:10:53 -07001173 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001174 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001175 EXPECT_EQ(initial_value - 1, new_value);
1176
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001177 EXPECT_TRUE(
1178 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001179
1180 // However, if the count is already 0, it's not decremented. Test that.
1181 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001182 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassani37b67232020-08-13 09:29:48 -07001183 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001184 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1185 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001186 EXPECT_EQ(initial_value, new_value);
1187
Alex Deymo60ca1a72015-06-18 18:19:15 -07001188 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001189}
1190
Jay Srinivasan08fce042012-06-07 16:31:01 -07001191TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001192 loop_.PostTask(
1193 FROM_HERE,
1194 base::Bind(
1195 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1196 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001197 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001198}
1199
1200void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1201 // Tests that no scattering logic is enabled if the update check
1202 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001203 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001204 FakePrefs fake_prefs;
1205 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001206
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001207 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001208 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001209
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001210 EXPECT_TRUE(
1211 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001212 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001213
1214 // make sure scatter_factor is non-zero as scattering is disabled
1215 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001216 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001217
Igor9fd76b62017-12-11 15:24:18 +01001218 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001219 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001220 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001221
1222 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001223 .WillRepeatedly(
1224 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001225
Igor9fd76b62017-12-11 15:24:18 +01001226 attempter_.policy_provider_.reset(
1227 new policy::PolicyProvider(std::move(device_policy)));
1228
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001229 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001230 attempter_.Update("",
1231 "",
1232 "",
1233 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001234 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001235 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001236 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001237 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001238 false,
1239 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001240 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1241
1242 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001243 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001244 EXPECT_FALSE(
1245 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001246 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001247 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1248 EXPECT_FALSE(
1249 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001250 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001251
Alex Deymo60ca1a72015-06-18 18:19:15 -07001252 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001253}
1254
Adolfo Victoria497044c2018-07-18 07:51:42 -07001255void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1256 FakePrefs* prefs) {
1257 attempter_.prefs_ = prefs;
1258 fake_system_state_.set_prefs(prefs);
1259
1260 int64_t initial_value = 8;
1261 EXPECT_TRUE(
1262 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1263 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1264 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1265
1266 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1267 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1268 fake_system_state_.set_device_policy(device_policy.get());
1269 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1270 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1271
1272 attempter_.policy_provider_.reset(
1273 new policy::PolicyProvider(std::move(device_policy)));
1274}
1275
1276TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1277 loop_.PostTask(
1278 FROM_HERE,
1279 base::Bind(
1280 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1281 base::Unretained(this)));
1282 loop_.Run();
1283}
1284
1285void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1286 // Tests that staging sets its prefs properly and turns off scattering.
1287 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1288 FakePrefs fake_prefs;
1289 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1290
Amin Hassani37b67232020-08-13 09:29:48 -07001291 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001292 // Check that prefs have the correct values.
1293 int64_t update_count;
1294 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1295 int64_t waiting_time_days;
1296 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1297 &waiting_time_days));
1298 EXPECT_GT(waiting_time_days, 0);
1299 // Update count should have been decremented.
1300 EXPECT_EQ(7, update_count);
1301 // Check that Omaha parameters were updated correctly.
1302 EXPECT_TRUE(
1303 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1304 EXPECT_TRUE(
1305 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1306 EXPECT_EQ(waiting_time_days,
1307 attempter_.omaha_request_params_->waiting_period().InDays());
1308 // Check class variables.
1309 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1310 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1311 // Check that scattering is turned off
1312 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1313 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1314
1315 ScheduleQuitMainLoop();
1316}
1317
1318void UpdateAttempterTest::CheckStagingOff() {
1319 // Check that all prefs were removed.
1320 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1321 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1322 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1323 // Check that the Omaha parameters have the correct value.
1324 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1325 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1326 attempter_.staging_wait_time_);
1327 EXPECT_FALSE(
1328 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1329 EXPECT_FALSE(
1330 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1331 // Check that scattering is turned off too.
1332 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1333}
1334
1335TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1336 loop_.PostTask(FROM_HERE,
1337 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1338 base::Unretained(this)));
1339 loop_.Run();
1340}
1341
1342void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1343 // Tests that staging is turned off when an interactive update is requested.
1344 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1345 FakePrefs fake_prefs;
1346 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1347
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001348 attempter_.Update(
Amin Hassani37b67232020-08-13 09:29:48 -07001349 "", "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001350 CheckStagingOff();
1351
1352 ScheduleQuitMainLoop();
1353}
1354
1355TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1356 loop_.PostTask(FROM_HERE,
1357 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1358 base::Unretained(this)));
1359 loop_.Run();
1360}
1361
1362void UpdateAttempterTest::StagingOffIfOobeStart() {
1363 // Tests that staging is turned off if OOBE hasn't been completed.
1364 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1365 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1366 FakePrefs fake_prefs;
1367 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1368
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001369 attempter_.Update(
Amin Hassani37b67232020-08-13 09:29:48 -07001370 "", "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001371 CheckStagingOff();
1372
1373 ScheduleQuitMainLoop();
1374}
1375
David Zeuthen985b1122013-10-09 12:13:15 -07001376// Checks that we only report daily metrics at most every 24 hours.
1377TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1378 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001379 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001380
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001381 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001382 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001383
1384 Time epoch = Time::FromInternalValue(0);
1385 fake_clock.SetWallclockTime(epoch);
1386
1387 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1388 // we should report.
1389 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1390 // We should not report again if no time has passed.
1391 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1392
1393 // We should not report if only 10 hours has passed.
1394 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1395 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1396
1397 // We should not report if only 24 hours - 1 sec has passed.
1398 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1399 TimeDelta::FromSeconds(1));
1400 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1401
1402 // We should report if 24 hours has passed.
1403 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1404 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1405
1406 // But then we should not report again..
1407 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1408
1409 // .. until another 24 hours has passed
1410 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1411 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1412 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1413 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1414 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1415
1416 // .. and another 24 hours
1417 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1418 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1419 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1420 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1421 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1422
1423 // If the span between time of reporting and present time is
1424 // negative, we report. This is in order to reset the timestamp and
1425 // avoid an edge condition whereby a distant point in the future is
1426 // in the state variable resulting in us never ever reporting again.
1427 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1428 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1429 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1430
1431 // In this case we should not update until the clock reads 71 + 24 = 95.
1432 // Check that.
1433 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1434 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1435 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1436 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1437 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001438}
1439
David Zeuthen3c55abd2013-10-14 12:48:03 -07001440TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001441 FakeClock fake_clock;
1442 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001443 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001444 FakePrefs fake_prefs;
1445 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001446 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001447
1448 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001449 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001450
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001451 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001452
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001453 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001454 EXPECT_EQ(boot_time.ToTimeT(), 42);
1455}
1456
David Pursell02c18642014-11-06 11:26:11 -08001457TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1458 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1459 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1460}
1461
1462TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1463 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001464 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001465 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1466}
1467
1468TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1469 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001470 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001471 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1472}
1473
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001474// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1475// When adding, remove older tests related to |CheckForInstall()|.
1476TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1477 for (const auto status : kNonIdleUpdateStatuses) {
1478 // GIVEN a non-idle status.
1479 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001480
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001481 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1482 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001483}
1484
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001485TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1486 for (const auto status : kNonIdleUpdateStatuses) {
1487 // GIVEN a non-idle status.
1488 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001489
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001490 // THEN |ScheduleUpdates()| should not be called.
1491 cfu_params_.should_schedule_updates_be_called = false;
1492 // THEN result should indicate failure.
1493 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001494
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001495 TestCheckForUpdate();
1496 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001497}
1498
1499TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1500 // GIVEN a official build.
1501
1502 // THEN we except forced app version + forced omaha url to be cleared.
1503
1504 TestCheckForUpdate();
1505}
1506
1507TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001508 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001509 cfu_params_.is_official_build = false;
1510 cfu_params_.are_dev_features_enabled = true;
1511
1512 // THEN the forced app version + forced omaha url changes based on input.
1513 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1514 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1515
1516 TestCheckForUpdate();
1517}
1518
1519TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1520 // GIVEN a scheduled autest omaha url.
1521 cfu_params_.omaha_url = "autest-scheduled";
1522
1523 // THEN forced app version is cleared.
1524 // THEN forced omaha url changes to default constant.
1525 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1526
1527 TestCheckForUpdate();
1528}
1529
1530TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1531 // GIVEN a scheduled autest omaha url.
1532 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001533 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001534 cfu_params_.is_official_build = false;
1535 cfu_params_.are_dev_features_enabled = true;
1536
1537 // THEN forced app version changes based on input.
1538 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1539 // THEN forced omaha url changes to default constant.
1540 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1541
1542 TestCheckForUpdate();
1543}
1544
1545TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1546 // GIVEN a autest omaha url.
1547 cfu_params_.omaha_url = "autest";
1548
1549 // THEN forced app version is cleared.
1550 // THEN forced omaha url changes to default constant.
1551 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1552
1553 TestCheckForUpdate();
1554}
1555
1556TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1557 // GIVEN a autest omha url.
1558 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001559 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001560 cfu_params_.is_official_build = false;
1561 cfu_params_.are_dev_features_enabled = true;
1562
1563 // THEN forced app version changes based on input.
1564 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1565 // THEN forced omaha url changes to default constant.
1566 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1567
1568 TestCheckForUpdate();
1569}
1570
1571TEST_F(UpdateAttempterTest,
1572 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1573 // GIVEN a scheduled autest omaha url.
1574 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001575 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001576 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1577
1578 // THEN forced app version is cleared.
1579 // THEN forced omaha url changes to default constant.
1580 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1581
1582 TestCheckForUpdate();
1583}
1584
1585TEST_F(UpdateAttempterTest,
1586 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1587 // GIVEN a scheduled autest omaha url.
1588 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001589 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001590 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001591 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001592 cfu_params_.is_official_build = false;
1593 cfu_params_.are_dev_features_enabled = true;
1594
1595 // THEN forced app version changes based on input.
1596 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1597 // THEN forced omaha url changes to default constant.
1598 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1599
1600 TestCheckForUpdate();
1601}
1602
1603TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1604 // GIVEN a autest omaha url.
1605 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001606 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001607 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1608
1609 // THEN forced app version is cleared.
1610 // THEN forced omaha url changes to default constant.
1611 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1612
1613 TestCheckForUpdate();
1614}
1615
1616TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1617 // GIVEN a autest omaha url.
1618 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001619 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001620 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001621 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001622 cfu_params_.is_official_build = false;
1623 cfu_params_.are_dev_features_enabled = true;
1624
1625 // THEN forced app version changes based on input.
1626 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1627 // THEN forced omaha url changes to default constant.
1628 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1629
1630 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001631}
1632
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001633TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1634 // GIVEN a official build.
1635 // GIVEN forced callback is not set.
1636 attempter_.set_forced_update_pending_callback(nullptr);
1637
1638 // THEN we except forced app version + forced omaha url to be cleared.
1639 // THEN |ScheduleUpdates()| should not be called.
1640 cfu_params_.should_schedule_updates_be_called = false;
1641
1642 TestCheckForUpdate();
1643}
1644
1645TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001646 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001647 cfu_params_.is_official_build = false;
1648 cfu_params_.are_dev_features_enabled = true;
1649 // GIVEN forced callback is not set.
1650 attempter_.set_forced_update_pending_callback(nullptr);
1651
1652 // THEN the forced app version + forced omaha url changes based on input.
1653 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1654 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1655 // THEN |ScheduleUpdates()| should not be called.
1656 cfu_params_.should_schedule_updates_be_called = false;
1657
1658 TestCheckForUpdate();
1659}
1660
Xiaochu Liu88d90382018-08-29 16:09:11 -07001661TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1662 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1663 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1664 attempter_.CheckForInstall({}, "autest");
1665 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1666
1667 attempter_.CheckForInstall({}, "autest-scheduled");
1668 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1669
1670 attempter_.CheckForInstall({}, "http://omaha.phishing");
1671 EXPECT_EQ("", attempter_.forced_omaha_url());
1672}
1673
Colin Howesac170d92018-11-20 16:29:28 -08001674TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1675 attempter_.CheckForInstall({}, "http://foo.bar");
1676 attempter_.status_ = UpdateStatus::DOWNLOADING;
1677 EXPECT_TRUE(attempter_.is_install_);
1678 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1679 UpdateEngineStatus status;
1680 attempter_.GetStatus(&status);
1681 // Should set status to idle after an install operation.
1682 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1683}
1684
Colin Howes978c1082018-12-03 11:46:12 -08001685TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1686 attempter_.is_install_ = true;
1687 attempter_.Rollback(false);
1688 EXPECT_FALSE(attempter_.is_install_);
1689}
1690
1691TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1692 attempter_.is_install_ = true;
1693 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1694 EXPECT_FALSE(attempter_.is_install_);
1695}
1696
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001697TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001698 attempter_.CalculateUpdateParams(
Amin Hassani37b67232020-08-13 09:29:48 -07001699 "", "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001700 EXPECT_EQ("1234",
1701 fake_system_state_.request_params()->target_version_prefix());
1702
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001703 attempter_.CalculateUpdateParams(
Amin Hassani37b67232020-08-13 09:29:48 -07001704 "", "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001705 EXPECT_TRUE(
1706 fake_system_state_.request_params()->target_version_prefix().empty());
1707}
1708
Amin Hassani37b67232020-08-13 09:29:48 -07001709TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
1710 attempter_.CalculateUpdateParams(
1711 "", "", "", "hint", "", false, false, 4, false, false);
1712 EXPECT_EQ("hint", fake_system_state_.request_params()->lts_tag());
1713
1714 attempter_.CalculateUpdateParams(
1715 "", "", "", "", "", false, 4, false, false, false);
1716 EXPECT_TRUE(fake_system_state_.request_params()->lts_tag().empty());
1717}
1718
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001719TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1720 attempter_.CalculateUpdateParams("",
1721 "",
1722 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001723 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001724 "1234",
1725 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001726 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001727 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001728 false,
1729 false);
1730 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001731 EXPECT_EQ(4,
1732 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001733
1734 attempter_.CalculateUpdateParams("",
1735 "",
1736 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001737 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001738 "1234",
1739 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001740 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001741 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001742 false,
1743 false);
1744 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001745 EXPECT_EQ(4,
1746 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001747}
1748
Aaron Wood23bd3392017-10-06 14:48:25 -07001749TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1750 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1751 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001752 OmahaResponseHandlerAction response_action(&fake_system_state_);
1753 response_action.install_plan_.version = "a.b.c.d";
1754 response_action.install_plan_.system_version = "b.c.d.e";
1755 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001756 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001757 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1758 // completed, with the deferred-update error code.
1759 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001760 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001761 {
1762 UpdateEngineStatus status;
1763 attempter_.GetStatus(&status);
1764 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001765 EXPECT_TRUE(attempter_.install_plan_);
1766 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001767 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001768 status.new_size_bytes);
1769 }
1770 // An "error" event should have been created to tell Omaha that the update is
1771 // being deferred.
1772 EXPECT_TRUE(nullptr != attempter_.error_event_);
1773 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1774 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1775 ErrorCode expected_code = static_cast<ErrorCode>(
1776 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1777 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1778 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1779 // End the processing
1780 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1781 // Validate the state of the attempter.
1782 {
1783 UpdateEngineStatus status;
1784 attempter_.GetStatus(&status);
1785 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001786 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001787 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001788 status.new_size_bytes);
1789 }
1790}
1791
1792TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001793 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001794 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001795 // Verify in-progress update with UPDATE_AVAILABLE is running
1796 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001797 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001798}
1799
Aaron Woodbf5a2522017-10-04 10:58:36 -07001800TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1801 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1802
1803 UpdateCheckParams params = {.updates_enabled = true};
1804 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1805
1806 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1807 attempter_.GetCurrentUpdateAttemptFlags());
1808}
1809
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001810TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1811 UpdateCheckParams params = {.updates_enabled = true,
1812 .rollback_allowed = false};
1813 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1814 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1815}
1816
1817TEST_F(UpdateAttempterTest, RollbackAllowed) {
1818 UpdateCheckParams params = {.updates_enabled = true,
1819 .rollback_allowed = true};
1820 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1821 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1822}
1823
Aaron Wood081c0232017-10-19 17:14:58 -07001824TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1825 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1826
1827 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1828 EXPECT_EQ(UpdateAttemptFlags::kNone,
1829 attempter_.GetCurrentUpdateAttemptFlags());
1830}
1831
1832TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1833 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1834
1835 // This tests that when CheckForUpdate() is called with the non-interactive
1836 // flag set, that it doesn't change the current UpdateAttemptFlags.
1837 attempter_.CheckForUpdate("",
1838 "",
1839 UpdateAttemptFlags::kFlagNonInteractive |
1840 UpdateAttemptFlags::kFlagRestrictDownload);
1841 EXPECT_EQ(UpdateAttemptFlags::kNone,
1842 attempter_.GetCurrentUpdateAttemptFlags());
1843}
1844
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001845void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1846 bool is_policy_loaded,
1847 bool expected_reset) {
1848 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1849 .WillRepeatedly(Return(true));
1850 auto mock_policy_provider =
1851 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1852 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1853 .WillRepeatedly(Return(is_consumer));
1854 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1855 .WillRepeatedly(Return(is_policy_loaded));
1856 const policy::MockDevicePolicy device_policy;
1857 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1858 .WillRepeatedly(ReturnRef(device_policy));
1859 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1860 SetRollbackHappened(false))
1861 .Times(expected_reset ? 1 : 0);
1862 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassani37b67232020-08-13 09:29:48 -07001863 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001864 ScheduleQuitMainLoop();
1865}
1866
1867TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1868 loop_.PostTask(FROM_HERE,
1869 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1870 base::Unretained(this),
1871 /*is_consumer=*/false,
1872 /*is_policy_loaded=*/false,
1873 /*expected_reset=*/false));
1874 loop_.Run();
1875}
1876
1877TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1878 loop_.PostTask(FROM_HERE,
1879 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1880 base::Unretained(this),
1881 /*is_consumer=*/true,
1882 /*is_policy_loaded=*/false,
1883 /*expected_reset=*/true));
1884 loop_.Run();
1885}
1886
1887TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1888 loop_.PostTask(FROM_HERE,
1889 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1890 base::Unretained(this),
1891 /*is_consumer=*/false,
1892 /*is_policy_loaded=*/true,
1893 /*expected_reset=*/true));
1894 loop_.Run();
1895}
1896
Marton Hunyady199152d2018-05-07 19:08:48 +02001897TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001898 attempter_.install_plan_.reset(new InstallPlan);
1899 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001900
1901 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1902 SetRollbackHappened(true))
1903 .Times(1);
1904 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1905}
1906
1907TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001908 attempter_.install_plan_.reset(new InstallPlan);
1909 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001910
1911 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1912 SetRollbackHappened(true))
1913 .Times(0);
1914 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1915}
1916
Marton Hunyadya0302682018-05-16 18:52:13 +02001917TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001918 attempter_.install_plan_.reset(new InstallPlan);
1919 attempter_.install_plan_->is_rollback = true;
1920 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001921
1922 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1923 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1924 .Times(1);
1925 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1926}
1927
1928TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001929 attempter_.install_plan_.reset(new InstallPlan);
1930 attempter_.install_plan_->is_rollback = false;
1931 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001932
1933 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1934 ReportEnterpriseRollbackMetrics(_, _))
1935 .Times(0);
1936 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1937}
1938
1939TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001940 attempter_.install_plan_.reset(new InstallPlan);
1941 attempter_.install_plan_->is_rollback = true;
1942 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001943
1944 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1945 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1946 .Times(1);
1947 MockAction action;
1948 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1949 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1950}
1951
1952TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001953 attempter_.install_plan_.reset(new InstallPlan);
1954 attempter_.install_plan_->is_rollback = false;
1955 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001956
1957 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1958 ReportEnterpriseRollbackMetrics(_, _))
1959 .Times(0);
1960 MockAction action;
1961 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1962 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1963}
1964
May Lippert60aa3ca2018-08-15 16:55:29 -07001965TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1966 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1967 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1968 .Times(0);
1969 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1970}
1971
1972TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1973 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1974 fake_system_state_.set_device_policy(device_policy.get());
1975 // Make device policy return that this is not enterprise enrolled
1976 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1977
1978 // Ensure that the metric is not recorded.
1979 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1980 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1981 .Times(0);
1982 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1983}
1984
1985TEST_F(UpdateAttempterTest,
1986 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1987 constexpr int kDaysToUpdate = 15;
1988 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1989 fake_system_state_.set_device_policy(device_policy.get());
1990 // Make device policy return that this is enterprise enrolled
1991 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1992 // Pretend that there's a time restriction policy in place
1993 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1994 .WillOnce(Return(true));
1995
1996 FakePrefs fake_prefs;
1997 Time update_first_seen_at = Time::Now();
1998 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1999 update_first_seen_at.ToInternalValue());
2000
2001 FakeClock fake_clock;
2002 Time update_finished_at =
2003 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2004 fake_clock.SetWallclockTime(update_finished_at);
2005
2006 fake_system_state_.set_clock(&fake_clock);
2007 fake_system_state_.set_prefs(&fake_prefs);
2008
2009 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2010 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
2011 .Times(1);
2012 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2013}
2014
2015TEST_F(UpdateAttempterTest,
2016 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
2017 constexpr int kDaysToUpdate = 15;
2018 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2019 fake_system_state_.set_device_policy(device_policy.get());
2020 // Make device policy return that this is enterprise enrolled
2021 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
2022 // Pretend that there's no time restriction policy in place
2023 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
2024 .WillOnce(Return(false));
2025
2026 FakePrefs fake_prefs;
2027 Time update_first_seen_at = Time::Now();
2028 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2029 update_first_seen_at.ToInternalValue());
2030
2031 FakeClock fake_clock;
2032 Time update_finished_at =
2033 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2034 fake_clock.SetWallclockTime(update_finished_at);
2035
2036 fake_system_state_.set_clock(&fake_clock);
2037 fake_system_state_.set_prefs(&fake_prefs);
2038
2039 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2040 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2041 .Times(1);
2042 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2043}
2044
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002045TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2046 // GIVEN an update finished.
2047
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002048 // THEN update_engine should call update completion.
2049 pd_params_.should_update_completed_be_called = true;
2050 // THEN need reboot since update applied.
2051 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2052 // THEN install indication should be false.
2053
2054 TestProcessingDone();
2055}
2056
2057TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2058 // GIVEN an update finished.
2059 // GIVEN DLC |AppParams| list.
2060 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2061 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2062 {dlc_2, {.name = dlc_2}}};
2063
2064 // THEN update_engine should call update completion.
2065 pd_params_.should_update_completed_be_called = true;
2066 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002067 // THEN need reboot since update applied.
2068 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2069 // THEN install indication should be false.
2070
2071 TestProcessingDone();
2072}
2073
2074TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2075 // GIVEN an install finished.
2076 pd_params_.is_install = true;
2077
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002078 // THEN update_engine should call install completion.
2079 pd_params_.should_install_completed_be_called = true;
2080 // THEN go idle.
2081 // THEN install indication should be false.
2082
2083 TestProcessingDone();
2084}
2085
2086TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2087 // GIVEN an install finished.
2088 pd_params_.is_install = true;
2089 // GIVEN DLC |AppParams| list.
2090 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2091 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2092 {dlc_2, {.name = dlc_2}}};
2093
2094 // THEN update_engine should call install completion.
2095 pd_params_.should_install_completed_be_called = true;
2096 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002097 // THEN go idle.
2098 // THEN install indication should be false.
2099
2100 TestProcessingDone();
2101}
2102
2103TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2104 // GIVEN an install finished.
2105 pd_params_.is_install = true;
2106 // GIVEN a reporting error occurred.
2107 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2108
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002109 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002110 // THEN go idle.
2111 // THEN install indication should be false.
2112
2113 TestProcessingDone();
2114}
2115
2116TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2117 // GIVEN an update finished.
2118 // GIVEN an action error occured.
2119 pd_params_.code = ErrorCode::kNoUpdate;
2120
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002121 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002122 // THEN go idle.
2123 // THEN install indication should be false.
2124
2125 TestProcessingDone();
2126}
2127
2128TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2129 // GIVEN an install finished.
2130 pd_params_.is_install = true;
2131 // GIVEN an action error occured.
2132 pd_params_.code = ErrorCode::kNoUpdate;
2133
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002134 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002135 // THEN go idle.
2136 // THEN install indication should be false.
2137
2138 TestProcessingDone();
2139}
2140
2141TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2142 // GIVEN an update finished.
2143 // GIVEN an action error occured.
2144 pd_params_.code = ErrorCode::kError;
2145 // GIVEN an event error is set.
2146 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2147 OmahaEvent::kResultError,
2148 ErrorCode::kError));
2149
2150 // THEN indicate a error event.
2151 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2152 // THEN install indication should be false.
2153
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002154 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002155 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2156 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2157 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2158 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2159 pd_params_.should_schedule_updates_be_called = false;
2160
2161 TestProcessingDone();
2162}
2163
2164TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2165 // GIVEN an install finished.
2166 pd_params_.is_install = true;
2167 // GIVEN an action error occured.
2168 pd_params_.code = ErrorCode::kError;
2169 // GIVEN an event error is set.
2170 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2171 OmahaEvent::kResultError,
2172 ErrorCode::kError));
2173
2174 // THEN indicate a error event.
2175 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2176 // THEN install indication should be false.
2177
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002178 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002179 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2180 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2181 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2182 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2183 pd_params_.should_schedule_updates_be_called = false;
2184
2185 TestProcessingDone();
2186}
2187
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002188void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2189 // Tests that checks if |device_quick_fix_build_token| arrives when
2190 // policy is set and the device is enterprise enrolled based on |set_token|.
2191 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002192 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2193 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002194 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002195
2196 if (set_token)
2197 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2198 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2199 else
2200 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2201 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002202 attempter_.policy_provider_.reset(
2203 new policy::PolicyProvider(std::move(device_policy)));
Amin Hassani37b67232020-08-13 09:29:48 -07002204 attempter_.Update("", "", "", "", "", false, false, 0, false, false);
Askar Aitzhan570ca872019-04-24 11:16:12 +02002205
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002206 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002207 ScheduleQuitMainLoop();
2208}
2209
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002210TEST_F(UpdateAttempterTest,
2211 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002212 loop_.PostTask(FROM_HERE,
2213 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002214 base::Unretained(this),
2215 /*set_token=*/true));
2216 loop_.Run();
2217}
2218
2219TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2220 loop_.PostTask(FROM_HERE,
2221 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2222 base::Unretained(this),
2223 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002224 loop_.Run();
2225}
2226
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002227TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2228 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2229 .Times(1);
2230 EXPECT_TRUE(attempter_.ScheduleUpdates());
2231 // Now there is an update scheduled which means that all subsequent
2232 // |ScheduleUpdates()| should fail.
2233 EXPECT_FALSE(attempter_.ScheduleUpdates());
2234 EXPECT_FALSE(attempter_.ScheduleUpdates());
2235 EXPECT_FALSE(attempter_.ScheduleUpdates());
2236}
2237
2238// Critical tests to always make sure that an update is scheduled. The following
2239// unittest(s) try and cover the correctness in synergy between
2240// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2241// actions that happen in the flow when |UpdateAttempter| get callbacked on
2242// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2243void UpdateAttempterTest::TestOnUpdateScheduled() {
2244 // Setup
2245 attempter_.SetWaitingForScheduledCheck(true);
2246 attempter_.DisableUpdate();
2247 attempter_.DisableScheduleUpdates();
2248
2249 // Invocation
2250 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2251
2252 // Verify
2253 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2254 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2255 attempter_.WasScheduleUpdatesCalled());
2256 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2257}
2258
2259TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2260 // GIVEN failed status.
2261
2262 // THEN update should be scheduled.
2263 ous_params_.should_schedule_updates_be_called = true;
2264
2265 TestOnUpdateScheduled();
2266}
2267
2268TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2269 // GIVEN ask me again later status.
2270 ous_params_.status = EvalStatus::kAskMeAgainLater;
2271
2272 // THEN update should be scheduled.
2273 ous_params_.should_schedule_updates_be_called = true;
2274
2275 TestOnUpdateScheduled();
2276}
2277
2278TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2279 // GIVEN continue status.
2280 ous_params_.status = EvalStatus::kContinue;
2281
2282 // THEN update should be scheduled.
2283 ous_params_.should_schedule_updates_be_called = true;
2284
2285 TestOnUpdateScheduled();
2286}
2287
2288TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2289 // GIVEN updates disabled.
2290 ous_params_.params = {.updates_enabled = false};
2291 // GIVEN succeeded status.
2292 ous_params_.status = EvalStatus::kSucceeded;
2293
2294 // THEN update should not be scheduled.
2295
2296 TestOnUpdateScheduled();
2297}
2298
2299TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2300 // GIVEN updates enabled.
2301 ous_params_.params = {.updates_enabled = true};
2302 // GIVEN succeeded status.
2303 ous_params_.status = EvalStatus::kSucceeded;
2304
2305 // THEN update should be called indicating status change.
2306 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2307 ous_params_.should_update_be_called = true;
2308
2309 TestOnUpdateScheduled();
2310}
2311
Amin Hassani9be122e2019-08-29 09:20:12 -07002312TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2313 UpdateEngineStatus status;
2314 attempter_.GetStatus(&status);
2315 EXPECT_FALSE(status.is_enterprise_rollback);
2316}
2317
2318TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2319 attempter_.install_plan_.reset(new InstallPlan);
2320 attempter_.install_plan_->is_rollback = false;
2321
2322 UpdateEngineStatus status;
2323 attempter_.GetStatus(&status);
2324 EXPECT_FALSE(status.is_enterprise_rollback);
2325}
2326
2327TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2328 attempter_.install_plan_.reset(new InstallPlan);
2329 attempter_.install_plan_->is_rollback = true;
2330
2331 UpdateEngineStatus status;
2332 attempter_.GetStatus(&status);
2333 EXPECT_TRUE(status.is_enterprise_rollback);
2334}
2335
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002336TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2337 UpdateEngineStatus status;
2338 attempter_.GetStatus(&status);
2339 EXPECT_FALSE(status.will_powerwash_after_reboot);
2340}
2341
2342TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2343 attempter_.install_plan_.reset(new InstallPlan);
2344 attempter_.install_plan_->powerwash_required = true;
2345
2346 UpdateEngineStatus status;
2347 attempter_.GetStatus(&status);
2348 EXPECT_TRUE(status.will_powerwash_after_reboot);
2349}
2350
2351TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2352 attempter_.install_plan_.reset(new InstallPlan);
2353 attempter_.install_plan_->is_rollback = true;
2354
2355 UpdateEngineStatus status;
2356 attempter_.GetStatus(&status);
2357 EXPECT_TRUE(status.will_powerwash_after_reboot);
2358}
2359
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002360TEST_F(UpdateAttempterTest, FutureEolTest) {
2361 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002362 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002363 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2364 .WillOnce(
2365 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2366
2367 UpdateEngineStatus status;
2368 attempter_.GetStatus(&status);
2369 EXPECT_EQ(eol_date, status.eol_date);
2370}
2371
2372TEST_F(UpdateAttempterTest, PastEolTest) {
2373 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002374 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002375 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2376 .WillOnce(
2377 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2378
2379 UpdateEngineStatus status;
2380 attempter_.GetStatus(&status);
2381 EXPECT_EQ(eol_date, status.eol_date);
2382}
2383
2384TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002385 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002386 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2387 .WillOnce(Return(false));
2388
2389 UpdateEngineStatus status;
2390 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002391 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2392}
2393
2394TEST_F(UpdateAttempterTest, MissingEolTest) {
2395 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2396
2397 UpdateEngineStatus status;
2398 attempter_.GetStatus(&status);
2399 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002400}
2401
Andrewe045aef2020-01-08 16:29:22 -08002402TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002403 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002404 FakePrefs fake_prefs;
2405 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002406 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002407 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002408 attempter_.CalculateDlcParams();
2409
2410 OmahaRequestParams* params = fake_system_state_.request_params();
2411 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2412 OmahaRequestParams::AppParams dlc_app_params =
2413 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2414 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2415 EXPECT_EQ(false, dlc_app_params.send_ping);
2416 // When the DLC gets installed, a ping is not sent, therefore we don't store
2417 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002418 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002419 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002420 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2421 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002422 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002423 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002424}
2425
2426TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002427 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002428 FakePrefs fake_prefs;
2429 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002430 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002431 .WillOnce(
2432 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2433
2434 attempter_.is_install_ = false;
2435 attempter_.CalculateDlcParams();
2436
2437 OmahaRequestParams* params = fake_system_state_.request_params();
2438 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2439 OmahaRequestParams::AppParams dlc_app_params =
2440 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2441 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2442
2443 EXPECT_EQ(true, dlc_app_params.send_ping);
2444 EXPECT_EQ(0, dlc_app_params.ping_active);
2445 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2446 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2447}
2448
2449TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002450 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002451 MemoryPrefs prefs;
2452 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002453 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002454 .WillOnce(
2455 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2456
2457 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002458 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002459 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002460 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002461 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002462 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002463 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002464 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2465 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2466 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002467 attempter_.is_install_ = false;
2468 attempter_.CalculateDlcParams();
2469
2470 OmahaRequestParams* params = fake_system_state_.request_params();
2471 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2472 OmahaRequestParams::AppParams dlc_app_params =
2473 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2474 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2475
2476 EXPECT_EQ(true, dlc_app_params.send_ping);
2477 EXPECT_EQ(0, dlc_app_params.ping_active);
2478 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2479 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2480}
2481
2482TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002483 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002484 MemoryPrefs fake_prefs;
2485 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002486 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002487 .WillOnce(
2488 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2489
2490 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002491 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002492 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002493 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002494 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002495 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002496 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002497
2498 fake_system_state_.prefs()->SetInt64(active_key, 1);
2499 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2500 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002501 attempter_.is_install_ = false;
2502 attempter_.CalculateDlcParams();
2503
2504 OmahaRequestParams* params = fake_system_state_.request_params();
2505 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2506 OmahaRequestParams::AppParams dlc_app_params =
2507 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2508 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2509
2510 EXPECT_EQ(true, dlc_app_params.send_ping);
2511 EXPECT_EQ(1, dlc_app_params.ping_active);
2512 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2513 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2514}
Andrewa8d7df32020-03-15 20:10:01 -07002515
2516TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002517 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002518 FakePrefs fake_prefs;
2519 fake_system_state_.set_prefs(&fake_prefs);
2520 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002521 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002522 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002523 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002524 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002525 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002526 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2527 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2528 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2529 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2530 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2531 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002532
Andrew065d78d2020-04-07 15:43:07 -07002533 attempter_.dlc_ids_ = {dlc_id};
2534 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002535 attempter_.CalculateDlcParams();
2536
Andrew065d78d2020-04-07 15:43:07 -07002537 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2538 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2539 // Active key is set on install.
2540 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2541 int64_t temp_int;
2542 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2543 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002544}
2545
2546TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002547 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002548 FakePrefs fake_prefs;
2549 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002550 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002551 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002552 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002553 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002554 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2555 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002556 EXPECT_EQ(temp_int, kPingActiveValue);
2557}
2558
2559TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002560 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002561 MemoryPrefs fake_prefs;
2562 fake_system_state_.set_prefs(&fake_prefs);
2563 auto sub_keys = {
2564 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2565 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002566 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002567 fake_system_state_.prefs()->SetInt64(key, 1);
2568 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2569 }
Andrewa8d7df32020-03-15 20:10:01 -07002570 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002571 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002572 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002573 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2574 }
Andrewa8d7df32020-03-15 20:10:01 -07002575}
2576
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002577TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2578 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2579 attempter_.omaha_request_params_->set_dlc_apps_params(
2580 {{dlc_1, {.name = dlc_1, .updated = false}},
2581 {dlc_2, {.name = dlc_2}},
2582 {dlc_3, {.name = dlc_3, .updated = false}}});
2583 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2584}
2585
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002586} // namespace chromeos_update_engine