blob: edcb67bc28e679b7b914a399e380706f0157d729 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
Darin Petkovf42cc1c2010-09-01 09:03:02 -070016
Alex Deymo2c0db7b2014-11-04 12:23:39 -080017#include "update_engine/update_attempter.h"
18
Ben Chan9abb7632014-08-07 00:10:53 -070019#include <stdint.h>
20
Jae Hoon Kim051627a2019-09-03 12:56:32 -070021#include <limits>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070022#include <map>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023#include <memory>
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -070024#include <string>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070025#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070026
Ben Chan06c76a42014-09-05 08:21:06 -070027#include <base/files/file_util.h>
Miriam Polzeraff72002020-08-27 08:20:39 +020028#include <base/files/scoped_temp_dir.h>
Alex Deymo0b3db6b2015-08-10 15:19:37 -070029#include <base/message_loop/message_loop.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"
46#include "update_engine/common/platform_constants.h"
47#include "update_engine/common/prefs.h"
48#include "update_engine/common/test_utils.h"
49#include "update_engine/common/utils.h"
Gilad Arnold5bb4c902014-04-10 12:32:13 -070050#include "update_engine/fake_system_state.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070051#include "update_engine/libcurl_http_fetcher.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070052#include "update_engine/mock_p2p_manager.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080053#include "update_engine/mock_payload_state.h"
Aaron Wood9321f502017-09-07 11:18:54 -070054#include "update_engine/mock_service_observer.h"
Jae Hoon Kim051627a2019-09-03 12:56:32 -070055#include "update_engine/omaha_utils.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:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700172 explicit UpdateAttempterUnderTest(SystemState* system_state)
173 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700174
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700175 void Update(const std::string& app_version,
176 const std::string& omaha_url,
177 const std::string& target_channel,
Amin Hassani37b67232020-08-13 09:29:48 -0700178 const std::string& lts_tag,
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700179 const std::string& target_version_prefix,
180 bool rollback_allowed,
181 bool rollback_data_save_requested,
182 int rollback_allowed_milestones,
Miriam Polzeraff72002020-08-27 08:20:39 +0200183 bool rollback_on_channel_downgrade,
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700184 bool obey_proxies,
185 bool interactive) override {
186 update_called_ = true;
187 if (do_update_) {
188 UpdateAttempter::Update(app_version,
189 omaha_url,
190 target_channel,
Amin Hassani37b67232020-08-13 09:29:48 -0700191 lts_tag,
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700192 target_version_prefix,
193 rollback_allowed,
194 rollback_data_save_requested,
195 rollback_allowed_milestones,
Miriam Polzeraff72002020-08-27 08:20:39 +0200196 rollback_on_channel_downgrade,
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700197 obey_proxies,
198 interactive);
199 return;
200 }
201 LOG(INFO) << "[TEST] Update() disabled.";
202 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
203 }
204
205 void DisableUpdate() { do_update_ = false; }
206
207 bool WasUpdateCalled() const { return update_called_; }
208
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700209 // Wrap the update scheduling method, allowing us to opt out of scheduled
210 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700211 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700212 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700213 if (do_schedule_updates_)
214 return UpdateAttempter::ScheduleUpdates();
215 LOG(INFO) << "[TEST] Update scheduling disabled.";
216 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700217 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700218 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700219
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700220 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
221
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700222 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700223 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700224
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700225 // Need to expose following private members of |UpdateAttempter| for tests.
226 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700227 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800228
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700229 // Need to expose |waiting_for_scheduled_check_| for testing.
230 void SetWaitingForScheduledCheck(bool waiting) {
231 waiting_for_scheduled_check_ = waiting;
232 }
233
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700234 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700235 // Used for overrides of |Update()|.
236 bool update_called_ = false;
237 bool do_update_ = true;
238
239 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700240 bool schedule_updates_called_ = false;
241 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700242};
243
244class UpdateAttempterTest : public ::testing::Test {
245 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700246 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600247 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300248 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700249 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700250 fake_system_state_.set_connection_manager(&mock_connection_manager);
251 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800252 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700253 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700254 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700255
Alex Deymo33e91e72015-12-01 18:26:08 -0300256 certificate_checker_.Init();
257
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800258 attempter_.set_forced_update_pending_callback(
259 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700260 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700261 attempter_.Init();
Jay Srinivasan43488792012-06-19 00:25:31 -0700262 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700263
Alex Deymo610277e2014-11-11 21:18:11 -0800264 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700265 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700266 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700267 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700268 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700269 EXPECT_EQ(0.0, attempter_.download_progress_);
270 EXPECT_EQ(0, attempter_.last_checked_time_);
271 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700272 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800273 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700274 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700275 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700276
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700277 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700278 actual_using_p2p_for_downloading_ = false;
279 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
280 SetUsingP2PForDownloading(_))
281 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
282 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
283 GetUsingP2PForDownloading())
284 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
285 actual_using_p2p_for_sharing_ = false;
286 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
287 SetUsingP2PForSharing(_))
288 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
289 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
290 GetUsingP2PForDownloading())
291 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700292 }
293
Alex Deymo60ca1a72015-06-18 18:19:15 -0700294 public:
295 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200296
Alex Deymo60ca1a72015-06-18 18:19:15 -0700297 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800298 void UpdateTestStart();
299 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700300 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700301 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700302 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700303 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700304 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700305 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700306 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700307 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700308 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700309 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700310 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700311 void SessionIdTestChange();
312 void SessionIdTestEnforceEmptyStrPingOmaha();
313 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700314 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200315 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200316 void ResetRollbackHappenedStart(bool is_consumer,
317 bool is_policy_available,
318 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700319 // Staging related callbacks.
320 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
321 void CheckStagingOff();
322 void StagingSetsPrefsAndTurnsOffScatteringStart();
323 void StagingOffIfInteractiveStart();
324 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700325
Gilad Arnold74b5f552014-10-07 08:17:16 -0700326 bool actual_using_p2p_for_downloading() {
327 return actual_using_p2p_for_downloading_;
328 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800329 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700330
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700331 // |CheckForUpdate()| related member functions.
332 void TestCheckForUpdate();
333
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700334 // |OnUpdateScheduled()| related member functions.
335 void TestOnUpdateScheduled();
336
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700337 // |ProcessingDone()| related member functions.
338 void TestProcessingDone();
339
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700340 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700341 brillo::BaseMessageLoop loop_{&base_loop_};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700342
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700343 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700344 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300345 OpenSSLWrapper openssl_wrapper_;
346 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800347 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700348 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700349
Alex Deymo8427b4a2014-11-05 14:00:32 -0800350 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700351 NiceMock<MockPrefs>*
352 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800353 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700354
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700355 // |CheckForUpdate()| test params.
356 CheckForUpdateTestParams cfu_params_;
357
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700358 // |OnUpdateScheduled()| test params.
359 OnUpdateScheduledTestParams ous_params_;
360
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700361 // |ProcessingDone()| test params.
362 ProcessingDoneTestParams pd_params_;
363
Gilad Arnold74b5f552014-10-07 08:17:16 -0700364 bool actual_using_p2p_for_downloading_;
365 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700366};
367
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700368void UpdateAttempterTest::TestCheckForUpdate() {
369 // Setup
370 attempter_.status_ = cfu_params_.status;
371 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
372 cfu_params_.is_official_build);
373 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
374 cfu_params_.are_dev_features_enabled);
375
376 // Invocation
377 EXPECT_EQ(
378 cfu_params_.expected_result,
379 attempter_.CheckForUpdate(
380 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
381
382 // Verify
383 EXPECT_EQ(cfu_params_.expected_forced_app_version,
384 attempter_.forced_app_version());
385 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
386 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700387 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
388 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700389}
390
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700391void UpdateAttempterTest::TestProcessingDone() {
392 // Setup
393 attempter_.DisableScheduleUpdates();
394 attempter_.is_install_ = pd_params_.is_install;
395 attempter_.status_ = pd_params_.status;
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -0700396 attempter_.omaha_request_params_->set_dlc_apps_params(
397 pd_params_.dlc_apps_params);
398
399 // Expects
400 if (pd_params_.should_install_completed_be_called)
401 EXPECT_CALL(mock_dlcservice_,
402 InstallCompleted(pd_params_.args_to_install_completed))
403 .WillOnce(Return(true));
404 else
405 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
406 if (pd_params_.should_update_completed_be_called)
407 EXPECT_CALL(mock_dlcservice_,
408 UpdateCompleted(pd_params_.args_to_update_completed))
409 .WillOnce(Return(true));
410 else
411 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700412
413 // Invocation
414 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
415
416 // Verify
417 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
418 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
419 attempter_.WasScheduleUpdatesCalled());
420 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
421}
422
Alex Deymo60ca1a72015-06-18 18:19:15 -0700423void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700424 loop_.PostTask(
425 FROM_HERE,
426 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
427 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700428}
429
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700430void UpdateAttempterTest::SessionIdTestChange() {
431 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
432 const auto old_session_id = attempter_.session_id_;
Miriam Polzeraff72002020-08-27 08:20:39 +0200433 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700434 EXPECT_NE(old_session_id, attempter_.session_id_);
435 ScheduleQuitMainLoop();
436}
437
438TEST_F(UpdateAttempterTest, SessionIdTestChange) {
439 loop_.PostTask(FROM_HERE,
440 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
441 base::Unretained(this)));
442 loop_.Run();
443}
444
445void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
446 // The |session_id_| should not be changed and should remain as an empty
447 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
448 // and |PingOmaha()| is called.
449 attempter_.DisableScheduleUpdates();
450 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
451 const auto old_session_id = attempter_.session_id_;
452 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
453 if (aa->Type() == OmahaRequestAction::StaticType()) {
454 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
455 }
456 };
457 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
458 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
459 EXPECT_CALL(*processor_, StartProcessing());
460 attempter_.PingOmaha();
461 EXPECT_EQ(old_session_id, attempter_.session_id_);
462 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
463 ScheduleQuitMainLoop();
464}
465
466TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
467 loop_.PostTask(
468 FROM_HERE,
469 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
470 base::Unretained(this)));
471 loop_.Run();
472}
473
474void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
475 // All session IDs passed into |OmahaRequestActions| should be enforced to
476 // have the same value in |BuildUpdateActions()|.
477 unordered_set<string> session_ids;
478 // Gather all the session IDs being passed to |OmahaRequestActions|.
479 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
480 if (aa->Type() == OmahaRequestAction::StaticType())
481 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
482 };
483 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
484 .WillRepeatedly(Invoke(CheckSessionId));
485 attempter_.BuildUpdateActions(false);
486 // Validate that all the session IDs are the same.
487 EXPECT_EQ(1, session_ids.size());
488 ScheduleQuitMainLoop();
489}
490
491TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
492 loop_.PostTask(
493 FROM_HERE,
494 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
495 base::Unretained(this)));
496 loop_.Run();
497}
498
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700499void UpdateAttempterTest::SessionIdTestInDownloadAction() {
500 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
501 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
502 string header_value;
503 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
504 if (aa->Type() == DownloadAction::StaticType()) {
505 DownloadAction* da = static_cast<DownloadAction*>(aa);
506 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
507 &header_value));
508 }
509 };
510 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
511 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
512 attempter_.BuildUpdateActions(false);
513 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
514 EXPECT_EQ(attempter_.session_id_, header_value);
515 ScheduleQuitMainLoop();
516}
517
518TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
519 loop_.PostTask(FROM_HERE,
520 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
521 base::Unretained(this)));
522 loop_.Run();
523}
524
Darin Petkov1b003102010-11-30 10:18:36 -0800525TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700526 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800527 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700528 DownloadAction action(prefs_,
529 nullptr,
530 nullptr,
531 nullptr,
532 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700533 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800534 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700535 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700536 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700537 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700538 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800539}
540
541TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800542 MockAction action;
543 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700544 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800545 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800546 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700547 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
548 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800549}
550
Aaron Wood9321f502017-09-07 11:18:54 -0700551TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
552 // Simple test case, where all the values match (nothing was skipped)
553 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
554 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
555 uint64_t bytes_received_1 = bytes_progressed_1;
556 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
557 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
558
559 double progress_1 =
560 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
561 double progress_2 =
562 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
563
564 EXPECT_EQ(0.0, attempter_.download_progress_);
565 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700566 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700567 attempter_.new_payload_size_ = bytes_total;
568 NiceMock<MockServiceObserver> observer;
569 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700570 SendStatusUpdate(AllOf(
571 Field(&UpdateEngineStatus::progress, progress_1),
572 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
573 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700574 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700575 SendStatusUpdate(AllOf(
576 Field(&UpdateEngineStatus::progress, progress_2),
577 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
578 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700579 attempter_.AddObserver(&observer);
580 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
581 EXPECT_EQ(progress_1, attempter_.download_progress_);
582 // This iteration validates that a later set of updates to the variables are
583 // properly handled (so that |getStatus()| will return the same progress info
584 // as the callback is receiving.
585 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
586 EXPECT_EQ(progress_2, attempter_.download_progress_);
587}
588
589TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700590 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700591 // first bytes are received.
592 uint64_t bytes_progressed = 1024 * 1024; // 1MB
593 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
594 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
595 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
596 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700597 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700598 attempter_.new_payload_size_ = bytes_total;
599 EXPECT_EQ(0.0, attempter_.download_progress_);
600 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700601 EXPECT_CALL(observer,
602 SendStatusUpdate(AllOf(
603 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
604 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700605 attempter_.AddObserver(&observer);
606 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
607 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
608}
609
610TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
611 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700612 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700613 uint64_t bytes_progressed = 0; // ignored
614 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
615 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
616 attempter_.status_ = UpdateStatus::DOWNLOADING;
617 attempter_.new_payload_size_ = bytes_total;
618 EXPECT_EQ(0.0, attempter_.download_progress_);
619 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700620 EXPECT_CALL(observer,
621 SendStatusUpdate(AllOf(
622 Field(&UpdateEngineStatus::progress, 1.0),
623 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
624 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700625 attempter_.AddObserver(&observer);
626 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
627 EXPECT_EQ(1.0, attempter_.download_progress_);
628}
629
Darin Petkov1b003102010-11-30 10:18:36 -0800630TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700631 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800632 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800633 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700634 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800635 ObjectCollectorAction<OmahaResponse> collector_action;
636 BondActions(&action, &collector_action);
637 OmahaResponse response;
638 response.poll_interval = 234;
639 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800640 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700641 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800642 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700643 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800644 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700645 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800646}
647
Alex Deymo30534502015-07-20 15:06:33 -0700648TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700649 FakePrefs fake_prefs;
650 string boot_id;
651 EXPECT_TRUE(utils::GetBootId(&boot_id));
652 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
653 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700654 attempter_.Init();
655 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700656}
657
658TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700659 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700660 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700661
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700662 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800663 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700664 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700665 EXPECT_EQ(ErrorCode::kOmahaRequestError,
666 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700667 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800668 EXPECT_EQ(
669 ErrorCode::kOmahaResponseHandlerError,
670 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Tianjie24f96092020-06-30 12:26:25 -0700671 DynamicPartitionControlStub dynamic_control_stub;
672 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800673 EXPECT_EQ(
674 ErrorCode::kFilesystemVerifierError,
675 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300676 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700677 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800678 EXPECT_EQ(
679 ErrorCode::kPostinstallRunnerError,
680 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800681 MockAction action_mock;
682 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700683 EXPECT_EQ(ErrorCode::kError,
684 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700685}
686
Darin Petkov36275772010-10-01 11:40:57 -0700687TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700688 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800689 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700690 .WillOnce(Return(false));
691 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700692 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800693 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800694 .WillOnce(
695 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
696 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700697 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700698 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800699 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800700 .WillOnce(
701 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
702 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700703 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700704 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800705 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700706 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700707 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700708}
709
710TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800711 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700712 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700713 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
714 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800715 .WillOnce(
716 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
717 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800718 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700719 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800720 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700721 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800722 EXPECT_CALL(*prefs_,
723 SetInt64(kPrefsDeltaUpdateFailures,
724 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
725 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700726 attempter_.MarkDeltaUpdateFailure();
727}
728
Darin Petkov1b003102010-11-30 10:18:36 -0800729TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
730 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
731 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700732 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800733 .Times(0);
734 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700735 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800736 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700737 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700738 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700739 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800740 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700741 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800742}
743
744TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
745 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700746 EnqueueAction(Pointee(Property(
747 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700748 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700749 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700750 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800751 attempter_.error_event_.reset(new OmahaEvent(
752 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800753 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700754 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800755}
756
Darin Petkove6ef2f82011-03-07 17:31:11 -0800757namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700758// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200759vector<string> GetUpdateActionTypes() {
760 return {OmahaRequestAction::StaticType(),
761 OmahaResponseHandlerAction::StaticType(),
762 UpdateBootFlagsAction::StaticType(),
763 OmahaRequestAction::StaticType(),
764 DownloadAction::StaticType(),
765 OmahaRequestAction::StaticType(),
766 FilesystemVerifierAction::StaticType(),
767 PostinstallRunnerAction::StaticType(),
768 OmahaRequestAction::StaticType()};
769}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700770
771// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200772vector<string> GetRollbackActionTypes() {
773 return {InstallPlanAction::StaticType(),
774 PostinstallRunnerAction::StaticType()};
775}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700776
Adolfo Victoria497044c2018-07-18 07:51:42 -0700777const StagingSchedule kValidStagingSchedule = {
778 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
779
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700780} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800781
782void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700783 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700784
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700785 // Expect that the device policy is loaded by the |UpdateAttempter| at some
786 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100787 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700788 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800789 .Times(testing::AtLeast(1))
790 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100791 attempter_.policy_provider_.reset(
792 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700793
794 {
795 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200796 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700797 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700798 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200799 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700800 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700801 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700802 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700803
Miriam Polzeraff72002020-08-27 08:20:39 +0200804 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700805 loop_.PostTask(FROM_HERE,
806 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
807 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800808}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700809
Darin Petkove6ef2f82011-03-07 17:31:11 -0800810void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700811 EXPECT_EQ(0, attempter_.http_response_code());
812 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700813 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700814 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800815}
816
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800817void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
818 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700819 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100820 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700821 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100822 fake_system_state_.set_device_policy(device_policy.get());
823 if (enterprise_rollback) {
824 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800825 EXPECT_CALL(*device_policy, GetOwner(_))
826 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100827 } else {
828 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800829 EXPECT_CALL(*device_policy, GetOwner(_))
830 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
831 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100832 }
833
834 attempter_.policy_provider_.reset(
835 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700836
Alex Deymo763e7db2015-08-27 21:08:08 -0700837 if (valid_slot) {
838 BootControlInterface::Slot rollback_slot = 1;
839 LOG(INFO) << "Test Mark Bootable: "
840 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700841 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
842 true);
Don Garrett6646b442013-11-13 15:29:11 -0800843 }
844
Chris Sosa28e479c2013-07-12 11:39:53 -0700845 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700846
Chris Sosad38b1132014-03-25 10:43:59 -0700847 // We only allow rollback on devices that are not enterprise enrolled and
848 // which have a valid slot to rollback to.
849 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800850 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700851 }
852
Chris Sosa28e479c2013-07-12 11:39:53 -0700853 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700854 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200855 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700856 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200857 EnqueueAction(Pointee(
858 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700859 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700860 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700861
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700862 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700863 loop_.PostTask(FROM_HERE,
864 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
865 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700866 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700867 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700868 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700869 }
870}
871
872void UpdateAttempterTest::RollbackTestVerify() {
873 // Verifies the actions that were enqueued.
874 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700875 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700876 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
877 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700878 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700879}
880
Darin Petkove6ef2f82011-03-07 17:31:11 -0800881TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700882 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700883 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700884}
885
Chris Sosa76a29ae2013-07-11 17:59:24 -0700886TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700887 loop_.PostTask(FROM_HERE,
888 base::Bind(&UpdateAttempterTest::RollbackTestStart,
889 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800890 false,
891 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700892 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700893}
894
Don Garrett6646b442013-11-13 15:29:11 -0800895TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700896 loop_.PostTask(FROM_HERE,
897 base::Bind(&UpdateAttempterTest::RollbackTestStart,
898 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800899 false,
900 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700901 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800902}
903
Chris Sosa76a29ae2013-07-11 17:59:24 -0700904TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700905 loop_.PostTask(FROM_HERE,
906 base::Bind(&UpdateAttempterTest::RollbackTestStart,
907 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800908 true,
909 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700910 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700911}
912
Thieu Le116fda32011-04-19 11:01:54 -0700913void UpdateAttempterTest::PingOmahaTestStart() {
914 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700915 EnqueueAction(Pointee(Property(
916 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700917 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700918 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700919 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700920}
921
922TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700923 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700924 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700925 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700926 // testing, which is more permissive than we want to handle here.
927 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700928 loop_.PostTask(FROM_HERE,
929 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
930 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700931 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700932 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700933 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700934}
935
Darin Petkov18c7bce2011-06-16 14:07:00 -0700936TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800937 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700938 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700939 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700940 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700941 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
942 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700943 EXPECT_EQ(
944 static_cast<ErrorCode>(static_cast<int>(kCode) |
945 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
946 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700947}
948
949TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700950 attempter_.install_plan_.reset(new InstallPlan);
951 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800952 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700953 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700954 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700955 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700956 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
957 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700958 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800959 static_cast<ErrorCode>(static_cast<int>(kCode) |
960 static_cast<int>(ErrorCode::kResumedFlag) |
961 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700962 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700963}
964
David Zeuthen8f191b22013-08-06 12:27:50 -0700965TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
966 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700967 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700968 mock_p2p_manager.fake().SetP2PEnabled(false);
969 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
970 attempter_.UpdateEngineStarted();
971}
972
973TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
974 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700975 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700976 mock_p2p_manager.fake().SetP2PEnabled(true);
977 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
978 attempter_.UpdateEngineStarted();
979}
980
981TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
982 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700983 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700984 mock_p2p_manager.fake().SetP2PEnabled(true);
985 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700986 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700987 attempter_.UpdateEngineStarted();
988}
989
990TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700991 loop_.PostTask(FROM_HERE,
992 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
993 base::Unretained(this)));
994 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700995}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700996
David Zeuthen8f191b22013-08-06 12:27:50 -0700997void UpdateAttempterTest::P2PNotEnabledStart() {
998 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700999 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001000 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001001 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001002 mock_p2p_manager.fake().SetP2PEnabled(false);
1003 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Miriam Polzeraff72002020-08-27 08:20:39 +02001004 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -07001005 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001006 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001007 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001008}
1009
1010TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001011 loop_.PostTask(FROM_HERE,
1012 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
1013 base::Unretained(this)));
1014 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001015}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001016
David Zeuthen8f191b22013-08-06 12:27:50 -07001017void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001018 // If P2P is enabled, but starting it fails ensure we don't do
1019 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001020 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001021 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001022 mock_p2p_manager.fake().SetP2PEnabled(true);
1023 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
1024 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1025 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Miriam Polzeraff72002020-08-27 08:20:39 +02001026 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001027 EXPECT_FALSE(actual_using_p2p_for_downloading());
1028 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001029 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001030}
1031
1032TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001033 loop_.PostTask(
1034 FROM_HERE,
1035 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1036 base::Unretained(this)));
1037 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001038}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001039
David Zeuthen8f191b22013-08-06 12:27:50 -07001040void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001041 // If P2P is enabled, starting it works but housekeeping fails, ensure
1042 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001043 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001044 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001045 mock_p2p_manager.fake().SetP2PEnabled(true);
1046 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1047 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001048 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Miriam Polzeraff72002020-08-27 08:20:39 +02001049 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001050 EXPECT_FALSE(actual_using_p2p_for_downloading());
1051 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001052 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001053}
1054
1055TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001056 loop_.PostTask(FROM_HERE,
1057 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1058 base::Unretained(this)));
1059 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001060}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001061
David Zeuthen8f191b22013-08-06 12:27:50 -07001062void UpdateAttempterTest::P2PEnabledStart() {
1063 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001064 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001065 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001066 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001067 mock_p2p_manager.fake().SetP2PEnabled(true);
1068 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1069 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001070 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Miriam Polzeraff72002020-08-27 08:20:39 +02001071 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001072 EXPECT_TRUE(actual_using_p2p_for_downloading());
1073 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001074 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001075}
1076
1077TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001078 loop_.PostTask(FROM_HERE,
1079 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1080 base::Unretained(this)));
1081 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001082}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001083
David Zeuthen8f191b22013-08-06 12:27:50 -07001084void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1085 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001086 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001087 // For an interactive check, if P2P is enabled and starting it
1088 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001089 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001090 mock_p2p_manager.fake().SetP2PEnabled(true);
1091 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1092 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001093 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001094 attempter_.Update("",
1095 "",
1096 "",
1097 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001098 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001099 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001100 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001101 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001102 false,
Miriam Polzeraff72002020-08-27 08:20:39 +02001103 false,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001104 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001105 EXPECT_FALSE(actual_using_p2p_for_downloading());
1106 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001107 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001108}
1109
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001110TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001111 loop_.PostTask(
1112 FROM_HERE,
1113 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1114 base::Unretained(this)));
1115 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116}
1117
1118// Tests that the scatter_factor_in_seconds value is properly fetched
1119// from the device policy.
1120void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001121 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001122
Igor9fd76b62017-12-11 15:24:18 +01001123 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001124 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001125 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001126
1127 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001128 .WillRepeatedly(
1129 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001130
Igor9fd76b62017-12-11 15:24:18 +01001131 attempter_.policy_provider_.reset(
1132 new policy::PolicyProvider(std::move(device_policy)));
1133
Miriam Polzeraff72002020-08-27 08:20:39 +02001134 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001135 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1136
Alex Deymo60ca1a72015-06-18 18:19:15 -07001137 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001138}
1139
1140TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001141 loop_.PostTask(
1142 FROM_HERE,
1143 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1144 base::Unretained(this)));
1145 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146}
1147
1148void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1149 // Tests that the scatter_factor_in_seconds value is properly fetched
1150 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001151 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001152 FakePrefs fake_prefs;
1153 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001154
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001155 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001156
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001157 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001158
Ben Chan9abb7632014-08-07 00:10:53 -07001159 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001160
Igor9fd76b62017-12-11 15:24:18 +01001161 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001162 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001163 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001164
1165 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001166 .WillRepeatedly(
1167 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001168
Igor9fd76b62017-12-11 15:24:18 +01001169 attempter_.policy_provider_.reset(
1170 new policy::PolicyProvider(std::move(device_policy)));
1171
Miriam Polzeraff72002020-08-27 08:20:39 +02001172 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001173 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1174
1175 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001176 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001177
Ben Chan9abb7632014-08-07 00:10:53 -07001178 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001179 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001180 EXPECT_EQ(initial_value - 1, new_value);
1181
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001182 EXPECT_TRUE(
1183 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001184
1185 // However, if the count is already 0, it's not decremented. Test that.
1186 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001187 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Miriam Polzeraff72002020-08-27 08:20:39 +02001188 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001189 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1190 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001191 EXPECT_EQ(initial_value, new_value);
1192
Alex Deymo60ca1a72015-06-18 18:19:15 -07001193 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001194}
1195
Jay Srinivasan08fce042012-06-07 16:31:01 -07001196TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001197 loop_.PostTask(
1198 FROM_HERE,
1199 base::Bind(
1200 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1201 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001202 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001203}
1204
1205void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1206 // Tests that no scattering logic is enabled if the update check
1207 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001208 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001209 FakePrefs fake_prefs;
1210 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001211
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001212 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001213 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001214
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001215 EXPECT_TRUE(
1216 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001217 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001218
1219 // make sure scatter_factor is non-zero as scattering is disabled
1220 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001221 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001222
Igor9fd76b62017-12-11 15:24:18 +01001223 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001224 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001225 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001226
1227 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001228 .WillRepeatedly(
1229 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001230
Igor9fd76b62017-12-11 15:24:18 +01001231 attempter_.policy_provider_.reset(
1232 new policy::PolicyProvider(std::move(device_policy)));
1233
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001234 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001235 attempter_.Update("",
1236 "",
1237 "",
1238 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001239 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001240 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001241 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001242 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001243 false,
Miriam Polzeraff72002020-08-27 08:20:39 +02001244 false,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001245 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001246 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1247
1248 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001249 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001250 EXPECT_FALSE(
1251 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001252 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001253 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1254 EXPECT_FALSE(
1255 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001256 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001257
Alex Deymo60ca1a72015-06-18 18:19:15 -07001258 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001259}
1260
Adolfo Victoria497044c2018-07-18 07:51:42 -07001261void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1262 FakePrefs* prefs) {
1263 attempter_.prefs_ = prefs;
1264 fake_system_state_.set_prefs(prefs);
1265
1266 int64_t initial_value = 8;
1267 EXPECT_TRUE(
1268 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1269 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1270 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1271
1272 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1273 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1274 fake_system_state_.set_device_policy(device_policy.get());
1275 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1276 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1277
1278 attempter_.policy_provider_.reset(
1279 new policy::PolicyProvider(std::move(device_policy)));
1280}
1281
1282TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1283 loop_.PostTask(
1284 FROM_HERE,
1285 base::Bind(
1286 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1287 base::Unretained(this)));
1288 loop_.Run();
1289}
1290
1291void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1292 // Tests that staging sets its prefs properly and turns off scattering.
1293 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1294 FakePrefs fake_prefs;
1295 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1296
Miriam Polzeraff72002020-08-27 08:20:39 +02001297 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001298 // Check that prefs have the correct values.
1299 int64_t update_count;
1300 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1301 int64_t waiting_time_days;
1302 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1303 &waiting_time_days));
1304 EXPECT_GT(waiting_time_days, 0);
1305 // Update count should have been decremented.
1306 EXPECT_EQ(7, update_count);
1307 // Check that Omaha parameters were updated correctly.
1308 EXPECT_TRUE(
1309 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1310 EXPECT_TRUE(
1311 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1312 EXPECT_EQ(waiting_time_days,
1313 attempter_.omaha_request_params_->waiting_period().InDays());
1314 // Check class variables.
1315 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1316 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1317 // Check that scattering is turned off
1318 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1319 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1320
1321 ScheduleQuitMainLoop();
1322}
1323
1324void UpdateAttempterTest::CheckStagingOff() {
1325 // Check that all prefs were removed.
1326 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1327 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1328 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1329 // Check that the Omaha parameters have the correct value.
1330 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1331 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1332 attempter_.staging_wait_time_);
1333 EXPECT_FALSE(
1334 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1335 EXPECT_FALSE(
1336 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1337 // Check that scattering is turned off too.
1338 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1339}
1340
1341TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1342 loop_.PostTask(FROM_HERE,
1343 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1344 base::Unretained(this)));
1345 loop_.Run();
1346}
1347
1348void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1349 // Tests that staging is turned off when an interactive update is requested.
1350 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1351 FakePrefs fake_prefs;
1352 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1353
Miriam Polzeraff72002020-08-27 08:20:39 +02001354 attempter_.Update("",
1355 "",
1356 "",
1357 "",
1358 "",
1359 false,
1360 false,
1361 0,
1362 false,
1363 false,
1364 /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001365 CheckStagingOff();
1366
1367 ScheduleQuitMainLoop();
1368}
1369
1370TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1371 loop_.PostTask(FROM_HERE,
1372 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1373 base::Unretained(this)));
1374 loop_.Run();
1375}
1376
1377void UpdateAttempterTest::StagingOffIfOobeStart() {
1378 // Tests that staging is turned off if OOBE hasn't been completed.
1379 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1380 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1381 FakePrefs fake_prefs;
1382 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1383
Miriam Polzeraff72002020-08-27 08:20:39 +02001384 attempter_.Update("",
1385 "",
1386 "",
1387 "",
1388 "",
1389 false,
1390 false,
1391 0,
1392 false,
1393 false,
1394 /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001395 CheckStagingOff();
1396
1397 ScheduleQuitMainLoop();
1398}
1399
David Zeuthen985b1122013-10-09 12:13:15 -07001400// Checks that we only report daily metrics at most every 24 hours.
1401TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1402 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001403 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001404
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001405 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001406 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001407
1408 Time epoch = Time::FromInternalValue(0);
1409 fake_clock.SetWallclockTime(epoch);
1410
1411 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1412 // we should report.
1413 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1414 // We should not report again if no time has passed.
1415 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1416
1417 // We should not report if only 10 hours has passed.
1418 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1419 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1420
1421 // We should not report if only 24 hours - 1 sec has passed.
1422 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1423 TimeDelta::FromSeconds(1));
1424 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1425
1426 // We should report if 24 hours has passed.
1427 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1428 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1429
1430 // But then we should not report again..
1431 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1432
1433 // .. until another 24 hours has passed
1434 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1435 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1436 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1437 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1438 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1439
1440 // .. and another 24 hours
1441 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1442 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1443 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1444 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1445 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1446
1447 // If the span between time of reporting and present time is
1448 // negative, we report. This is in order to reset the timestamp and
1449 // avoid an edge condition whereby a distant point in the future is
1450 // in the state variable resulting in us never ever reporting again.
1451 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1452 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1453 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1454
1455 // In this case we should not update until the clock reads 71 + 24 = 95.
1456 // Check that.
1457 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1458 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1459 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1460 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1461 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001462}
1463
David Zeuthen3c55abd2013-10-14 12:48:03 -07001464TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001465 FakeClock fake_clock;
1466 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001467 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001468 FakePrefs fake_prefs;
1469 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001470 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001471
1472 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001473 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001474
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001475 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001476
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001477 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001478 EXPECT_EQ(boot_time.ToTimeT(), 42);
1479}
1480
David Pursell02c18642014-11-06 11:26:11 -08001481TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1482 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1483 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1484}
1485
1486TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1487 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001488 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001489 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1490}
1491
1492TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1493 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001494 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001495 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1496}
1497
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001498// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1499// When adding, remove older tests related to |CheckForInstall()|.
1500TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1501 for (const auto status : kNonIdleUpdateStatuses) {
1502 // GIVEN a non-idle status.
1503 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001504
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001505 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1506 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001507}
1508
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001509TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1510 for (const auto status : kNonIdleUpdateStatuses) {
1511 // GIVEN a non-idle status.
1512 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001513
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001514 // THEN |ScheduleUpdates()| should not be called.
1515 cfu_params_.should_schedule_updates_be_called = false;
1516 // THEN result should indicate failure.
1517 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001518
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001519 TestCheckForUpdate();
1520 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001521}
1522
1523TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1524 // GIVEN a official build.
1525
1526 // THEN we except forced app version + forced omaha url to be cleared.
1527
1528 TestCheckForUpdate();
1529}
1530
1531TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001532 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001533 cfu_params_.is_official_build = false;
1534 cfu_params_.are_dev_features_enabled = true;
1535
1536 // THEN the forced app version + forced omaha url changes based on input.
1537 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1538 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1539
1540 TestCheckForUpdate();
1541}
1542
1543TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1544 // GIVEN a scheduled autest omaha url.
1545 cfu_params_.omaha_url = "autest-scheduled";
1546
1547 // THEN forced app version is cleared.
1548 // THEN forced omaha url changes to default constant.
1549 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1550
1551 TestCheckForUpdate();
1552}
1553
1554TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1555 // GIVEN a scheduled autest omaha url.
1556 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001557 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001558 cfu_params_.is_official_build = false;
1559 cfu_params_.are_dev_features_enabled = true;
1560
1561 // THEN forced app version changes based on input.
1562 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1563 // THEN forced omaha url changes to default constant.
1564 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1565
1566 TestCheckForUpdate();
1567}
1568
1569TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1570 // GIVEN a autest omaha url.
1571 cfu_params_.omaha_url = "autest";
1572
1573 // THEN forced app version is cleared.
1574 // THEN forced omaha url changes to default constant.
1575 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1576
1577 TestCheckForUpdate();
1578}
1579
1580TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1581 // GIVEN a autest omha url.
1582 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001583 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001584 cfu_params_.is_official_build = false;
1585 cfu_params_.are_dev_features_enabled = true;
1586
1587 // THEN forced app version changes based on input.
1588 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1589 // THEN forced omaha url changes to default constant.
1590 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1591
1592 TestCheckForUpdate();
1593}
1594
1595TEST_F(UpdateAttempterTest,
1596 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1597 // GIVEN a scheduled autest omaha url.
1598 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001599 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001600 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1601
1602 // THEN forced app version is cleared.
1603 // THEN forced omaha url changes to default constant.
1604 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1605
1606 TestCheckForUpdate();
1607}
1608
1609TEST_F(UpdateAttempterTest,
1610 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1611 // GIVEN a scheduled autest omaha url.
1612 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001613 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001614 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001615 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001616 cfu_params_.is_official_build = false;
1617 cfu_params_.are_dev_features_enabled = true;
1618
1619 // THEN forced app version changes based on input.
1620 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1621 // THEN forced omaha url changes to default constant.
1622 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1623
1624 TestCheckForUpdate();
1625}
1626
1627TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1628 // GIVEN a autest omaha url.
1629 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001630 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001631 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1632
1633 // THEN forced app version is cleared.
1634 // THEN forced omaha url changes to default constant.
1635 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1636
1637 TestCheckForUpdate();
1638}
1639
1640TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1641 // GIVEN a autest omaha url.
1642 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001643 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001644 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001645 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001646 cfu_params_.is_official_build = false;
1647 cfu_params_.are_dev_features_enabled = true;
1648
1649 // THEN forced app version changes based on input.
1650 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1651 // THEN forced omaha url changes to default constant.
1652 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1653
1654 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001655}
1656
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001657TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1658 // GIVEN a official build.
1659 // GIVEN forced callback is not set.
1660 attempter_.set_forced_update_pending_callback(nullptr);
1661
1662 // THEN we except forced app version + forced omaha url to be cleared.
1663 // THEN |ScheduleUpdates()| should not be called.
1664 cfu_params_.should_schedule_updates_be_called = false;
1665
1666 TestCheckForUpdate();
1667}
1668
1669TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001670 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001671 cfu_params_.is_official_build = false;
1672 cfu_params_.are_dev_features_enabled = true;
1673 // GIVEN forced callback is not set.
1674 attempter_.set_forced_update_pending_callback(nullptr);
1675
1676 // THEN the forced app version + forced omaha url changes based on input.
1677 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1678 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1679 // THEN |ScheduleUpdates()| should not be called.
1680 cfu_params_.should_schedule_updates_be_called = false;
1681
1682 TestCheckForUpdate();
1683}
1684
Xiaochu Liu88d90382018-08-29 16:09:11 -07001685TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1686 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1687 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1688 attempter_.CheckForInstall({}, "autest");
1689 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1690
1691 attempter_.CheckForInstall({}, "autest-scheduled");
1692 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1693
1694 attempter_.CheckForInstall({}, "http://omaha.phishing");
1695 EXPECT_EQ("", attempter_.forced_omaha_url());
1696}
1697
Colin Howesac170d92018-11-20 16:29:28 -08001698TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1699 attempter_.CheckForInstall({}, "http://foo.bar");
1700 attempter_.status_ = UpdateStatus::DOWNLOADING;
1701 EXPECT_TRUE(attempter_.is_install_);
1702 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1703 UpdateEngineStatus status;
1704 attempter_.GetStatus(&status);
1705 // Should set status to idle after an install operation.
1706 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1707}
1708
Colin Howes978c1082018-12-03 11:46:12 -08001709TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1710 attempter_.is_install_ = true;
1711 attempter_.Rollback(false);
1712 EXPECT_FALSE(attempter_.is_install_);
1713}
1714
1715TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1716 attempter_.is_install_ = true;
1717 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1718 EXPECT_FALSE(attempter_.is_install_);
1719}
1720
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001721TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001722 attempter_.CalculateUpdateParams(
Miriam Polzeraff72002020-08-27 08:20:39 +02001723 /*app_version=*/"",
1724 /*omaha_url=*/"",
1725 /*target_channel=*/"",
1726 /*lts_tag=*/"",
1727 /*target_version_prefix=*/"1234",
1728 /*rollback_allowed=*/false,
1729 /*rollback_data_save_requested=*/false,
1730 /*rollback_allowed_milestones=*/4,
1731 /*rollback_on_channel_downgrade=*/false,
1732 /*obey_proxies=*/false,
1733 /*interactive=*/false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001734 EXPECT_EQ("1234",
1735 fake_system_state_.request_params()->target_version_prefix());
1736
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001737 attempter_.CalculateUpdateParams(
Miriam Polzeraff72002020-08-27 08:20:39 +02001738 "", "", "", "", "", false, false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001739 EXPECT_TRUE(
1740 fake_system_state_.request_params()->target_version_prefix().empty());
1741}
1742
Amin Hassani37b67232020-08-13 09:29:48 -07001743TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
1744 attempter_.CalculateUpdateParams(
Miriam Polzeraff72002020-08-27 08:20:39 +02001745 "", "", "", "hint", "", false, false, 4, false, false, false);
Amin Hassani37b67232020-08-13 09:29:48 -07001746 EXPECT_EQ("hint", fake_system_state_.request_params()->lts_tag());
1747
1748 attempter_.CalculateUpdateParams(
Miriam Polzeraff72002020-08-27 08:20:39 +02001749 "", "", "", "", "", false, false, 4, false, false, false);
Amin Hassani37b67232020-08-13 09:29:48 -07001750 EXPECT_TRUE(fake_system_state_.request_params()->lts_tag().empty());
1751}
1752
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001753TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1754 attempter_.CalculateUpdateParams("",
1755 "",
1756 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001757 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001758 "1234",
1759 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001760 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001761 /*rollback_allowed_milestones=*/4,
Miriam Polzeraff72002020-08-27 08:20:39 +02001762 /*rollback_on_channel_downgrade=*/false,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001763 false,
1764 false);
1765 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001766 EXPECT_EQ(4,
1767 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001768
1769 attempter_.CalculateUpdateParams("",
1770 "",
1771 "",
Amin Hassani37b67232020-08-13 09:29:48 -07001772 "",
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001773 "1234",
1774 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001775 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001776 /*rollback_allowed_milestones=*/4,
Miriam Polzeraff72002020-08-27 08:20:39 +02001777 /*rollback_on_channel_downgrade=*/false,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001778 false,
1779 false);
1780 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001781 EXPECT_EQ(4,
1782 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001783}
1784
Miriam Polzeraff72002020-08-27 08:20:39 +02001785TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1786 base::ScopedTempDir tempdir;
1787 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
1788 fake_system_state_.request_params()->set_root(tempdir.GetPath().value());
1789 attempter_.CalculateUpdateParams(/*app_version=*/"",
1790 /*omaha_url=*/"",
1791 /*target_channel=*/"stable-channel",
1792 /*lts_tag=*/"",
1793 /*target_version_prefix=*/"",
1794 /*rollback_allowed=*/false,
1795 /*rollback_data_save_requested=*/false,
1796 /*rollback_allowed_milestones=*/4,
1797 /*rollback_on_channel_downgrade=*/false,
1798 /*obey_proxies=*/false,
1799 /*interactive=*/false);
1800 EXPECT_FALSE(fake_system_state_.request_params()->is_powerwash_allowed());
1801}
1802
1803TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1804 base::ScopedTempDir tempdir;
1805 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
1806 fake_system_state_.request_params()->set_root(tempdir.GetPath().value());
1807 attempter_.CalculateUpdateParams(/*app_version=*/"",
1808 /*omaha_url=*/"",
1809 /*target_channel=*/"stable-channel",
1810 /*lts_tag=*/"",
1811 /*target_version_prefix=*/"",
1812 /*rollback_allowed=*/false,
1813 /*rollback_data_save_requested=*/false,
1814 /*rollback_allowed_milestones=*/4,
1815 /*rollback_on_channel_downgrade=*/true,
1816 /*obey_proxies=*/false,
1817 /*interactive=*/false);
1818 EXPECT_TRUE(fake_system_state_.request_params()->is_powerwash_allowed());
1819}
1820
Aaron Wood23bd3392017-10-06 14:48:25 -07001821TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1822 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1823 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001824 OmahaResponseHandlerAction response_action(&fake_system_state_);
1825 response_action.install_plan_.version = "a.b.c.d";
1826 response_action.install_plan_.system_version = "b.c.d.e";
1827 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001828 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001829 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1830 // completed, with the deferred-update error code.
1831 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001832 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001833 {
1834 UpdateEngineStatus status;
1835 attempter_.GetStatus(&status);
1836 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001837 EXPECT_TRUE(attempter_.install_plan_);
1838 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001839 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001840 status.new_size_bytes);
1841 }
1842 // An "error" event should have been created to tell Omaha that the update is
1843 // being deferred.
1844 EXPECT_TRUE(nullptr != attempter_.error_event_);
1845 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1846 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1847 ErrorCode expected_code = static_cast<ErrorCode>(
1848 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1849 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1850 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1851 // End the processing
1852 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1853 // Validate the state of the attempter.
1854 {
1855 UpdateEngineStatus status;
1856 attempter_.GetStatus(&status);
1857 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001858 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001859 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001860 status.new_size_bytes);
1861 }
1862}
1863
1864TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001865 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001866 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001867 // Verify in-progress update with UPDATE_AVAILABLE is running
1868 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001869 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001870}
1871
Aaron Woodbf5a2522017-10-04 10:58:36 -07001872TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1873 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1874
1875 UpdateCheckParams params = {.updates_enabled = true};
1876 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1877
1878 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1879 attempter_.GetCurrentUpdateAttemptFlags());
1880}
1881
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001882TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1883 UpdateCheckParams params = {.updates_enabled = true,
1884 .rollback_allowed = false};
1885 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1886 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1887}
1888
1889TEST_F(UpdateAttempterTest, RollbackAllowed) {
1890 UpdateCheckParams params = {.updates_enabled = true,
1891 .rollback_allowed = true};
1892 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1893 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1894}
1895
Aaron Wood081c0232017-10-19 17:14:58 -07001896TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1897 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1898
1899 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1900 EXPECT_EQ(UpdateAttemptFlags::kNone,
1901 attempter_.GetCurrentUpdateAttemptFlags());
1902}
1903
1904TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1905 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1906
1907 // This tests that when CheckForUpdate() is called with the non-interactive
1908 // flag set, that it doesn't change the current UpdateAttemptFlags.
1909 attempter_.CheckForUpdate("",
1910 "",
1911 UpdateAttemptFlags::kFlagNonInteractive |
1912 UpdateAttemptFlags::kFlagRestrictDownload);
1913 EXPECT_EQ(UpdateAttemptFlags::kNone,
1914 attempter_.GetCurrentUpdateAttemptFlags());
1915}
1916
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001917void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1918 bool is_policy_loaded,
1919 bool expected_reset) {
1920 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1921 .WillRepeatedly(Return(true));
1922 auto mock_policy_provider =
1923 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1924 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1925 .WillRepeatedly(Return(is_consumer));
1926 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1927 .WillRepeatedly(Return(is_policy_loaded));
1928 const policy::MockDevicePolicy device_policy;
1929 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1930 .WillRepeatedly(ReturnRef(device_policy));
1931 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1932 SetRollbackHappened(false))
1933 .Times(expected_reset ? 1 : 0);
1934 attempter_.policy_provider_ = std::move(mock_policy_provider);
Miriam Polzeraff72002020-08-27 08:20:39 +02001935 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001936 ScheduleQuitMainLoop();
1937}
1938
1939TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1940 loop_.PostTask(FROM_HERE,
1941 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1942 base::Unretained(this),
1943 /*is_consumer=*/false,
1944 /*is_policy_loaded=*/false,
1945 /*expected_reset=*/false));
1946 loop_.Run();
1947}
1948
1949TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1950 loop_.PostTask(FROM_HERE,
1951 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1952 base::Unretained(this),
1953 /*is_consumer=*/true,
1954 /*is_policy_loaded=*/false,
1955 /*expected_reset=*/true));
1956 loop_.Run();
1957}
1958
1959TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1960 loop_.PostTask(FROM_HERE,
1961 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1962 base::Unretained(this),
1963 /*is_consumer=*/false,
1964 /*is_policy_loaded=*/true,
1965 /*expected_reset=*/true));
1966 loop_.Run();
1967}
1968
Marton Hunyady199152d2018-05-07 19:08:48 +02001969TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001970 attempter_.install_plan_.reset(new InstallPlan);
1971 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001972
1973 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1974 SetRollbackHappened(true))
1975 .Times(1);
1976 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1977}
1978
1979TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001980 attempter_.install_plan_.reset(new InstallPlan);
1981 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001982
1983 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1984 SetRollbackHappened(true))
1985 .Times(0);
1986 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1987}
1988
Marton Hunyadya0302682018-05-16 18:52:13 +02001989TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001990 attempter_.install_plan_.reset(new InstallPlan);
1991 attempter_.install_plan_->is_rollback = true;
1992 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001993
1994 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1995 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1996 .Times(1);
1997 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1998}
1999
2000TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07002001 attempter_.install_plan_.reset(new InstallPlan);
2002 attempter_.install_plan_->is_rollback = false;
2003 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02002004
2005 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2006 ReportEnterpriseRollbackMetrics(_, _))
2007 .Times(0);
2008 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2009}
2010
2011TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07002012 attempter_.install_plan_.reset(new InstallPlan);
2013 attempter_.install_plan_->is_rollback = true;
2014 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02002015
2016 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2017 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
2018 .Times(1);
2019 MockAction action;
2020 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
2021 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
2022}
2023
2024TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07002025 attempter_.install_plan_.reset(new InstallPlan);
2026 attempter_.install_plan_->is_rollback = false;
2027 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02002028
2029 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2030 ReportEnterpriseRollbackMetrics(_, _))
2031 .Times(0);
2032 MockAction action;
2033 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
2034 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
2035}
2036
May Lippert60aa3ca2018-08-15 16:55:29 -07002037TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
2038 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2039 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
2040 .Times(0);
2041 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
2042}
2043
2044TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
2045 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2046 fake_system_state_.set_device_policy(device_policy.get());
2047 // Make device policy return that this is not enterprise enrolled
2048 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
2049
2050 // Ensure that the metric is not recorded.
2051 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2052 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
2053 .Times(0);
2054 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2055}
2056
2057TEST_F(UpdateAttempterTest,
2058 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
2059 constexpr int kDaysToUpdate = 15;
2060 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2061 fake_system_state_.set_device_policy(device_policy.get());
2062 // Make device policy return that this is enterprise enrolled
2063 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
2064 // Pretend that there's a time restriction policy in place
2065 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
2066 .WillOnce(Return(true));
2067
2068 FakePrefs fake_prefs;
2069 Time update_first_seen_at = Time::Now();
2070 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2071 update_first_seen_at.ToInternalValue());
2072
2073 FakeClock fake_clock;
2074 Time update_finished_at =
2075 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2076 fake_clock.SetWallclockTime(update_finished_at);
2077
2078 fake_system_state_.set_clock(&fake_clock);
2079 fake_system_state_.set_prefs(&fake_prefs);
2080
2081 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2082 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
2083 .Times(1);
2084 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2085}
2086
2087TEST_F(UpdateAttempterTest,
2088 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
2089 constexpr int kDaysToUpdate = 15;
2090 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2091 fake_system_state_.set_device_policy(device_policy.get());
2092 // Make device policy return that this is enterprise enrolled
2093 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
2094 // Pretend that there's no time restriction policy in place
2095 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
2096 .WillOnce(Return(false));
2097
2098 FakePrefs fake_prefs;
2099 Time update_first_seen_at = Time::Now();
2100 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
2101 update_first_seen_at.ToInternalValue());
2102
2103 FakeClock fake_clock;
2104 Time update_finished_at =
2105 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
2106 fake_clock.SetWallclockTime(update_finished_at);
2107
2108 fake_system_state_.set_clock(&fake_clock);
2109 fake_system_state_.set_prefs(&fake_prefs);
2110
2111 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
2112 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
2113 .Times(1);
2114 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
2115}
2116
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002117TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2118 // GIVEN an update finished.
2119
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002120 // THEN update_engine should call update completion.
2121 pd_params_.should_update_completed_be_called = true;
2122 // THEN need reboot since update applied.
2123 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2124 // THEN install indication should be false.
2125
2126 TestProcessingDone();
2127}
2128
2129TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
2130 // GIVEN an update finished.
2131 // GIVEN DLC |AppParams| list.
2132 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2133 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2134 {dlc_2, {.name = dlc_2}}};
2135
2136 // THEN update_engine should call update completion.
2137 pd_params_.should_update_completed_be_called = true;
2138 pd_params_.args_to_update_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002139 // THEN need reboot since update applied.
2140 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2141 // THEN install indication should be false.
2142
2143 TestProcessingDone();
2144}
2145
2146TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2147 // GIVEN an install finished.
2148 pd_params_.is_install = true;
2149
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002150 // THEN update_engine should call install completion.
2151 pd_params_.should_install_completed_be_called = true;
2152 // THEN go idle.
2153 // THEN install indication should be false.
2154
2155 TestProcessingDone();
2156}
2157
2158TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2159 // GIVEN an install finished.
2160 pd_params_.is_install = true;
2161 // GIVEN DLC |AppParams| list.
2162 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2163 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2164 {dlc_2, {.name = dlc_2}}};
2165
2166 // THEN update_engine should call install completion.
2167 pd_params_.should_install_completed_be_called = true;
2168 pd_params_.args_to_install_completed = {dlc_2};
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002169 // THEN go idle.
2170 // THEN install indication should be false.
2171
2172 TestProcessingDone();
2173}
2174
2175TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2176 // GIVEN an install finished.
2177 pd_params_.is_install = true;
2178 // GIVEN a reporting error occurred.
2179 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2180
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002181 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002182 // THEN go idle.
2183 // THEN install indication should be false.
2184
2185 TestProcessingDone();
2186}
2187
2188TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2189 // GIVEN an update finished.
2190 // GIVEN an action error occured.
2191 pd_params_.code = ErrorCode::kNoUpdate;
2192
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002193 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002194 // THEN go idle.
2195 // THEN install indication should be false.
2196
2197 TestProcessingDone();
2198}
2199
2200TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2201 // GIVEN an install finished.
2202 pd_params_.is_install = true;
2203 // GIVEN an action error occured.
2204 pd_params_.code = ErrorCode::kNoUpdate;
2205
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002206 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002207 // THEN go idle.
2208 // THEN install indication should be false.
2209
2210 TestProcessingDone();
2211}
2212
2213TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2214 // GIVEN an update finished.
2215 // GIVEN an action error occured.
2216 pd_params_.code = ErrorCode::kError;
2217 // GIVEN an event error is set.
2218 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2219 OmahaEvent::kResultError,
2220 ErrorCode::kError));
2221
2222 // THEN indicate a error event.
2223 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2224 // THEN install indication should be false.
2225
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002226 // THEN update_engine should not call update completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002227 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2228 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2229 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2230 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2231 pd_params_.should_schedule_updates_be_called = false;
2232
2233 TestProcessingDone();
2234}
2235
2236TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2237 // GIVEN an install finished.
2238 pd_params_.is_install = true;
2239 // GIVEN an action error occured.
2240 pd_params_.code = ErrorCode::kError;
2241 // GIVEN an event error is set.
2242 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2243 OmahaEvent::kResultError,
2244 ErrorCode::kError));
2245
2246 // THEN indicate a error event.
2247 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2248 // THEN install indication should be false.
2249
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002250 // THEN update_engine should not call install completion.
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07002251 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2252 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2253 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2254 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2255 pd_params_.should_schedule_updates_be_called = false;
2256
2257 TestProcessingDone();
2258}
2259
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002260void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2261 // Tests that checks if |device_quick_fix_build_token| arrives when
2262 // policy is set and the device is enterprise enrolled based on |set_token|.
2263 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002264 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2265 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002266 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002267
2268 if (set_token)
2269 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2270 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2271 else
2272 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2273 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002274 attempter_.policy_provider_.reset(
2275 new policy::PolicyProvider(std::move(device_policy)));
Miriam Polzeraff72002020-08-27 08:20:39 +02002276 attempter_.Update("", "", "", "", "", false, false, 0, false, false, false);
Askar Aitzhan570ca872019-04-24 11:16:12 +02002277
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002278 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002279 ScheduleQuitMainLoop();
2280}
2281
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002282TEST_F(UpdateAttempterTest,
2283 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002284 loop_.PostTask(FROM_HERE,
2285 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002286 base::Unretained(this),
2287 /*set_token=*/true));
2288 loop_.Run();
2289}
2290
2291TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2292 loop_.PostTask(FROM_HERE,
2293 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2294 base::Unretained(this),
2295 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002296 loop_.Run();
2297}
2298
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002299TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2300 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2301 .Times(1);
2302 EXPECT_TRUE(attempter_.ScheduleUpdates());
2303 // Now there is an update scheduled which means that all subsequent
2304 // |ScheduleUpdates()| should fail.
2305 EXPECT_FALSE(attempter_.ScheduleUpdates());
2306 EXPECT_FALSE(attempter_.ScheduleUpdates());
2307 EXPECT_FALSE(attempter_.ScheduleUpdates());
2308}
2309
2310// Critical tests to always make sure that an update is scheduled. The following
2311// unittest(s) try and cover the correctness in synergy between
2312// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2313// actions that happen in the flow when |UpdateAttempter| get callbacked on
2314// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2315void UpdateAttempterTest::TestOnUpdateScheduled() {
2316 // Setup
2317 attempter_.SetWaitingForScheduledCheck(true);
2318 attempter_.DisableUpdate();
2319 attempter_.DisableScheduleUpdates();
2320
2321 // Invocation
2322 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2323
2324 // Verify
2325 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2326 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2327 attempter_.WasScheduleUpdatesCalled());
2328 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2329}
2330
2331TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2332 // GIVEN failed status.
2333
2334 // THEN update should be scheduled.
2335 ous_params_.should_schedule_updates_be_called = true;
2336
2337 TestOnUpdateScheduled();
2338}
2339
2340TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2341 // GIVEN ask me again later status.
2342 ous_params_.status = EvalStatus::kAskMeAgainLater;
2343
2344 // THEN update should be scheduled.
2345 ous_params_.should_schedule_updates_be_called = true;
2346
2347 TestOnUpdateScheduled();
2348}
2349
2350TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2351 // GIVEN continue status.
2352 ous_params_.status = EvalStatus::kContinue;
2353
2354 // THEN update should be scheduled.
2355 ous_params_.should_schedule_updates_be_called = true;
2356
2357 TestOnUpdateScheduled();
2358}
2359
2360TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2361 // GIVEN updates disabled.
2362 ous_params_.params = {.updates_enabled = false};
2363 // GIVEN succeeded status.
2364 ous_params_.status = EvalStatus::kSucceeded;
2365
2366 // THEN update should not be scheduled.
2367
2368 TestOnUpdateScheduled();
2369}
2370
2371TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2372 // GIVEN updates enabled.
2373 ous_params_.params = {.updates_enabled = true};
2374 // GIVEN succeeded status.
2375 ous_params_.status = EvalStatus::kSucceeded;
2376
2377 // THEN update should be called indicating status change.
2378 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2379 ous_params_.should_update_be_called = true;
2380
2381 TestOnUpdateScheduled();
2382}
2383
Amin Hassani9be122e2019-08-29 09:20:12 -07002384TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2385 UpdateEngineStatus status;
2386 attempter_.GetStatus(&status);
2387 EXPECT_FALSE(status.is_enterprise_rollback);
2388}
2389
2390TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2391 attempter_.install_plan_.reset(new InstallPlan);
2392 attempter_.install_plan_->is_rollback = false;
2393
2394 UpdateEngineStatus status;
2395 attempter_.GetStatus(&status);
2396 EXPECT_FALSE(status.is_enterprise_rollback);
2397}
2398
2399TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2400 attempter_.install_plan_.reset(new InstallPlan);
2401 attempter_.install_plan_->is_rollback = true;
2402
2403 UpdateEngineStatus status;
2404 attempter_.GetStatus(&status);
2405 EXPECT_TRUE(status.is_enterprise_rollback);
2406}
2407
Miriam Polzer0cf1acb2020-04-29 17:39:51 +02002408TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2409 UpdateEngineStatus status;
2410 attempter_.GetStatus(&status);
2411 EXPECT_FALSE(status.will_powerwash_after_reboot);
2412}
2413
2414TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2415 attempter_.install_plan_.reset(new InstallPlan);
2416 attempter_.install_plan_->powerwash_required = true;
2417
2418 UpdateEngineStatus status;
2419 attempter_.GetStatus(&status);
2420 EXPECT_TRUE(status.will_powerwash_after_reboot);
2421}
2422
2423TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2424 attempter_.install_plan_.reset(new InstallPlan);
2425 attempter_.install_plan_->is_rollback = true;
2426
2427 UpdateEngineStatus status;
2428 attempter_.GetStatus(&status);
2429 EXPECT_TRUE(status.will_powerwash_after_reboot);
2430}
2431
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002432TEST_F(UpdateAttempterTest, FutureEolTest) {
2433 EolDate eol_date = std::numeric_limits<int64_t>::max();
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002434 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002435 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2436 .WillOnce(
2437 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2438
2439 UpdateEngineStatus status;
2440 attempter_.GetStatus(&status);
2441 EXPECT_EQ(eol_date, status.eol_date);
2442}
2443
2444TEST_F(UpdateAttempterTest, PastEolTest) {
2445 EolDate eol_date = 1;
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002446 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002447 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2448 .WillOnce(
2449 DoAll(SetArgPointee<1>(EolDateToString(eol_date)), Return(true)));
2450
2451 UpdateEngineStatus status;
2452 attempter_.GetStatus(&status);
2453 EXPECT_EQ(eol_date, status.eol_date);
2454}
2455
2456TEST_F(UpdateAttempterTest, FailedEolTest) {
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002457 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(true));
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002458 EXPECT_CALL(*prefs_, GetString(kPrefsOmahaEolDate, _))
2459 .WillOnce(Return(false));
2460
2461 UpdateEngineStatus status;
2462 attempter_.GetStatus(&status);
Jae Hoon Kim2dfd35d2020-06-02 10:53:13 -07002463 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2464}
2465
2466TEST_F(UpdateAttempterTest, MissingEolTest) {
2467 EXPECT_CALL(*prefs_, Exists(kPrefsOmahaEolDate)).WillOnce(Return(false));
2468
2469 UpdateEngineStatus status;
2470 attempter_.GetStatus(&status);
2471 EXPECT_EQ(kEolDateInvalid, status.eol_date);
Jae Hoon Kim051627a2019-09-03 12:56:32 -07002472}
2473
Andrewe045aef2020-01-08 16:29:22 -08002474TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
Andrewe045aef2020-01-08 16:29:22 -08002475 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002476 FakePrefs fake_prefs;
2477 fake_system_state_.set_prefs(&fake_prefs);
Andrewe045aef2020-01-08 16:29:22 -08002478 attempter_.is_install_ = true;
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002479 attempter_.dlc_ids_ = {dlc_id};
Andrewe045aef2020-01-08 16:29:22 -08002480 attempter_.CalculateDlcParams();
2481
2482 OmahaRequestParams* params = fake_system_state_.request_params();
2483 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2484 OmahaRequestParams::AppParams dlc_app_params =
2485 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2486 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2487 EXPECT_EQ(false, dlc_app_params.send_ping);
2488 // When the DLC gets installed, a ping is not sent, therefore we don't store
2489 // the values sent by Omaha.
Andrew065d78d2020-04-07 15:43:07 -07002490 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002491 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002492 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2493 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002494 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002495 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewe045aef2020-01-08 16:29:22 -08002496}
2497
2498TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002499 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002500 FakePrefs fake_prefs;
2501 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002502 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002503 .WillOnce(
2504 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2505
2506 attempter_.is_install_ = false;
2507 attempter_.CalculateDlcParams();
2508
2509 OmahaRequestParams* params = fake_system_state_.request_params();
2510 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2511 OmahaRequestParams::AppParams dlc_app_params =
2512 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2513 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2514
2515 EXPECT_EQ(true, dlc_app_params.send_ping);
2516 EXPECT_EQ(0, dlc_app_params.ping_active);
2517 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2518 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2519}
2520
2521TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002522 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002523 MemoryPrefs prefs;
2524 fake_system_state_.set_prefs(&prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002525 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002526 .WillOnce(
2527 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2528
2529 // Write non numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002530 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002531 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002532 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002533 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002534 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002535 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002536 fake_system_state_.prefs()->SetString(active_key, "z2yz");
2537 fake_system_state_.prefs()->SetString(last_active_key, "z2yz");
2538 fake_system_state_.prefs()->SetString(last_rollcall_key, "z2yz");
Andrewe045aef2020-01-08 16:29:22 -08002539 attempter_.is_install_ = false;
2540 attempter_.CalculateDlcParams();
2541
2542 OmahaRequestParams* params = fake_system_state_.request_params();
2543 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2544 OmahaRequestParams::AppParams dlc_app_params =
2545 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2546 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2547
2548 EXPECT_EQ(true, dlc_app_params.send_ping);
2549 EXPECT_EQ(0, dlc_app_params.ping_active);
2550 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2551 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2552}
2553
2554TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
Andrewe045aef2020-01-08 16:29:22 -08002555 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002556 MemoryPrefs fake_prefs;
2557 fake_system_state_.set_prefs(&fake_prefs);
Amin Hassani2b68e6b2020-04-17 10:49:12 -07002558 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
Andrewe045aef2020-01-08 16:29:22 -08002559 .WillOnce(
2560 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2561
2562 // Write numeric values in the metadata files.
Andrew065d78d2020-04-07 15:43:07 -07002563 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002564 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002565 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002566 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002567 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002568 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002569
2570 fake_system_state_.prefs()->SetInt64(active_key, 1);
2571 fake_system_state_.prefs()->SetInt64(last_active_key, 78);
2572 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 99);
Andrewe045aef2020-01-08 16:29:22 -08002573 attempter_.is_install_ = false;
2574 attempter_.CalculateDlcParams();
2575
2576 OmahaRequestParams* params = fake_system_state_.request_params();
2577 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2578 OmahaRequestParams::AppParams dlc_app_params =
2579 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2580 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2581
2582 EXPECT_EQ(true, dlc_app_params.send_ping);
2583 EXPECT_EQ(1, dlc_app_params.ping_active);
2584 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2585 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2586}
Andrewa8d7df32020-03-15 20:10:01 -07002587
2588TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
Andrewa8d7df32020-03-15 20:10:01 -07002589 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002590 FakePrefs fake_prefs;
2591 fake_system_state_.set_prefs(&fake_prefs);
2592 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002593 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002594 auto last_active_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002595 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
Andrew065d78d2020-04-07 15:43:07 -07002596 auto last_rollcall_key = PrefsInterface::CreateSubKey(
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002597 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
Andrew065d78d2020-04-07 15:43:07 -07002598 fake_system_state_.prefs()->SetInt64(active_key, kPingInactiveValue);
2599 fake_system_state_.prefs()->SetInt64(last_active_key, 0);
2600 fake_system_state_.prefs()->SetInt64(last_rollcall_key, 0);
2601 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2602 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_active_key));
2603 EXPECT_TRUE(fake_system_state_.prefs()->Exists(last_rollcall_key));
Andrewa8d7df32020-03-15 20:10:01 -07002604
Andrew065d78d2020-04-07 15:43:07 -07002605 attempter_.dlc_ids_ = {dlc_id};
2606 attempter_.is_install_ = true;
Andrewa8d7df32020-03-15 20:10:01 -07002607 attempter_.CalculateDlcParams();
2608
Andrew065d78d2020-04-07 15:43:07 -07002609 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_active_key));
2610 EXPECT_FALSE(fake_system_state_.prefs()->Exists(last_rollcall_key));
2611 // Active key is set on install.
2612 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2613 int64_t temp_int;
2614 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
2615 EXPECT_EQ(temp_int, kPingActiveValue);
Andrewa8d7df32020-03-15 20:10:01 -07002616}
2617
2618TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
Andrewa8d7df32020-03-15 20:10:01 -07002619 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002620 FakePrefs fake_prefs;
2621 fake_system_state_.set_prefs(&fake_prefs);
Andrewa8d7df32020-03-15 20:10:01 -07002622 attempter_.SetDlcActiveValue(true, dlc_id);
Andrewa8d7df32020-03-15 20:10:01 -07002623 int64_t temp_int;
Andrew065d78d2020-04-07 15:43:07 -07002624 auto active_key =
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002625 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
Andrew065d78d2020-04-07 15:43:07 -07002626 EXPECT_TRUE(fake_system_state_.prefs()->Exists(active_key));
2627 EXPECT_TRUE(fake_system_state_.prefs()->GetInt64(active_key, &temp_int));
Andrewa8d7df32020-03-15 20:10:01 -07002628 EXPECT_EQ(temp_int, kPingActiveValue);
2629}
2630
2631TEST_F(UpdateAttempterTest, SetDlcInactive) {
Andrewa8d7df32020-03-15 20:10:01 -07002632 string dlc_id = "dlc0";
Andrew065d78d2020-04-07 15:43:07 -07002633 MemoryPrefs fake_prefs;
2634 fake_system_state_.set_prefs(&fake_prefs);
2635 auto sub_keys = {
2636 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2637 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002638 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002639 fake_system_state_.prefs()->SetInt64(key, 1);
2640 EXPECT_TRUE(fake_system_state_.prefs()->Exists(key));
2641 }
Andrewa8d7df32020-03-15 20:10:01 -07002642 attempter_.SetDlcActiveValue(false, dlc_id);
Andrew065d78d2020-04-07 15:43:07 -07002643 for (auto& sub_key : sub_keys) {
Jae Hoon Kimc1f36922020-05-11 18:20:18 -07002644 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
Andrew065d78d2020-04-07 15:43:07 -07002645 EXPECT_FALSE(fake_system_state_.prefs()->Exists(key));
2646 }
Andrewa8d7df32020-03-15 20:10:01 -07002647}
2648
Jae Hoon Kim7fdfbf12020-04-10 18:15:50 -07002649TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2650 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2651 attempter_.omaha_request_params_->set_dlc_apps_params(
2652 {{dlc_1, {.name = dlc_1, .updated = false}},
2653 {dlc_2, {.name = dlc_2}},
2654 {dlc_3, {.name = dlc_3, .updated = false}}});
2655 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2656}
2657
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002658} // namespace chromeos_update_engine