blob: b348d5005b4f36eb19e578a208c82bbb0096b796 [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
Amin Hassaniec7bc112020-10-29 16:47:58 -070017#include "update_engine/cros/update_attempter.h"
Alex Deymo2c0db7b2014-11-04 12:23:39 -080018
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>
Miriam Polzeraff72002020-08-27 08:20:39 +020028#include <base/files/scoped_temp_dir.h>
Qijiang Fanb0b6cc22020-10-15 21:54:11 +090029#include <base/task/single_thread_task_executor.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070030#include <brillo/message_loops/base_message_loop.h>
31#include <brillo/message_loops/message_loop.h>
32#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070033#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020034#include <policy/libpolicy.h>
35#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020036#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070037
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070038#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080039#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/common/fake_clock.h"
41#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080042#include "update_engine/common/mock_action.h"
43#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080044#include "update_engine/common/mock_http_fetcher.h"
45#include "update_engine/common/mock_prefs.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070046#include "update_engine/common/mock_service_observer.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080047#include "update_engine/common/platform_constants.h"
48#include "update_engine/common/prefs.h"
49#include "update_engine/common/test_utils.h"
50#include "update_engine/common/utils.h"
Amin Hassaniec7bc112020-10-29 16:47:58 -070051#include "update_engine/cros/fake_system_state.h"
52#include "update_engine/cros/mock_p2p_manager.h"
53#include "update_engine/cros/mock_payload_state.h"
54#include "update_engine/cros/omaha_utils.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070055#include "update_engine/libcurl_http_fetcher.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080056#include "update_engine/payload_consumer/filesystem_verifier_action.h"
57#include "update_engine/payload_consumer/install_plan.h"
58#include "update_engine/payload_consumer/payload_constants.h"
59#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070060#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070061#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070062
David Zeuthen985b1122013-10-09 12:13:15 -070063using base::Time;
64using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070065using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070066using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070067using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070068using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070069using policy::DevicePolicy;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070070using std::map;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070071using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070072using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070073using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070074using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070075using testing::_;
Andrew065d78d2020-04-07 15:43:07 -070076using testing::Contains;
Darin Petkov36275772010-10-01 11:40:57 -070077using testing::DoAll;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070078using testing::ElementsAre;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070079using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070080using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070081using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070082using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080083using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070084using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070085using testing::Property;
86using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070087using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020088using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080089using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070090using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070091using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070092using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070093using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070094
95namespace chromeos_update_engine {
96
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080097namespace {
98
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070099const UpdateStatus kNonIdleUpdateStatuses[] = {
100 UpdateStatus::CHECKING_FOR_UPDATE,
101 UpdateStatus::UPDATE_AVAILABLE,
102 UpdateStatus::DOWNLOADING,
103 UpdateStatus::VERIFYING,
104 UpdateStatus::FINALIZING,
105 UpdateStatus::UPDATED_NEED_REBOOT,
106 UpdateStatus::REPORTING_ERROR_EVENT,
107 UpdateStatus::ATTEMPTING_ROLLBACK,
108 UpdateStatus::DISABLED,
109 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
110};
111
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700112struct CheckForUpdateTestParams {
113 // Setups + Inputs:
114 UpdateStatus status = UpdateStatus::IDLE;
115 string app_version = "fake_app_version";
116 string omaha_url = "fake_omaha_url";
117 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
118 bool is_official_build = true;
119 bool are_dev_features_enabled = false;
120
121 // Expects:
122 string expected_forced_app_version = "";
123 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700124 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700125 bool expected_result = true;
126};
127
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700128struct OnUpdateScheduledTestParams {
129 // Setups + Inputs:
130 UpdateCheckParams params = {};
131 EvalStatus status = EvalStatus::kFailed;
132 // Expects:
133 UpdateStatus exit_status = UpdateStatus::IDLE;
134 bool should_schedule_updates_be_called = false;
135 bool should_update_be_called = false;
136};
137
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700138struct ProcessingDoneTestParams {
139 // Setups + Inputs:
140 bool is_install = false;
141 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
142 ActionProcessor* processor = nullptr;
143 ErrorCode code = ErrorCode::kSuccess;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700144 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700145
146 // Expects:
147 const bool kExpectedIsInstall = false;
148 bool should_schedule_updates_be_called = true;
149 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700150 bool should_install_completed_be_called = false;
151 bool should_update_completed_be_called = false;
152 vector<string> args_to_install_completed;
153 vector<string> args_to_update_completed;
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700154};
155
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800156class MockDlcService : public DlcServiceInterface {
157 public:
Amin Hassani2b68e6b2020-04-17 10:49:12 -0700158 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700159 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
160 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800161};
162
163} // namespace
164
Marton Hunyadya0302682018-05-16 18:52:13 +0200165const char kRollbackVersion[] = "10575.39.2";
166
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700167// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700168// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700169// methods.
170class UpdateAttempterUnderTest : public UpdateAttempter {
171 public:
Amin Hassani538bd592020-11-04 20:46:08 -0800172 UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700173
Amin Hassanie8153632020-10-27 15:11:28 -0700174 void Update(const UpdateCheckParams& params) override {
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700175 update_called_ = true;
176 if (do_update_) {
Amin Hassanie8153632020-10-27 15:11:28 -0700177 UpdateAttempter::Update(params);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700178 return;
179 }
180 LOG(INFO) << "[TEST] Update() disabled.";
181 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
182 }
183
184 void DisableUpdate() { do_update_ = false; }
185
186 bool WasUpdateCalled() const { return update_called_; }
187
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700188 // Wrap the update scheduling method, allowing us to opt out of scheduled
189 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700190 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700191 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700192 if (do_schedule_updates_)
193 return UpdateAttempter::ScheduleUpdates();
194 LOG(INFO) << "[TEST] Update scheduling disabled.";
195 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700196 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700197 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700198
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700199 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
200
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700201 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700202 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700203
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700204 // Need to expose following private members of |UpdateAttempter| for tests.
205 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700206 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800207
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700208 // Need to expose |waiting_for_scheduled_check_| for testing.
209 void SetWaitingForScheduledCheck(bool waiting) {
210 waiting_for_scheduled_check_ = waiting;
211 }
212
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700213 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700214 // Used for overrides of |Update()|.
215 bool update_called_ = false;
216 bool do_update_ = true;
217
218 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700219 bool schedule_updates_called_ = false;
220 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700221};
222
223class UpdateAttempterTest : public ::testing::Test {
224 protected:
Amin Hassani538bd592020-11-04 20:46:08 -0800225 void SetUp() override {
Gilad Arnold1f847232014-04-07 12:07:49 -0700226 // Override system state members.
Amin Hassani538bd592020-11-04 20:46:08 -0800227 FakeSystemState::CreateInstance();
228 FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
229 FakeSystemState::Get()->set_update_attempter(&attempter_);
230 FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
231 FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700232 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700233
Amin Hassani538bd592020-11-04 20:46:08 -0800234 certificate_checker_.reset(new CertificateChecker(
235 FakeSystemState::Get()->mock_prefs(), &openssl_wrapper_));
236 certificate_checker_->Init();
Alex Deymo33e91e72015-12-01 18:26:08 -0300237
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800238 attempter_.set_forced_update_pending_callback(
239 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700240 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700241 attempter_.Init();
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700242
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700243 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700244 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700245 EXPECT_EQ(0.0, attempter_.download_progress_);
246 EXPECT_EQ(0, attempter_.last_checked_time_);
247 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700248 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800249 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700250 attempter_.processor_.reset(processor_); // Transfers ownership.
Amin Hassani538bd592020-11-04 20:46:08 -0800251 prefs_ = FakeSystemState::Get()->mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700252
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700253 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700254 actual_using_p2p_for_downloading_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800255 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700256 SetUsingP2PForDownloading(_))
257 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
Amin Hassani538bd592020-11-04 20:46:08 -0800258 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700259 GetUsingP2PForDownloading())
260 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
261 actual_using_p2p_for_sharing_ = false;
Amin Hassani538bd592020-11-04 20:46:08 -0800262 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700263 SetUsingP2PForSharing(_))
264 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
Amin Hassani538bd592020-11-04 20:46:08 -0800265 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Gilad Arnold74b5f552014-10-07 08:17:16 -0700266 GetUsingP2PForDownloading())
267 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700268 }
269
Alex Deymo60ca1a72015-06-18 18:19:15 -0700270 public:
271 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200272
Alex Deymo60ca1a72015-06-18 18:19:15 -0700273 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800274 void UpdateTestStart();
275 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700276 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700277 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700278 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700279 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700280 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700281 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700282 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700283 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700284 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700285 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700286 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700287 void SessionIdTestChange();
288 void SessionIdTestEnforceEmptyStrPingOmaha();
289 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700290 void SessionIdTestInDownloadAction();
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200291 void ResetRollbackHappenedStart(bool is_consumer,
292 bool is_policy_available,
293 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700294 // Staging related callbacks.
295 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
296 void CheckStagingOff();
297 void StagingSetsPrefsAndTurnsOffScatteringStart();
298 void StagingOffIfInteractiveStart();
299 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700300
Gilad Arnold74b5f552014-10-07 08:17:16 -0700301 bool actual_using_p2p_for_downloading() {
302 return actual_using_p2p_for_downloading_;
303 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800304 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700305
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700306 // |CheckForUpdate()| related member functions.
307 void TestCheckForUpdate();
308
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700309 // |OnUpdateScheduled()| related member functions.
310 void TestOnUpdateScheduled();
311
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700312 // |ProcessingDone()| related member functions.
313 void TestProcessingDone();
314
Qijiang Fanb0b6cc22020-10-15 21:54:11 +0900315 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
316 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700317
Amin Hassani538bd592020-11-04 20:46:08 -0800318 UpdateAttempterUnderTest attempter_;
Alex Deymo33e91e72015-12-01 18:26:08 -0300319 OpenSSLWrapper openssl_wrapper_;
Amin Hassani538bd592020-11-04 20:46:08 -0800320 std::unique_ptr<CertificateChecker> certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800321 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700322 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700323
Alex Deymo8427b4a2014-11-05 14:00:32 -0800324 NiceMock<MockActionProcessor>* processor_;
Amin Hassani538bd592020-11-04 20:46:08 -0800325 NiceMock<MockPrefs>* prefs_;
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800326 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700327
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700328 // |CheckForUpdate()| test params.
329 CheckForUpdateTestParams cfu_params_;
330
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700331 // |OnUpdateScheduled()| test params.
332 OnUpdateScheduledTestParams ous_params_;
333
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700334 // |ProcessingDone()| test params.
335 ProcessingDoneTestParams pd_params_;
336
Gilad Arnold74b5f552014-10-07 08:17:16 -0700337 bool actual_using_p2p_for_downloading_;
338 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700339};
340
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700341void UpdateAttempterTest::TestCheckForUpdate() {
342 // Setup
343 attempter_.status_ = cfu_params_.status;
Amin Hassani538bd592020-11-04 20:46:08 -0800344 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700345 cfu_params_.is_official_build);
Amin Hassani538bd592020-11-04 20:46:08 -0800346 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700347 cfu_params_.are_dev_features_enabled);
348
349 // Invocation
350 EXPECT_EQ(
351 cfu_params_.expected_result,
352 attempter_.CheckForUpdate(
353 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
354
355 // Verify
356 EXPECT_EQ(cfu_params_.expected_forced_app_version,
357 attempter_.forced_app_version());
358 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
359 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700360 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
361 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700362}
363
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700364void UpdateAttempterTest::TestProcessingDone() {
365 // Setup
366 attempter_.DisableScheduleUpdates();
367 attempter_.is_install_ = pd_params_.is_install;
368 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700369 attempter_.omaha_request_params_->set_dlc_apps_params(
370 pd_params_.dlc_apps_params);
371
372 // Expects
373 if (pd_params_.should_install_completed_be_called)
374 EXPECT_CALL(mock_dlcservice_,
375 InstallCompleted(pd_params_.args_to_install_completed))
376 .WillOnce(Return(true));
377 else
378 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
379 if (pd_params_.should_update_completed_be_called)
380 EXPECT_CALL(mock_dlcservice_,
381 UpdateCompleted(pd_params_.args_to_update_completed))
382 .WillOnce(Return(true));
383 else
384 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700385
386 // Invocation
387 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
388
389 // Verify
390 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
391 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
392 attempter_.WasScheduleUpdatesCalled());
393 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
394}
395
Alex Deymo60ca1a72015-06-18 18:19:15 -0700396void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700397 loop_.PostTask(
398 FROM_HERE,
399 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
400 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700401}
402
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700403void UpdateAttempterTest::SessionIdTestChange() {
404 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
405 const auto old_session_id = attempter_.session_id_;
Amin Hassanie8153632020-10-27 15:11:28 -0700406 attempter_.Update({});
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700407 EXPECT_NE(old_session_id, attempter_.session_id_);
408 ScheduleQuitMainLoop();
409}
410
411TEST_F(UpdateAttempterTest, SessionIdTestChange) {
412 loop_.PostTask(FROM_HERE,
413 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
414 base::Unretained(this)));
415 loop_.Run();
416}
417
418void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
419 // The |session_id_| should not be changed and should remain as an empty
420 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
421 // and |PingOmaha()| is called.
422 attempter_.DisableScheduleUpdates();
423 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
424 const auto old_session_id = attempter_.session_id_;
425 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
426 if (aa->Type() == OmahaRequestAction::StaticType()) {
427 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
428 }
429 };
430 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
431 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
432 EXPECT_CALL(*processor_, StartProcessing());
433 attempter_.PingOmaha();
434 EXPECT_EQ(old_session_id, attempter_.session_id_);
435 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
436 ScheduleQuitMainLoop();
437}
438
439TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
440 loop_.PostTask(
441 FROM_HERE,
442 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
443 base::Unretained(this)));
444 loop_.Run();
445}
446
447void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
448 // All session IDs passed into |OmahaRequestActions| should be enforced to
449 // have the same value in |BuildUpdateActions()|.
450 unordered_set<string> session_ids;
451 // Gather all the session IDs being passed to |OmahaRequestActions|.
452 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
453 if (aa->Type() == OmahaRequestAction::StaticType())
454 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
455 };
456 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
457 .WillRepeatedly(Invoke(CheckSessionId));
458 attempter_.BuildUpdateActions(false);
459 // Validate that all the session IDs are the same.
460 EXPECT_EQ(1, session_ids.size());
461 ScheduleQuitMainLoop();
462}
463
464TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
465 loop_.PostTask(
466 FROM_HERE,
467 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
468 base::Unretained(this)));
469 loop_.Run();
470}
471
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700472void UpdateAttempterTest::SessionIdTestInDownloadAction() {
473 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
474 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
475 string header_value;
476 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
477 if (aa->Type() == DownloadAction::StaticType()) {
478 DownloadAction* da = static_cast<DownloadAction*>(aa);
479 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
480 &header_value));
481 }
482 };
483 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
484 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
485 attempter_.BuildUpdateActions(false);
486 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
487 EXPECT_EQ(attempter_.session_id_, header_value);
488 ScheduleQuitMainLoop();
489}
490
491TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
492 loop_.PostTask(FROM_HERE,
493 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
494 base::Unretained(this)));
495 loop_.Run();
496}
497
Darin Petkov1b003102010-11-30 10:18:36 -0800498TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700499 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800500 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700501 DownloadAction action(prefs_,
502 nullptr,
503 nullptr,
Amin Hassani7ecda262017-07-11 17:10:50 -0700504 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700505 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800506 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700507 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700508 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700509 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700510 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800511}
512
513TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800514 MockAction action;
515 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700516 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800517 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800518 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700519 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
520 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800521}
522
Aaron Wood9321f502017-09-07 11:18:54 -0700523TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
524 // Simple test case, where all the values match (nothing was skipped)
525 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
526 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
527 uint64_t bytes_received_1 = bytes_progressed_1;
528 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
529 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
530
531 double progress_1 =
532 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
533 double progress_2 =
534 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
535
536 EXPECT_EQ(0.0, attempter_.download_progress_);
537 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700538 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700539 attempter_.new_payload_size_ = bytes_total;
540 NiceMock<MockServiceObserver> observer;
541 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700542 SendStatusUpdate(AllOf(
543 Field(&UpdateEngineStatus::progress, progress_1),
544 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
545 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700546 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700547 SendStatusUpdate(AllOf(
548 Field(&UpdateEngineStatus::progress, progress_2),
549 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
550 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700551 attempter_.AddObserver(&observer);
552 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
553 EXPECT_EQ(progress_1, attempter_.download_progress_);
554 // This iteration validates that a later set of updates to the variables are
555 // properly handled (so that |getStatus()| will return the same progress info
556 // as the callback is receiving.
557 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
558 EXPECT_EQ(progress_2, attempter_.download_progress_);
559}
560
561TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700562 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700563 // first bytes are received.
564 uint64_t bytes_progressed = 1024 * 1024; // 1MB
565 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
566 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
567 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
568 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700569 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700570 attempter_.new_payload_size_ = bytes_total;
571 EXPECT_EQ(0.0, attempter_.download_progress_);
572 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700573 EXPECT_CALL(observer,
574 SendStatusUpdate(AllOf(
575 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
576 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700577 attempter_.AddObserver(&observer);
578 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
579 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
580}
581
582TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
583 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700584 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700585 uint64_t bytes_progressed = 0; // ignored
586 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
587 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
588 attempter_.status_ = UpdateStatus::DOWNLOADING;
589 attempter_.new_payload_size_ = bytes_total;
590 EXPECT_EQ(0.0, attempter_.download_progress_);
591 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700592 EXPECT_CALL(observer,
593 SendStatusUpdate(AllOf(
594 Field(&UpdateEngineStatus::progress, 1.0),
595 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
596 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700597 attempter_.AddObserver(&observer);
598 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
599 EXPECT_EQ(1.0, attempter_.download_progress_);
600}
601
Darin Petkov1b003102010-11-30 10:18:36 -0800602TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700603 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800604 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani538bd592020-11-04 20:46:08 -0800605 OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800606 ObjectCollectorAction<OmahaResponse> collector_action;
607 BondActions(&action, &collector_action);
608 OmahaResponse response;
609 response.poll_interval = 234;
610 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800611 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700612 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800613 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700614 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800615 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700616 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800617}
618
Alex Deymo30534502015-07-20 15:06:33 -0700619TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700620 FakePrefs fake_prefs;
621 string boot_id;
622 EXPECT_TRUE(utils::GetBootId(&boot_id));
623 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
Amin Hassani538bd592020-11-04 20:46:08 -0800624 FakeSystemState::Get()->set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700625 attempter_.Init();
626 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700627}
628
629TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700630 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700631 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700632
Amin Hassani538bd592020-11-04 20:46:08 -0800633 OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700634 EXPECT_EQ(ErrorCode::kOmahaRequestError,
635 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Amin Hassani538bd592020-11-04 20:46:08 -0800636 OmahaResponseHandlerAction omaha_response_handler_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800637 EXPECT_EQ(
638 ErrorCode::kOmahaResponseHandlerError,
639 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700640 DynamicPartitionControlStub dynamic_control_stub;
641 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800642 EXPECT_EQ(
643 ErrorCode::kFilesystemVerifierError,
644 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300645 PostinstallRunnerAction postinstall_runner_action(
Amin Hassani538bd592020-11-04 20:46:08 -0800646 FakeSystemState::Get()->fake_boot_control(),
647 FakeSystemState::Get()->fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800648 EXPECT_EQ(
649 ErrorCode::kPostinstallRunnerError,
650 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800651 MockAction action_mock;
652 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700653 EXPECT_EQ(ErrorCode::kError,
654 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700655}
656
Darin Petkov36275772010-10-01 11:40:57 -0700657TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700658 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800659 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700660 .WillOnce(Return(false));
661 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700662 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800663 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800664 .WillOnce(
665 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
666 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700667 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700668 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800669 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800670 .WillOnce(
671 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
672 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700673 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700674 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800675 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700676 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700677 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700678}
679
680TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800681 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700682 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700683 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
684 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800685 .WillOnce(
686 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
687 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800688 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700689 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800690 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700691 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800692 EXPECT_CALL(*prefs_,
693 SetInt64(kPrefsDeltaUpdateFailures,
694 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
695 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700696 attempter_.MarkDeltaUpdateFailure();
697}
698
Darin Petkov1b003102010-11-30 10:18:36 -0800699TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
700 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
701 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Amin Hassani538bd592020-11-04 20:46:08 -0800702 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800703 .Times(0);
704 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700705 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800706 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Amin Hassani538bd592020-11-04 20:46:08 -0800707 EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700708 .WillRepeatedly(Return(url1));
Amin Hassani538bd592020-11-04 20:46:08 -0800709 FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800710 attempter_.ScheduleErrorEventAction();
Amin Hassani538bd592020-11-04 20:46:08 -0800711 EXPECT_EQ(url1,
712 FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800713}
714
715TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
716 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700717 EnqueueAction(Pointee(Property(
718 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700719 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700720 ErrorCode err = ErrorCode::kError;
Amin Hassani538bd592020-11-04 20:46:08 -0800721 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800722 attempter_.error_event_.reset(new OmahaEvent(
723 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800724 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700725 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800726}
727
Darin Petkove6ef2f82011-03-07 17:31:11 -0800728namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700729// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200730vector<string> GetUpdateActionTypes() {
731 return {OmahaRequestAction::StaticType(),
732 OmahaResponseHandlerAction::StaticType(),
733 UpdateBootFlagsAction::StaticType(),
734 OmahaRequestAction::StaticType(),
735 DownloadAction::StaticType(),
736 OmahaRequestAction::StaticType(),
737 FilesystemVerifierAction::StaticType(),
738 PostinstallRunnerAction::StaticType(),
739 OmahaRequestAction::StaticType()};
740}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700741
742// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200743vector<string> GetRollbackActionTypes() {
744 return {InstallPlanAction::StaticType(),
745 PostinstallRunnerAction::StaticType()};
746}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700747
Adolfo Victoria497044c2018-07-18 07:51:42 -0700748const StagingSchedule kValidStagingSchedule = {
749 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
750
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700751} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800752
753void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700754 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700755
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700756 // Expect that the device policy is loaded by the |UpdateAttempter| at some
757 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100758 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700759 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800760 .Times(testing::AtLeast(1))
761 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100762 attempter_.policy_provider_.reset(
763 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700764
765 {
766 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200767 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700768 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700769 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200770 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700771 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700772 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700773 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700774
Amin Hassanie8153632020-10-27 15:11:28 -0700775 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700776 loop_.PostTask(FROM_HERE,
777 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
778 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800779}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700780
Darin Petkove6ef2f82011-03-07 17:31:11 -0800781void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700782 EXPECT_EQ(0, attempter_.http_response_code());
783 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700784 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700785 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800786}
787
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800788void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
789 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700790 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100791 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700792 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -0800793 FakeSystemState::Get()->set_device_policy(device_policy.get());
Igor9fd76b62017-12-11 15:24:18 +0100794 if (enterprise_rollback) {
795 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800796 EXPECT_CALL(*device_policy, GetOwner(_))
797 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100798 } else {
799 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800800 EXPECT_CALL(*device_policy, GetOwner(_))
801 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
802 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100803 }
804
805 attempter_.policy_provider_.reset(
806 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700807
Alex Deymo763e7db2015-08-27 21:08:08 -0700808 if (valid_slot) {
809 BootControlInterface::Slot rollback_slot = 1;
810 LOG(INFO) << "Test Mark Bootable: "
811 << BootControlInterface::SlotName(rollback_slot);
Amin Hassani538bd592020-11-04 20:46:08 -0800812 FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
813 true);
Don Garrett6646b442013-11-13 15:29:11 -0800814 }
815
Chris Sosa28e479c2013-07-12 11:39:53 -0700816 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700817
Chris Sosad38b1132014-03-25 10:43:59 -0700818 // We only allow rollback on devices that are not enterprise enrolled and
819 // which have a valid slot to rollback to.
820 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800821 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700822 }
823
Chris Sosa28e479c2013-07-12 11:39:53 -0700824 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700825 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200826 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700827 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200828 EnqueueAction(Pointee(
829 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700830 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700831 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700832
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700833 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700834 loop_.PostTask(FROM_HERE,
835 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
836 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700837 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700838 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700839 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700840 }
841}
842
843void UpdateAttempterTest::RollbackTestVerify() {
844 // Verifies the actions that were enqueued.
845 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700846 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700847 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
848 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700849 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700850}
851
Darin Petkove6ef2f82011-03-07 17:31:11 -0800852TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700853 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700854 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700855}
856
Chris Sosa76a29ae2013-07-11 17:59:24 -0700857TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700858 loop_.PostTask(FROM_HERE,
859 base::Bind(&UpdateAttempterTest::RollbackTestStart,
860 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800861 false,
862 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700863 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700864}
865
Don Garrett6646b442013-11-13 15:29:11 -0800866TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700867 loop_.PostTask(FROM_HERE,
868 base::Bind(&UpdateAttempterTest::RollbackTestStart,
869 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800870 false,
871 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700872 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800873}
874
Chris Sosa76a29ae2013-07-11 17:59:24 -0700875TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700876 loop_.PostTask(FROM_HERE,
877 base::Bind(&UpdateAttempterTest::RollbackTestStart,
878 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800879 true,
880 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700881 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700882}
883
Thieu Le116fda32011-04-19 11:01:54 -0700884void UpdateAttempterTest::PingOmahaTestStart() {
885 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700886 EnqueueAction(Pointee(Property(
887 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700888 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700889 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700890 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700891}
892
893TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700894 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700895 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700896 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700897 // testing, which is more permissive than we want to handle here.
898 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700899 loop_.PostTask(FROM_HERE,
900 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
901 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700902 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700903 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700904 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700905}
906
Darin Petkov18c7bce2011-06-16 14:07:00 -0700907TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800908 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700909 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700910 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700911 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700912 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
913 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700914 EXPECT_EQ(
915 static_cast<ErrorCode>(static_cast<int>(kCode) |
916 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
917 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700918}
919
920TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700921 attempter_.install_plan_.reset(new InstallPlan);
922 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800923 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700924 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700925 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700926 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700927 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
928 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700929 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800930 static_cast<ErrorCode>(static_cast<int>(kCode) |
931 static_cast<int>(ErrorCode::kResumedFlag) |
932 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700933 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700934}
935
David Zeuthen8f191b22013-08-06 12:27:50 -0700936TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
937 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800938 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700939 mock_p2p_manager.fake().SetP2PEnabled(false);
940 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
941 attempter_.UpdateEngineStarted();
942}
943
944TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
945 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800946 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700947 mock_p2p_manager.fake().SetP2PEnabled(true);
948 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
949 attempter_.UpdateEngineStarted();
950}
951
952TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
953 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800954 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700955 mock_p2p_manager.fake().SetP2PEnabled(true);
956 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700957 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700958 attempter_.UpdateEngineStarted();
959}
960
961TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700962 loop_.PostTask(FROM_HERE,
963 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
964 base::Unretained(this)));
965 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700966}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700967
David Zeuthen8f191b22013-08-06 12:27:50 -0700968void UpdateAttempterTest::P2PNotEnabledStart() {
969 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700970 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700971 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800972 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700973 mock_p2p_manager.fake().SetP2PEnabled(false);
974 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700975 attempter_.Update({});
Alex Deymo60ca1a72015-06-18 18:19:15 -0700976 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700977 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700978 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700979}
980
981TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700982 loop_.PostTask(FROM_HERE,
983 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
984 base::Unretained(this)));
985 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700986}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700987
David Zeuthen8f191b22013-08-06 12:27:50 -0700988void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700989 // If P2P is enabled, but starting it fails ensure we don't do
990 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700991 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -0800992 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700993 mock_p2p_manager.fake().SetP2PEnabled(true);
994 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
995 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
996 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Amin Hassanie8153632020-10-27 15:11:28 -0700997 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -0700998 EXPECT_FALSE(actual_using_p2p_for_downloading());
999 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001000 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001001}
1002
1003TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001004 loop_.PostTask(
1005 FROM_HERE,
1006 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1007 base::Unretained(this)));
1008 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001009}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001010
David Zeuthen8f191b22013-08-06 12:27:50 -07001011void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001012 // If P2P is enabled, starting it works but housekeeping fails, ensure
1013 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001014 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001015 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001016 mock_p2p_manager.fake().SetP2PEnabled(true);
1017 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1018 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001019 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001020 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001021 EXPECT_FALSE(actual_using_p2p_for_downloading());
1022 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001023 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001024}
1025
1026TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001027 loop_.PostTask(FROM_HERE,
1028 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1029 base::Unretained(this)));
1030 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001031}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001032
David Zeuthen8f191b22013-08-06 12:27:50 -07001033void UpdateAttempterTest::P2PEnabledStart() {
1034 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001035 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001036 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001037 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001038 mock_p2p_manager.fake().SetP2PEnabled(true);
1039 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1040 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001041 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001042 attempter_.Update({});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001043 EXPECT_TRUE(actual_using_p2p_for_downloading());
1044 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001045 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001046}
1047
1048TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001049 loop_.PostTask(FROM_HERE,
1050 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1051 base::Unretained(this)));
1052 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001053}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001054
David Zeuthen8f191b22013-08-06 12:27:50 -07001055void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1056 MockP2PManager mock_p2p_manager;
Amin Hassani538bd592020-11-04 20:46:08 -08001057 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001058 // For an interactive check, if P2P is enabled and starting it
1059 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001060 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001061 mock_p2p_manager.fake().SetP2PEnabled(true);
1062 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1063 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001064 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Amin Hassanie8153632020-10-27 15:11:28 -07001065 attempter_.Update({.interactive = true});
Gilad Arnold74b5f552014-10-07 08:17:16 -07001066 EXPECT_FALSE(actual_using_p2p_for_downloading());
1067 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001068 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001069}
1070
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001071TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001072 loop_.PostTask(
1073 FROM_HERE,
1074 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1075 base::Unretained(this)));
1076 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001077}
1078
1079// Tests that the scatter_factor_in_seconds value is properly fetched
1080// from the device policy.
1081void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001082 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001083
Igor9fd76b62017-12-11 15:24:18 +01001084 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001085 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001086 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001087
1088 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001089 .WillRepeatedly(
1090 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001091
Igor9fd76b62017-12-11 15:24:18 +01001092 attempter_.policy_provider_.reset(
1093 new policy::PolicyProvider(std::move(device_policy)));
1094
Amin Hassanie8153632020-10-27 15:11:28 -07001095 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001096 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1097
Alex Deymo60ca1a72015-06-18 18:19:15 -07001098 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001099}
1100
1101TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001102 loop_.PostTask(
1103 FROM_HERE,
1104 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1105 base::Unretained(this)));
1106 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001107}
1108
1109void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1110 // Tests that the scatter_factor_in_seconds value is properly fetched
1111 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001112 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001113 FakePrefs fake_prefs;
1114 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001115
Amin Hassani538bd592020-11-04 20:46:08 -08001116 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001117
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001118 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001119
Ben Chan9abb7632014-08-07 00:10:53 -07001120 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001121
Igor9fd76b62017-12-11 15:24:18 +01001122 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001123 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001124 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001125
1126 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001127 .WillRepeatedly(
1128 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001129
Igor9fd76b62017-12-11 15:24:18 +01001130 attempter_.policy_provider_.reset(
1131 new policy::PolicyProvider(std::move(device_policy)));
1132
Amin Hassanie8153632020-10-27 15:11:28 -07001133 attempter_.Update({});
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001134 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1135
1136 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001137 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001138
Ben Chan9abb7632014-08-07 00:10:53 -07001139 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001140 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001141 EXPECT_EQ(initial_value - 1, new_value);
1142
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001143 EXPECT_TRUE(
1144 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001145
1146 // However, if the count is already 0, it's not decremented. Test that.
1147 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001148 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Amin Hassanie8153632020-10-27 15:11:28 -07001149 attempter_.Update({});
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001150 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1151 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001152 EXPECT_EQ(initial_value, new_value);
1153
Alex Deymo60ca1a72015-06-18 18:19:15 -07001154 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001155}
1156
Jay Srinivasan08fce042012-06-07 16:31:01 -07001157TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001158 loop_.PostTask(
1159 FROM_HERE,
1160 base::Bind(
1161 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1162 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001163 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001164}
1165
1166void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1167 // Tests that no scattering logic is enabled if the update check
1168 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001169 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001170 FakePrefs fake_prefs;
1171 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001172
Amin Hassani538bd592020-11-04 20:46:08 -08001173 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1174 FakeSystemState::Get()->set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001175
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001176 EXPECT_TRUE(
1177 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001178 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001179
1180 // make sure scatter_factor is non-zero as scattering is disabled
1181 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001182 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001183
Igor9fd76b62017-12-11 15:24:18 +01001184 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001185 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001186 FakeSystemState::Get()->set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001187
1188 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001189 .WillRepeatedly(
1190 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001191
Igor9fd76b62017-12-11 15:24:18 +01001192 attempter_.policy_provider_.reset(
1193 new policy::PolicyProvider(std::move(device_policy)));
1194
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001195 // Trigger an interactive check so we can test that scattering is disabled.
Amin Hassanie8153632020-10-27 15:11:28 -07001196 attempter_.Update({.interactive = true});
Jay Srinivasan08fce042012-06-07 16:31:01 -07001197 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1198
1199 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001200 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001201 EXPECT_FALSE(
1202 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001203 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001204 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1205 EXPECT_FALSE(
1206 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001207 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001208
Alex Deymo60ca1a72015-06-18 18:19:15 -07001209 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001210}
1211
Adolfo Victoria497044c2018-07-18 07:51:42 -07001212void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1213 FakePrefs* prefs) {
1214 attempter_.prefs_ = prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001215 FakeSystemState::Get()->set_prefs(prefs);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001216
1217 int64_t initial_value = 8;
1218 EXPECT_TRUE(
1219 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1220 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1221 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1222
1223 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1224 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amin Hassani538bd592020-11-04 20:46:08 -08001225 FakeSystemState::Get()->set_device_policy(device_policy.get());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001226 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1227 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1228
1229 attempter_.policy_provider_.reset(
1230 new policy::PolicyProvider(std::move(device_policy)));
1231}
1232
1233TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1234 loop_.PostTask(
1235 FROM_HERE,
1236 base::Bind(
1237 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1238 base::Unretained(this)));
1239 loop_.Run();
1240}
1241
1242void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1243 // Tests that staging sets its prefs properly and turns off scattering.
Amin Hassani538bd592020-11-04 20:46:08 -08001244 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001245 FakePrefs fake_prefs;
1246 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1247
Amin Hassanie8153632020-10-27 15:11:28 -07001248 attempter_.Update({});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001249 // Check that prefs have the correct values.
1250 int64_t update_count;
1251 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1252 int64_t waiting_time_days;
1253 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1254 &waiting_time_days));
1255 EXPECT_GT(waiting_time_days, 0);
1256 // Update count should have been decremented.
1257 EXPECT_EQ(7, update_count);
1258 // Check that Omaha parameters were updated correctly.
1259 EXPECT_TRUE(
1260 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1261 EXPECT_TRUE(
1262 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1263 EXPECT_EQ(waiting_time_days,
1264 attempter_.omaha_request_params_->waiting_period().InDays());
1265 // Check class variables.
1266 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1267 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1268 // Check that scattering is turned off
1269 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1270 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1271
1272 ScheduleQuitMainLoop();
1273}
1274
1275void UpdateAttempterTest::CheckStagingOff() {
1276 // Check that all prefs were removed.
1277 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1278 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1279 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1280 // Check that the Omaha parameters have the correct value.
1281 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1282 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1283 attempter_.staging_wait_time_);
1284 EXPECT_FALSE(
1285 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1286 EXPECT_FALSE(
1287 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1288 // Check that scattering is turned off too.
1289 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1290}
1291
1292TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1293 loop_.PostTask(FROM_HERE,
1294 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1295 base::Unretained(this)));
1296 loop_.Run();
1297}
1298
1299void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1300 // Tests that staging is turned off when an interactive update is requested.
Amin Hassani538bd592020-11-04 20:46:08 -08001301 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Adolfo Victoria497044c2018-07-18 07:51:42 -07001302 FakePrefs fake_prefs;
1303 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1304
Amin Hassanie8153632020-10-27 15:11:28 -07001305 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001306 CheckStagingOff();
1307
1308 ScheduleQuitMainLoop();
1309}
1310
1311TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1312 loop_.PostTask(FROM_HERE,
1313 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1314 base::Unretained(this)));
1315 loop_.Run();
1316}
1317
1318void UpdateAttempterTest::StagingOffIfOobeStart() {
1319 // Tests that staging is turned off if OOBE hasn't been completed.
Amin Hassani538bd592020-11-04 20:46:08 -08001320 FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
1321 FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
Adolfo Victoria497044c2018-07-18 07:51:42 -07001322 FakePrefs fake_prefs;
1323 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1324
Amin Hassanie8153632020-10-27 15:11:28 -07001325 attempter_.Update({.interactive = true});
Adolfo Victoria497044c2018-07-18 07:51:42 -07001326 CheckStagingOff();
1327
1328 ScheduleQuitMainLoop();
1329}
1330
David Zeuthen985b1122013-10-09 12:13:15 -07001331// Checks that we only report daily metrics at most every 24 hours.
1332TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1333 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001334 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001335
Amin Hassani538bd592020-11-04 20:46:08 -08001336 FakeSystemState::Get()->set_clock(&fake_clock);
1337 FakeSystemState::Get()->set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001338
1339 Time epoch = Time::FromInternalValue(0);
1340 fake_clock.SetWallclockTime(epoch);
1341
1342 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1343 // we should report.
1344 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1345 // We should not report again if no time has passed.
1346 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1347
1348 // We should not report if only 10 hours has passed.
1349 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1350 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1351
1352 // We should not report if only 24 hours - 1 sec has passed.
1353 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1354 TimeDelta::FromSeconds(1));
1355 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1356
1357 // We should report if 24 hours has passed.
1358 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1359 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1360
1361 // But then we should not report again..
1362 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1363
1364 // .. until another 24 hours has passed
1365 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1366 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1367 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1368 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1369 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1370
1371 // .. and another 24 hours
1372 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1373 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1374 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1375 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1376 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1377
1378 // If the span between time of reporting and present time is
1379 // negative, we report. This is in order to reset the timestamp and
1380 // avoid an edge condition whereby a distant point in the future is
1381 // in the state variable resulting in us never ever reporting again.
1382 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1383 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1384 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1385
1386 // In this case we should not update until the clock reads 71 + 24 = 95.
1387 // Check that.
1388 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1389 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1390 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1391 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1392 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001393}
1394
David Zeuthen3c55abd2013-10-14 12:48:03 -07001395TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001396 FakeClock fake_clock;
1397 fake_clock.SetBootTime(Time::FromTimeT(42));
Amin Hassani538bd592020-11-04 20:46:08 -08001398 FakeSystemState::Get()->set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001399 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08001400 FakeSystemState::Get()->set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001401 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001402
1403 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001404 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001405
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001406 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001407
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001408 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001409 EXPECT_EQ(boot_time.ToTimeT(), 42);
1410}
1411
David Pursell02c18642014-11-06 11:26:11 -08001412TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
Amin Hassani538bd592020-11-04 20:46:08 -08001413 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
David Pursell02c18642014-11-06 11:26:11 -08001414 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1415}
1416
1417TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
Amin Hassani538bd592020-11-04 20:46:08 -08001418 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1419 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001420 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1421}
1422
1423TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
Amin Hassani538bd592020-11-04 20:46:08 -08001424 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1425 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001426 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1427}
1428
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001429// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1430// When adding, remove older tests related to |CheckForInstall()|.
1431TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1432 for (const auto status : kNonIdleUpdateStatuses) {
1433 // GIVEN a non-idle status.
1434 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001435
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001436 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1437 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001438}
1439
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001440TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1441 for (const auto status : kNonIdleUpdateStatuses) {
1442 // GIVEN a non-idle status.
1443 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001444
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001445 // THEN |ScheduleUpdates()| should not be called.
1446 cfu_params_.should_schedule_updates_be_called = false;
1447 // THEN result should indicate failure.
1448 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001449
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001450 TestCheckForUpdate();
1451 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001452}
1453
1454TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1455 // GIVEN a official build.
1456
1457 // THEN we except forced app version + forced omaha url to be cleared.
1458
1459 TestCheckForUpdate();
1460}
1461
1462TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001463 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001464 cfu_params_.is_official_build = false;
1465 cfu_params_.are_dev_features_enabled = true;
1466
1467 // THEN the forced app version + forced omaha url changes based on input.
1468 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1469 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1470
1471 TestCheckForUpdate();
1472}
1473
1474TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1475 // GIVEN a scheduled autest omaha url.
1476 cfu_params_.omaha_url = "autest-scheduled";
1477
1478 // THEN forced app version is cleared.
1479 // THEN forced omaha url changes to default constant.
1480 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1481
1482 TestCheckForUpdate();
1483}
1484
1485TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1486 // GIVEN a scheduled autest omaha url.
1487 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001488 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001489 cfu_params_.is_official_build = false;
1490 cfu_params_.are_dev_features_enabled = true;
1491
1492 // THEN forced app version changes based on input.
1493 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1494 // THEN forced omaha url changes to default constant.
1495 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1496
1497 TestCheckForUpdate();
1498}
1499
1500TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1501 // GIVEN a autest omaha url.
1502 cfu_params_.omaha_url = "autest";
1503
1504 // THEN forced app version is cleared.
1505 // THEN forced omaha url changes to default constant.
1506 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1507
1508 TestCheckForUpdate();
1509}
1510
1511TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1512 // GIVEN a autest omha url.
1513 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001514 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001515 cfu_params_.is_official_build = false;
1516 cfu_params_.are_dev_features_enabled = true;
1517
1518 // THEN forced app version changes based on input.
1519 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1520 // THEN forced omaha url changes to default constant.
1521 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1522
1523 TestCheckForUpdate();
1524}
1525
1526TEST_F(UpdateAttempterTest,
1527 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1528 // GIVEN a scheduled autest omaha url.
1529 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001530 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001531 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1532
1533 // THEN forced app version is cleared.
1534 // THEN forced omaha url changes to default constant.
1535 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1536
1537 TestCheckForUpdate();
1538}
1539
1540TEST_F(UpdateAttempterTest,
1541 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1542 // GIVEN a scheduled autest omaha url.
1543 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001544 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001545 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001546 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001547 cfu_params_.is_official_build = false;
1548 cfu_params_.are_dev_features_enabled = true;
1549
1550 // THEN forced app version changes based on input.
1551 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1552 // THEN forced omaha url changes to default constant.
1553 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1554
1555 TestCheckForUpdate();
1556}
1557
1558TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1559 // GIVEN a autest omaha url.
1560 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001561 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001562 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1563
1564 // THEN forced app version is cleared.
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, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1572 // GIVEN a autest omaha url.
1573 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001574 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001575 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001576 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001577 cfu_params_.is_official_build = false;
1578 cfu_params_.are_dev_features_enabled = true;
1579
1580 // THEN forced app version changes based on input.
1581 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1582 // THEN forced omaha url changes to default constant.
1583 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1584
1585 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001586}
1587
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001588TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1589 // GIVEN a official build.
1590 // GIVEN forced callback is not set.
1591 attempter_.set_forced_update_pending_callback(nullptr);
1592
1593 // THEN we except forced app version + forced omaha url to be cleared.
1594 // THEN |ScheduleUpdates()| should not be called.
1595 cfu_params_.should_schedule_updates_be_called = false;
1596
1597 TestCheckForUpdate();
1598}
1599
1600TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001601 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001602 cfu_params_.is_official_build = false;
1603 cfu_params_.are_dev_features_enabled = true;
1604 // GIVEN forced callback is not set.
1605 attempter_.set_forced_update_pending_callback(nullptr);
1606
1607 // THEN the forced app version + forced omaha url changes based on input.
1608 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1609 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1610 // THEN |ScheduleUpdates()| should not be called.
1611 cfu_params_.should_schedule_updates_be_called = false;
1612
1613 TestCheckForUpdate();
1614}
1615
Xiaochu Liu88d90382018-08-29 16:09:11 -07001616TEST_F(UpdateAttempterTest, CheckForInstallTest) {
Amin Hassani538bd592020-11-04 20:46:08 -08001617 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1618 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
Xiaochu Liu88d90382018-08-29 16:09:11 -07001619 attempter_.CheckForInstall({}, "autest");
1620 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1621
1622 attempter_.CheckForInstall({}, "autest-scheduled");
1623 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1624
1625 attempter_.CheckForInstall({}, "http://omaha.phishing");
1626 EXPECT_EQ("", attempter_.forced_omaha_url());
1627}
1628
Colin Howesac170d92018-11-20 16:29:28 -08001629TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1630 attempter_.CheckForInstall({}, "http://foo.bar");
1631 attempter_.status_ = UpdateStatus::DOWNLOADING;
1632 EXPECT_TRUE(attempter_.is_install_);
1633 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1634 UpdateEngineStatus status;
1635 attempter_.GetStatus(&status);
1636 // Should set status to idle after an install operation.
1637 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1638}
1639
Colin Howes978c1082018-12-03 11:46:12 -08001640TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1641 attempter_.is_install_ = true;
1642 attempter_.Rollback(false);
1643 EXPECT_FALSE(attempter_.is_install_);
1644}
1645
1646TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1647 attempter_.is_install_ = true;
1648 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1649 EXPECT_FALSE(attempter_.is_install_);
1650}
1651
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001652TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001653 UpdateCheckParams params;
1654 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001655 EXPECT_EQ("1234",
Amin Hassani538bd592020-11-04 20:46:08 -08001656 FakeSystemState::Get()->request_params()->target_version_prefix());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001657
Amin Hassanie8153632020-10-27 15:11:28 -07001658 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001659 EXPECT_TRUE(FakeSystemState::Get()
1660 ->request_params()
1661 ->target_version_prefix()
1662 .empty());
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001663}
1664
Amin Hassani37b67232020-08-13 09:29:48 -07001665TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001666 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
Amin Hassani538bd592020-11-04 20:46:08 -08001667 EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
Amin Hassani37b67232020-08-13 09:29:48 -07001668
Amin Hassanie8153632020-10-27 15:11:28 -07001669 attempter_.CalculateUpdateParams({});
Amin Hassani538bd592020-11-04 20:46:08 -08001670 EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
Amin Hassani37b67232020-08-13 09:29:48 -07001671}
1672
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001673TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
Amin Hassanie8153632020-10-27 15:11:28 -07001674 attempter_.CalculateUpdateParams({
1675 .target_version_prefix = "1234",
1676 .rollback_allowed = true,
1677 .rollback_allowed_milestones = 4,
1678 });
Amin Hassani538bd592020-11-04 20:46:08 -08001679 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1680 EXPECT_EQ(
1681 4,
1682 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001683
Amin Hassanie8153632020-10-27 15:11:28 -07001684 attempter_.CalculateUpdateParams({
1685 .target_version_prefix = "1234",
1686 .rollback_allowed_milestones = 4,
1687 });
Amin Hassani538bd592020-11-04 20:46:08 -08001688 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1689 EXPECT_EQ(
1690 4,
1691 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001692}
1693
Miriam Polzeraff72002020-08-27 08:20:39 +02001694TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1695 base::ScopedTempDir tempdir;
1696 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001697 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001698 attempter_.CalculateUpdateParams({
1699 .target_channel = "stable-channel",
1700 });
Amin Hassani538bd592020-11-04 20:46:08 -08001701 EXPECT_FALSE(
1702 FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001703}
1704
1705TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1706 base::ScopedTempDir tempdir;
1707 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
Amin Hassani538bd592020-11-04 20:46:08 -08001708 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
Amin Hassanie8153632020-10-27 15:11:28 -07001709 attempter_.CalculateUpdateParams({
1710 .rollback_on_channel_downgrade = true,
1711 .target_channel = "stable-channel",
1712 });
Amin Hassani538bd592020-11-04 20:46:08 -08001713 EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
Miriam Polzeraff72002020-08-27 08:20:39 +02001714}
1715
Aaron Wood23bd3392017-10-06 14:48:25 -07001716TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1717 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1718 // but the update is being deferred by the Policy.
Amin Hassani538bd592020-11-04 20:46:08 -08001719 OmahaResponseHandlerAction response_action;
Amin Hassani68512d42018-07-31 23:52:33 -07001720 response_action.install_plan_.version = "a.b.c.d";
Amin Hassani68512d42018-07-31 23:52:33 -07001721 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001722 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001723 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1724 // completed, with the deferred-update error code.
1725 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001726 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001727 {
1728 UpdateEngineStatus status;
1729 attempter_.GetStatus(&status);
1730 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001731 EXPECT_TRUE(attempter_.install_plan_);
1732 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001733 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001734 status.new_size_bytes);
1735 }
1736 // An "error" event should have been created to tell Omaha that the update is
1737 // being deferred.
1738 EXPECT_TRUE(nullptr != attempter_.error_event_);
1739 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1740 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1741 ErrorCode expected_code = static_cast<ErrorCode>(
1742 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1743 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1744 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1745 // End the processing
1746 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1747 // Validate the state of the attempter.
1748 {
1749 UpdateEngineStatus status;
1750 attempter_.GetStatus(&status);
1751 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001752 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001753 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001754 status.new_size_bytes);
1755 }
1756}
1757
1758TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001759 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001760 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001761 // Verify in-progress update with UPDATE_AVAILABLE is running
1762 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001763 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001764}
1765
Aaron Woodbf5a2522017-10-04 10:58:36 -07001766TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1767 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1768
1769 UpdateCheckParams params = {.updates_enabled = true};
1770 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1771
1772 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1773 attempter_.GetCurrentUpdateAttemptFlags());
1774}
1775
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001776TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1777 UpdateCheckParams params = {.updates_enabled = true,
1778 .rollback_allowed = false};
1779 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001780 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001781}
1782
1783TEST_F(UpdateAttempterTest, RollbackAllowed) {
1784 UpdateCheckParams params = {.updates_enabled = true,
1785 .rollback_allowed = true};
1786 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
Amin Hassani538bd592020-11-04 20:46:08 -08001787 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001788}
1789
Aaron Wood081c0232017-10-19 17:14:58 -07001790TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1791 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1792
1793 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1794 EXPECT_EQ(UpdateAttemptFlags::kNone,
1795 attempter_.GetCurrentUpdateAttemptFlags());
1796}
1797
1798TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1799 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1800
1801 // This tests that when CheckForUpdate() is called with the non-interactive
1802 // flag set, that it doesn't change the current UpdateAttemptFlags.
1803 attempter_.CheckForUpdate("",
1804 "",
1805 UpdateAttemptFlags::kFlagNonInteractive |
1806 UpdateAttemptFlags::kFlagRestrictDownload);
1807 EXPECT_EQ(UpdateAttemptFlags::kNone,
1808 attempter_.GetCurrentUpdateAttemptFlags());
1809}
1810
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001811void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1812 bool is_policy_loaded,
1813 bool expected_reset) {
Amin Hassani538bd592020-11-04 20:46:08 -08001814 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1815 GetRollbackHappened())
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001816 .WillRepeatedly(Return(true));
1817 auto mock_policy_provider =
1818 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1819 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1820 .WillRepeatedly(Return(is_consumer));
1821 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1822 .WillRepeatedly(Return(is_policy_loaded));
1823 const policy::MockDevicePolicy device_policy;
1824 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1825 .WillRepeatedly(ReturnRef(device_policy));
Amin Hassani538bd592020-11-04 20:46:08 -08001826 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001827 SetRollbackHappened(false))
1828 .Times(expected_reset ? 1 : 0);
1829 attempter_.policy_provider_ = std::move(mock_policy_provider);
Amin Hassanie8153632020-10-27 15:11:28 -07001830 attempter_.Update({});
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001831 ScheduleQuitMainLoop();
1832}
1833
1834TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1835 loop_.PostTask(FROM_HERE,
1836 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1837 base::Unretained(this),
1838 /*is_consumer=*/false,
1839 /*is_policy_loaded=*/false,
1840 /*expected_reset=*/false));
1841 loop_.Run();
1842}
1843
1844TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1845 loop_.PostTask(FROM_HERE,
1846 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1847 base::Unretained(this),
1848 /*is_consumer=*/true,
1849 /*is_policy_loaded=*/false,
1850 /*expected_reset=*/true));
1851 loop_.Run();
1852}
1853
1854TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1855 loop_.PostTask(FROM_HERE,
1856 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1857 base::Unretained(this),
1858 /*is_consumer=*/false,
1859 /*is_policy_loaded=*/true,
1860 /*expected_reset=*/true));
1861 loop_.Run();
1862}
1863
Marton Hunyady199152d2018-05-07 19:08:48 +02001864TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001865 attempter_.install_plan_.reset(new InstallPlan);
1866 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001867
Amin Hassani538bd592020-11-04 20:46:08 -08001868 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001869 SetRollbackHappened(true))
1870 .Times(1);
1871 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1872}
1873
1874TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001875 attempter_.install_plan_.reset(new InstallPlan);
1876 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001877
Amin Hassani538bd592020-11-04 20:46:08 -08001878 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
Marton Hunyady199152d2018-05-07 19:08:48 +02001879 SetRollbackHappened(true))
1880 .Times(0);
1881 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1882}
1883
Marton Hunyadya0302682018-05-16 18:52:13 +02001884TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001885 attempter_.install_plan_.reset(new InstallPlan);
1886 attempter_.install_plan_->is_rollback = true;
1887 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001888
Amin Hassani538bd592020-11-04 20:46:08 -08001889 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001890 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1891 .Times(1);
1892 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1893}
1894
1895TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001896 attempter_.install_plan_.reset(new InstallPlan);
1897 attempter_.install_plan_->is_rollback = false;
1898 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001899
Amin Hassani538bd592020-11-04 20:46:08 -08001900 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001901 ReportEnterpriseRollbackMetrics(_, _))
1902 .Times(0);
1903 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1904}
1905
1906TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001907 attempter_.install_plan_.reset(new InstallPlan);
1908 attempter_.install_plan_->is_rollback = true;
1909 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001910
Amin Hassani538bd592020-11-04 20:46:08 -08001911 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001912 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1913 .Times(1);
1914 MockAction action;
1915 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1916 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1917}
1918
1919TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001920 attempter_.install_plan_.reset(new InstallPlan);
1921 attempter_.install_plan_->is_rollback = false;
1922 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001923
Amin Hassani538bd592020-11-04 20:46:08 -08001924 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
Marton Hunyadya0302682018-05-16 18:52:13 +02001925 ReportEnterpriseRollbackMetrics(_, _))
1926 .Times(0);
1927 MockAction action;
1928 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1929 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1930}
1931
May Lippert60aa3ca2018-08-15 16:55:29 -07001932TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
Amin Hassani538bd592020-11-04 20:46:08 -08001933 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001934 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1935 .Times(0);
1936 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1937}
1938
1939TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1940 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001941 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001942 // Make device policy return that this is not enterprise enrolled
1943 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1944
1945 // Ensure that the metric is not recorded.
Amin Hassani538bd592020-11-04 20:46:08 -08001946 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001947 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1948 .Times(0);
1949 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1950}
1951
1952TEST_F(UpdateAttempterTest,
1953 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1954 constexpr int kDaysToUpdate = 15;
1955 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001956 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001957 // Make device policy return that this is enterprise enrolled
1958 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1959 // Pretend that there's a time restriction policy in place
1960 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1961 .WillOnce(Return(true));
1962
1963 FakePrefs fake_prefs;
1964 Time update_first_seen_at = Time::Now();
1965 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1966 update_first_seen_at.ToInternalValue());
1967
1968 FakeClock fake_clock;
1969 Time update_finished_at =
1970 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1971 fake_clock.SetWallclockTime(update_finished_at);
1972
Amin Hassani538bd592020-11-04 20:46:08 -08001973 FakeSystemState::Get()->set_clock(&fake_clock);
1974 FakeSystemState::Get()->set_prefs(&fake_prefs);
May Lippert60aa3ca2018-08-15 16:55:29 -07001975
Amin Hassani538bd592020-11-04 20:46:08 -08001976 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07001977 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1978 .Times(1);
1979 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1980}
1981
1982TEST_F(UpdateAttempterTest,
1983 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1984 constexpr int kDaysToUpdate = 15;
1985 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Amin Hassani538bd592020-11-04 20:46:08 -08001986 FakeSystemState::Get()->set_device_policy(device_policy.get());
May Lippert60aa3ca2018-08-15 16:55:29 -07001987 // Make device policy return that this is enterprise enrolled
1988 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1989 // Pretend that there's no time restriction policy in place
1990 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1991 .WillOnce(Return(false));
1992
1993 FakePrefs fake_prefs;
1994 Time update_first_seen_at = Time::Now();
1995 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1996 update_first_seen_at.ToInternalValue());
1997
1998 FakeClock fake_clock;
1999 Time update_finished_at =
2000 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2001 fake_clock.SetWallclockTime(update_finished_at);
2002
Amin Hassani538bd592020-11-04 20:46:08 -08002003 FakeSystemState::Get()->set_clock(&fake_clock);
2004 FakeSystemState::Get()->set_prefs(&fake_prefs);
May Lippert60aa3ca2018-08-15 16:55:29 -07002005
Amin Hassani538bd592020-11-04 20:46:08 -08002006 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
May Lippert60aa3ca2018-08-15 16:55:29 -07002007 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2008 .Times(1);
2009 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2010}
2011
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002012TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2013 // GIVEN an update finished.
2014
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002015 // THEN update_engine should call update completion.
2016 pd_params_.should_update_completed_be_called = true;
2017 // THEN need reboot since update applied.
2018 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2019 // THEN install indication should be false.
2020
2021 TestProcessingDone();
2022}
2023
2024TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2025 // GIVEN an update finished.
2026 // GIVEN DLC |AppParams| list.
2027 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2028 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2029 {dlc_2, {.name = dlc_2}}};
2030
2031 // THEN update_engine should call update completion.
2032 pd_params_.should_update_completed_be_called = true;
2033 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002034 // THEN need reboot since update applied.
2035 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2036 // THEN install indication should be false.
2037
2038 TestProcessingDone();
2039}
2040
2041TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2042 // GIVEN an install finished.
2043 pd_params_.is_install = true;
2044
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002045 // THEN update_engine should call install completion.
2046 pd_params_.should_install_completed_be_called = true;
2047 // THEN go idle.
2048 // THEN install indication should be false.
2049
2050 TestProcessingDone();
2051}
2052
2053TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2054 // GIVEN an install finished.
2055 pd_params_.is_install = true;
2056 // GIVEN DLC |AppParams| list.
2057 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2058 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2059 {dlc_2, {.name = dlc_2}}};
2060
2061 // THEN update_engine should call install completion.
2062 pd_params_.should_install_completed_be_called = true;
2063 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002064 // THEN go idle.
2065 // THEN install indication should be false.
2066
2067 TestProcessingDone();
2068}
2069
2070TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2071 // GIVEN an install finished.
2072 pd_params_.is_install = true;
2073 // GIVEN a reporting error occurred.
2074 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2075
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002076 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002077 // THEN go idle.
2078 // THEN install indication should be false.
2079
2080 TestProcessingDone();
2081}
2082
2083TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2084 // GIVEN an update finished.
2085 // GIVEN an action error occured.
2086 pd_params_.code = ErrorCode::kNoUpdate;
2087
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002088 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002089 // THEN go idle.
2090 // THEN install indication should be false.
2091
2092 TestProcessingDone();
2093}
2094
2095TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2096 // GIVEN an install finished.
2097 pd_params_.is_install = true;
2098 // GIVEN an action error occured.
2099 pd_params_.code = ErrorCode::kNoUpdate;
2100
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002101 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002102 // THEN go idle.
2103 // THEN install indication should be false.
2104
2105 TestProcessingDone();
2106}
2107
2108TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2109 // GIVEN an update finished.
2110 // GIVEN an action error occured.
2111 pd_params_.code = ErrorCode::kError;
2112 // GIVEN an event error is set.
2113 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2114 OmahaEvent::kResultError,
2115 ErrorCode::kError));
2116
2117 // THEN indicate a error event.
2118 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2119 // THEN install indication should be false.
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 expect critical actions of |ScheduleErrorEventAction()|.
2123 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2124 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2125 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2126 pd_params_.should_schedule_updates_be_called = false;
2127
2128 TestProcessingDone();
2129}
2130
2131TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2132 // GIVEN an install finished.
2133 pd_params_.is_install = true;
2134 // GIVEN an action error occured.
2135 pd_params_.code = ErrorCode::kError;
2136 // GIVEN an event error is set.
2137 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2138 OmahaEvent::kResultError,
2139 ErrorCode::kError));
2140
2141 // THEN indicate a error event.
2142 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2143 // THEN install indication should be false.
2144
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002145 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002146 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2147 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2148 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2149 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2150 pd_params_.should_schedule_updates_be_called = false;
2151
2152 TestProcessingDone();
2153}
2154
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002155TEST_F(UpdateAttempterTest, QuickFixTokenWhenDeviceIsEnterpriseEnrolled) {
2156 attempter_.CalculateUpdateParams({.quick_fix_build_token = "token"});
2157 EXPECT_EQ("token",
2158 FakeSystemState::Get()->request_params()->autoupdate_token());
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002159
Saurabh Nijhara43d7adc2020-11-06 16:13:02 +01002160 attempter_.CalculateUpdateParams({});
2161 EXPECT_TRUE(
2162 FakeSystemState::Get()->request_params()->autoupdate_token().empty());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002163}
2164
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002165TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2166 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2167 .Times(1);
2168 EXPECT_TRUE(attempter_.ScheduleUpdates());
2169 // Now there is an update scheduled which means that all subsequent
2170 // |ScheduleUpdates()| should fail.
2171 EXPECT_FALSE(attempter_.ScheduleUpdates());
2172 EXPECT_FALSE(attempter_.ScheduleUpdates());
2173 EXPECT_FALSE(attempter_.ScheduleUpdates());
2174}
2175
2176// Critical tests to always make sure that an update is scheduled. The following
2177// unittest(s) try and cover the correctness in synergy between
2178// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2179// actions that happen in the flow when |UpdateAttempter| get callbacked on
2180// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2181void UpdateAttempterTest::TestOnUpdateScheduled() {
2182 // Setup
2183 attempter_.SetWaitingForScheduledCheck(true);
2184 attempter_.DisableUpdate();
2185 attempter_.DisableScheduleUpdates();
2186
2187 // Invocation
2188 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2189
2190 // Verify
2191 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2192 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2193 attempter_.WasScheduleUpdatesCalled());
2194 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2195}
2196
2197TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2198 // GIVEN failed status.
2199
2200 // THEN update should be scheduled.
2201 ous_params_.should_schedule_updates_be_called = true;
2202
2203 TestOnUpdateScheduled();
2204}
2205
2206TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2207 // GIVEN ask me again later status.
2208 ous_params_.status = EvalStatus::kAskMeAgainLater;
2209
2210 // THEN update should be scheduled.
2211 ous_params_.should_schedule_updates_be_called = true;
2212
2213 TestOnUpdateScheduled();
2214}
2215
2216TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2217 // GIVEN continue status.
2218 ous_params_.status = EvalStatus::kContinue;
2219
2220 // THEN update should be scheduled.
2221 ous_params_.should_schedule_updates_be_called = true;
2222
2223 TestOnUpdateScheduled();
2224}
2225
2226TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2227 // GIVEN updates disabled.
2228 ous_params_.params = {.updates_enabled = false};
2229 // GIVEN succeeded status.
2230 ous_params_.status = EvalStatus::kSucceeded;
2231
2232 // THEN update should not be scheduled.
2233
2234 TestOnUpdateScheduled();
2235}
2236
2237TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2238 // GIVEN updates enabled.
2239 ous_params_.params = {.updates_enabled = true};
2240 // GIVEN succeeded status.
2241 ous_params_.status = EvalStatus::kSucceeded;
2242
2243 // THEN update should be called indicating status change.
2244 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2245 ous_params_.should_update_be_called = true;
2246
2247 TestOnUpdateScheduled();
2248}
2249
Amin Hassani9be122e2019-08-29 09:20:12 -07002250TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2251 UpdateEngineStatus status;
2252 attempter_.GetStatus(&status);
2253 EXPECT_FALSE(status.is_enterprise_rollback);
2254}
2255
2256TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2257 attempter_.install_plan_.reset(new InstallPlan);
2258 attempter_.install_plan_->is_rollback = false;
2259
2260 UpdateEngineStatus status;
2261 attempter_.GetStatus(&status);
2262 EXPECT_FALSE(status.is_enterprise_rollback);
2263}
2264
2265TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2266 attempter_.install_plan_.reset(new InstallPlan);
2267 attempter_.install_plan_->is_rollback = true;
2268
2269 UpdateEngineStatus status;
2270 attempter_.GetStatus(&status);
2271 EXPECT_TRUE(status.is_enterprise_rollback);
2272}
2273
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002274TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2275 UpdateEngineStatus status;
2276 attempter_.GetStatus(&status);
2277 EXPECT_FALSE(status.will_powerwash_after_reboot);
2278}
2279
2280TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2281 attempter_.install_plan_.reset(new InstallPlan);
2282 attempter_.install_plan_->powerwash_required = true;
2283
2284 UpdateEngineStatus status;
2285 attempter_.GetStatus(&status);
2286 EXPECT_TRUE(status.will_powerwash_after_reboot);
2287}
2288
2289TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2290 attempter_.install_plan_.reset(new InstallPlan);
2291 attempter_.install_plan_->is_rollback = true;
2292
2293 UpdateEngineStatus status;
2294 attempter_.GetStatus(&status);
2295 EXPECT_TRUE(status.will_powerwash_after_reboot);
2296}
2297
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002298TEST_F(UpdateAttempterTest, FutureEolTest) {
2299 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002300 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002301 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2302 .WillOnce(
2303 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2304
2305 UpdateEngineStatus status;
2306 attempter_.GetStatus(&status);
2307 EXPECT_EQ(eol_date, status.eol_date);
2308}
2309
2310TEST_F(UpdateAttempterTest, PastEolTest) {
2311 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002312 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002313 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2314 .WillOnce(
2315 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2316
2317 UpdateEngineStatus status;
2318 attempter_.GetStatus(&status);
2319 EXPECT_EQ(eol_date, status.eol_date);
2320}
2321
2322TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002323 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002324 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2325 .WillOnce(Return(false));
2326
2327 UpdateEngineStatus status;
2328 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002329 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2330}
2331
2332TEST_F(UpdateAttempterTest, MissingEolTest) {
2333 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2334
2335 UpdateEngineStatus status;
2336 attempter_.GetStatus(&status);
2337 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002338}
2339
Andrewe045aef2020-01-08 16:29:22 -08002340TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002341 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002342 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002343 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002344 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002345 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002346 attempter_.CalculateDlcParams();
2347
Amin Hassani538bd592020-11-04 20:46:08 -08002348 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002349 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2350 OmahaRequestParams::AppParams dlc_app_params =
2351 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2352 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2353 EXPECT_EQ(false, dlc_app_params.send_ping);
2354 // When the DLC gets installed, a ping is not sent, therefore we don't store
2355 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002356 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002357 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002358 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
Andrew065d78d2020-04-07 15:43:07 -07002359 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002360 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002361 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002362}
2363
2364TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002365 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002366 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002367 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002368 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002369 .WillOnce(
2370 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2371
2372 attempter_.is_install_ = false;
2373 attempter_.CalculateDlcParams();
2374
Amin Hassani538bd592020-11-04 20:46:08 -08002375 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002376 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2377 OmahaRequestParams::AppParams dlc_app_params =
2378 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2379 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2380
2381 EXPECT_EQ(true, dlc_app_params.send_ping);
2382 EXPECT_EQ(0, dlc_app_params.ping_active);
2383 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2384 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2385}
2386
2387TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002388 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002389 MemoryPrefs prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002390 FakeSystemState::Get()->set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002391 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002392 .WillOnce(
2393 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2394
2395 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002396 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002397 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002398 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002399 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002400 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002401 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Amin Hassani538bd592020-11-04 20:46:08 -08002402 FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
2403 FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
2404 FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002405 attempter_.is_install_ = false;
2406 attempter_.CalculateDlcParams();
2407
Amin Hassani538bd592020-11-04 20:46:08 -08002408 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002409 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2410 OmahaRequestParams::AppParams dlc_app_params =
2411 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2412 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2413
2414 EXPECT_EQ(true, dlc_app_params.send_ping);
2415 EXPECT_EQ(0, dlc_app_params.ping_active);
2416 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2417 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2418}
2419
2420TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002421 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002422 MemoryPrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002423 FakeSystemState::Get()->set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002424 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002425 .WillOnce(
2426 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2427
2428 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002429 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002430 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002431 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002432 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002433 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002434 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002435
Amin Hassani538bd592020-11-04 20:46:08 -08002436 FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
2437 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
2438 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002439 attempter_.is_install_ = false;
2440 attempter_.CalculateDlcParams();
2441
Amin Hassani538bd592020-11-04 20:46:08 -08002442 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
Andrewe045aef2020-01-08 16:29:22 -08002443 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2444 OmahaRequestParams::AppParams dlc_app_params =
2445 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2446 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2447
2448 EXPECT_EQ(true, dlc_app_params.send_ping);
2449 EXPECT_EQ(1, dlc_app_params.ping_active);
2450 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2451 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2452}
Andrewa8d7df32020-03-15 20:10:01 -07002453
2454TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002455 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002456 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002457 FakeSystemState::Get()->set_prefs(&fake_prefs);
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});
Amin Hassani538bd592020-11-04 20:46:08 -08002464 FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
2465 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
2466 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
2467 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2468 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2469 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002470
Andrew065d78d2020-04-07 15:43:07 -07002471 attempter_.dlc_ids_ = {dlc_id};
2472 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002473 attempter_.CalculateDlcParams();
2474
Amin Hassani538bd592020-11-04 20:46:08 -08002475 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2476 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
Andrew065d78d2020-04-07 15:43:07 -07002477 // Active key is set on install.
Amin Hassani538bd592020-11-04 20:46:08 -08002478 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
Andrew065d78d2020-04-07 15:43:07 -07002479 int64_t temp_int;
Amin Hassani538bd592020-11-04 20:46:08 -08002480 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrew065d78d2020-04-07 15:43:07 -07002481 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002482}
2483
2484TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002485 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002486 FakePrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002487 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002488 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002489 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002490 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002491 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Amin Hassani538bd592020-11-04 20:46:08 -08002492 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2493 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002494 EXPECT_EQ(temp_int, kPingActiveValue);
2495}
2496
2497TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002498 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002499 MemoryPrefs fake_prefs;
Amin Hassani538bd592020-11-04 20:46:08 -08002500 FakeSystemState::Get()->set_prefs(&fake_prefs);
Andrew065d78d2020-04-07 15:43:07 -07002501 auto sub_keys = {
2502 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2503 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002504 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002505 FakeSystemState::Get()->prefs()->SetInt64(key, 1);
2506 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002507 }
Andrewa8d7df32020-03-15 20:10:01 -07002508 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002509 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002510 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Amin Hassani538bd592020-11-04 20:46:08 -08002511 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
Andrew065d78d2020-04-07 15:43:07 -07002512 }
Andrewa8d7df32020-03-15 20:10:01 -07002513}
2514
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002515TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2516 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2517 attempter_.omaha_request_params_->set_dlc_apps_params(
2518 {{dlc_1, {.name = dlc_1, .updated = false}},
2519 {dlc_2, {.name = dlc_2}},
2520 {dlc_3, {.name = dlc_3, .updated = false}}});
2521 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2522}
2523
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002524} // namespace chromeos_update_engine