blob: 0e7435353def110787d43ff8c53e1a062d231c83 [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
Ben Chan02f7c1d2014-10-18 15:18:02 -070021#include <memory>
Jae Hoon Kimedb65502019-06-14 11:52:17 -070022#include <unordered_set>
Ben Chan02f7c1d2014-10-18 15:18:02 -070023
Ben Chan06c76a42014-09-05 08:21:06 -070024#include <base/files/file_util.h>
Alex Deymo0b3db6b2015-08-10 15:19:37 -070025#include <base/message_loop/message_loop.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070026#include <brillo/message_loops/base_message_loop.h>
27#include <brillo/message_loops/message_loop.h>
28#include <brillo/message_loops/message_loop_utils.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070029#include <gtest/gtest.h>
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +020030#include <policy/libpolicy.h>
31#include <policy/mock_device_policy.h>
Marton Hunyadye58bddb2018-04-10 20:27:26 +020032#include <policy/mock_libpolicy.h>
Darin Petkovf42cc1c2010-09-01 09:03:02 -070033
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070034#include "update_engine/common/constants.h"
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080035#include "update_engine/common/dlcservice_interface.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080036#include "update_engine/common/fake_clock.h"
37#include "update_engine/common/fake_prefs.h"
Alex Deymo14fd1ec2016-02-24 22:03:57 -080038#include "update_engine/common/mock_action.h"
39#include "update_engine/common/mock_action_processor.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080040#include "update_engine/common/mock_http_fetcher.h"
41#include "update_engine/common/mock_prefs.h"
42#include "update_engine/common/platform_constants.h"
43#include "update_engine/common/prefs.h"
44#include "update_engine/common/test_utils.h"
45#include "update_engine/common/utils.h"
Gilad Arnold5bb4c902014-04-10 12:32:13 -070046#include "update_engine/fake_system_state.h"
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -070047#include "update_engine/libcurl_http_fetcher.h"
David Zeuthen8f191b22013-08-06 12:27:50 -070048#include "update_engine/mock_p2p_manager.h"
Jay Srinivasan6f6ea002012-12-14 11:26:28 -080049#include "update_engine/mock_payload_state.h"
Aaron Wood9321f502017-09-07 11:18:54 -070050#include "update_engine/mock_service_observer.h"
Alex Deymo39910dc2015-11-09 17:04:30 -080051#include "update_engine/payload_consumer/filesystem_verifier_action.h"
52#include "update_engine/payload_consumer/install_plan.h"
53#include "update_engine/payload_consumer/payload_constants.h"
54#include "update_engine/payload_consumer/postinstall_runner_action.h"
Amin Hassani0882a512018-04-05 16:25:44 -070055#include "update_engine/update_boot_flags_action.h"
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070056#include "update_engine/update_manager/mock_update_manager.h"
Darin Petkovf42cc1c2010-09-01 09:03:02 -070057
David Zeuthen985b1122013-10-09 12:13:15 -070058using base::Time;
59using base::TimeDelta;
Aaron Woodbf5a2522017-10-04 10:58:36 -070060using chromeos_update_manager::EvalStatus;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -070061using chromeos_update_manager::MockUpdateManager;
Adolfo Victoria497044c2018-07-18 07:51:42 -070062using chromeos_update_manager::StagingSchedule;
Aaron Woodbf5a2522017-10-04 10:58:36 -070063using chromeos_update_manager::UpdateCheckParams;
Adolfo Victoria497044c2018-07-18 07:51:42 -070064using policy::DevicePolicy;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070065using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070066using std::unique_ptr;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070067using std::unordered_set;
Xiaochu Liu88d90382018-08-29 16:09:11 -070068using std::vector;
Aaron Woodbf5a2522017-10-04 10:58:36 -070069using testing::_;
Darin Petkov36275772010-10-01 11:40:57 -070070using testing::DoAll;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070071using testing::Field;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070072using testing::InSequence;
Jae Hoon Kimedb65502019-06-14 11:52:17 -070073using testing::Invoke;
Darin Petkov2dd01092010-10-08 15:43:05 -070074using testing::Ne;
Darin Petkov9c096d62010-11-17 14:49:04 -080075using testing::NiceMock;
Amin Hassanid3f4bea2018-04-30 14:52:40 -070076using testing::Pointee;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070077using testing::Property;
78using testing::Return;
Gilad Arnold74b5f552014-10-07 08:17:16 -070079using testing::ReturnPointee;
Marton Hunyadye58bddb2018-04-10 20:27:26 +020080using testing::ReturnRef;
Alex Deymo2c0db7b2014-11-04 12:23:39 -080081using testing::SaveArg;
Ben Chan672c1f52017-10-23 15:41:39 -070082using testing::SetArgPointee;
Aaron Woodbf5a2522017-10-04 10:58:36 -070083using update_engine::UpdateAttemptFlags;
Aaron Wood7f92e2b2017-08-28 14:51:21 -070084using update_engine::UpdateEngineStatus;
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -070085using update_engine::UpdateStatus;
Darin Petkovf42cc1c2010-09-01 09:03:02 -070086
87namespace chromeos_update_engine {
88
Xiaochu Liu8ba486f2018-11-06 11:14:10 -080089namespace {
90
Jae Hoon Kimc437ea52019-07-11 11:20:38 -070091const UpdateStatus kNonIdleUpdateStatuses[] = {
92 UpdateStatus::CHECKING_FOR_UPDATE,
93 UpdateStatus::UPDATE_AVAILABLE,
94 UpdateStatus::DOWNLOADING,
95 UpdateStatus::VERIFYING,
96 UpdateStatus::FINALIZING,
97 UpdateStatus::UPDATED_NEED_REBOOT,
98 UpdateStatus::REPORTING_ERROR_EVENT,
99 UpdateStatus::ATTEMPTING_ROLLBACK,
100 UpdateStatus::DISABLED,
101 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
102};
103
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700104struct CheckForUpdateTestParams {
105 // Setups + Inputs:
106 UpdateStatus status = UpdateStatus::IDLE;
107 string app_version = "fake_app_version";
108 string omaha_url = "fake_omaha_url";
109 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
110 bool is_official_build = true;
111 bool are_dev_features_enabled = false;
112
113 // Expects:
114 string expected_forced_app_version = "";
115 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700116 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700117 bool expected_result = true;
118};
119
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700120struct OnUpdateScheduledTestParams {
121 // Setups + Inputs:
122 UpdateCheckParams params = {};
123 EvalStatus status = EvalStatus::kFailed;
124 // Expects:
125 UpdateStatus exit_status = UpdateStatus::IDLE;
126 bool should_schedule_updates_be_called = false;
127 bool should_update_be_called = false;
128};
129
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700130struct ProcessingDoneTestParams {
131 // Setups + Inputs:
132 bool is_install = false;
133 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
134 ActionProcessor* processor = nullptr;
135 ErrorCode code = ErrorCode::kSuccess;
136
137 // Expects:
138 const bool kExpectedIsInstall = false;
139 bool should_schedule_updates_be_called = true;
140 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
141};
142
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800143class MockDlcService : public DlcServiceInterface {
144 public:
145 MOCK_METHOD1(GetInstalled, bool(vector<string>*));
146};
147
148} // namespace
149
Marton Hunyadya0302682018-05-16 18:52:13 +0200150const char kRollbackVersion[] = "10575.39.2";
151
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700152// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700153// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700154// methods.
155class UpdateAttempterUnderTest : public UpdateAttempter {
156 public:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700157 explicit UpdateAttempterUnderTest(SystemState* system_state)
158 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700159
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700160 void Update(const std::string& app_version,
161 const std::string& omaha_url,
162 const std::string& target_channel,
163 const std::string& target_version_prefix,
164 bool rollback_allowed,
165 bool rollback_data_save_requested,
166 int rollback_allowed_milestones,
167 bool obey_proxies,
168 bool interactive) override {
169 update_called_ = true;
170 if (do_update_) {
171 UpdateAttempter::Update(app_version,
172 omaha_url,
173 target_channel,
174 target_version_prefix,
175 rollback_allowed,
176 rollback_data_save_requested,
177 rollback_allowed_milestones,
178 obey_proxies,
179 interactive);
180 return;
181 }
182 LOG(INFO) << "[TEST] Update() disabled.";
183 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
184 }
185
186 void DisableUpdate() { do_update_ = false; }
187
188 bool WasUpdateCalled() const { return update_called_; }
189
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700190 // Wrap the update scheduling method, allowing us to opt out of scheduled
191 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700192 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700193 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700194 if (do_schedule_updates_)
195 return UpdateAttempter::ScheduleUpdates();
196 LOG(INFO) << "[TEST] Update scheduling disabled.";
197 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700198 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700199 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700200
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700201 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
202
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700203 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700204 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700205
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700206 // Need to expose following private members of |UpdateAttempter| for tests.
207 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700208 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800209
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700210 // Need to expose |waiting_for_scheduled_check_| for testing.
211 void SetWaitingForScheduledCheck(bool waiting) {
212 waiting_for_scheduled_check_ = waiting;
213 }
214
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700215 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700216 // Used for overrides of |Update()|.
217 bool update_called_ = false;
218 bool do_update_ = true;
219
220 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700221 bool schedule_updates_called_ = false;
222 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700223};
224
225class UpdateAttempterTest : public ::testing::Test {
226 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700227 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600228 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300229 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700230 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700231 fake_system_state_.set_connection_manager(&mock_connection_manager);
232 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800233 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700234 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700235 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700236
Alex Deymo33e91e72015-12-01 18:26:08 -0300237 certificate_checker_.Init();
238
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800239 attempter_.set_forced_update_pending_callback(
240 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700241 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700242 attempter_.Init();
Jay Srinivasan43488792012-06-19 00:25:31 -0700243 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700244
Alex Deymo610277e2014-11-11 21:18:11 -0800245 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700246 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700247 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700248 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700249 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700250 EXPECT_EQ(0.0, attempter_.download_progress_);
251 EXPECT_EQ(0, attempter_.last_checked_time_);
252 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700253 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800254 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700255 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700256 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700257
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700258 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700259 actual_using_p2p_for_downloading_ = false;
260 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
261 SetUsingP2PForDownloading(_))
262 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
263 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
264 GetUsingP2PForDownloading())
265 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
266 actual_using_p2p_for_sharing_ = false;
267 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
268 SetUsingP2PForSharing(_))
269 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
270 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
271 GetUsingP2PForDownloading())
272 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700273 }
274
Alex Deymo60ca1a72015-06-18 18:19:15 -0700275 public:
276 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200277
Alex Deymo60ca1a72015-06-18 18:19:15 -0700278 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800279 void UpdateTestStart();
280 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700281 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700282 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700283 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700284 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700285 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700286 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700287 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700288 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700289 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700290 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700291 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700292 void SessionIdTestChange();
293 void SessionIdTestEnforceEmptyStrPingOmaha();
294 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700295 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200296 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200297 void ResetRollbackHappenedStart(bool is_consumer,
298 bool is_policy_available,
299 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700300 // Staging related callbacks.
301 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
302 void CheckStagingOff();
303 void StagingSetsPrefsAndTurnsOffScatteringStart();
304 void StagingOffIfInteractiveStart();
305 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700306
Gilad Arnold74b5f552014-10-07 08:17:16 -0700307 bool actual_using_p2p_for_downloading() {
308 return actual_using_p2p_for_downloading_;
309 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800310 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700311
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700312 // |CheckForUpdate()| related member functions.
313 void TestCheckForUpdate();
314
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700315 // |OnUpdateScheduled()| related member functions.
316 void TestOnUpdateScheduled();
317
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700318 // |ProcessingDone()| related member functions.
319 void TestProcessingDone();
320
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700321 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700322 brillo::BaseMessageLoop loop_{&base_loop_};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700323
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700324 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700325 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300326 OpenSSLWrapper openssl_wrapper_;
327 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800328 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700329 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700330
Alex Deymo8427b4a2014-11-05 14:00:32 -0800331 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700332 NiceMock<MockPrefs>*
333 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800334 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700335
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700336 // |CheckForUpdate()| test params.
337 CheckForUpdateTestParams cfu_params_;
338
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700339 // |OnUpdateScheduled()| test params.
340 OnUpdateScheduledTestParams ous_params_;
341
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700342 // |ProcessingDone()| test params.
343 ProcessingDoneTestParams pd_params_;
344
Gilad Arnold74b5f552014-10-07 08:17:16 -0700345 bool actual_using_p2p_for_downloading_;
346 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700347};
348
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700349void UpdateAttempterTest::TestCheckForUpdate() {
350 // Setup
351 attempter_.status_ = cfu_params_.status;
352 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
353 cfu_params_.is_official_build);
354 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
355 cfu_params_.are_dev_features_enabled);
356
357 // Invocation
358 EXPECT_EQ(
359 cfu_params_.expected_result,
360 attempter_.CheckForUpdate(
361 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
362
363 // Verify
364 EXPECT_EQ(cfu_params_.expected_forced_app_version,
365 attempter_.forced_app_version());
366 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
367 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700368 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
369 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700370}
371
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -0700372void UpdateAttempterTest::TestProcessingDone() {
373 // Setup
374 attempter_.DisableScheduleUpdates();
375 attempter_.is_install_ = pd_params_.is_install;
376 attempter_.status_ = pd_params_.status;
377
378 // Invocation
379 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
380
381 // Verify
382 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
383 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
384 attempter_.WasScheduleUpdatesCalled());
385 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
386}
387
Alex Deymo60ca1a72015-06-18 18:19:15 -0700388void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700389 loop_.PostTask(
390 FROM_HERE,
391 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
392 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700393}
394
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700395void UpdateAttempterTest::SessionIdTestChange() {
396 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
397 const auto old_session_id = attempter_.session_id_;
398 attempter_.Update("", "", "", "", false, false, 0, false, false);
399 EXPECT_NE(old_session_id, attempter_.session_id_);
400 ScheduleQuitMainLoop();
401}
402
403TEST_F(UpdateAttempterTest, SessionIdTestChange) {
404 loop_.PostTask(FROM_HERE,
405 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
406 base::Unretained(this)));
407 loop_.Run();
408}
409
410void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
411 // The |session_id_| should not be changed and should remain as an empty
412 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
413 // and |PingOmaha()| is called.
414 attempter_.DisableScheduleUpdates();
415 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
416 const auto old_session_id = attempter_.session_id_;
417 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
418 if (aa->Type() == OmahaRequestAction::StaticType()) {
419 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
420 }
421 };
422 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
423 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
424 EXPECT_CALL(*processor_, StartProcessing());
425 attempter_.PingOmaha();
426 EXPECT_EQ(old_session_id, attempter_.session_id_);
427 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
428 ScheduleQuitMainLoop();
429}
430
431TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
432 loop_.PostTask(
433 FROM_HERE,
434 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
435 base::Unretained(this)));
436 loop_.Run();
437}
438
439void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
440 // All session IDs passed into |OmahaRequestActions| should be enforced to
441 // have the same value in |BuildUpdateActions()|.
442 unordered_set<string> session_ids;
443 // Gather all the session IDs being passed to |OmahaRequestActions|.
444 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
445 if (aa->Type() == OmahaRequestAction::StaticType())
446 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
447 };
448 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
449 .WillRepeatedly(Invoke(CheckSessionId));
450 attempter_.BuildUpdateActions(false);
451 // Validate that all the session IDs are the same.
452 EXPECT_EQ(1, session_ids.size());
453 ScheduleQuitMainLoop();
454}
455
456TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
457 loop_.PostTask(
458 FROM_HERE,
459 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
460 base::Unretained(this)));
461 loop_.Run();
462}
463
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700464void UpdateAttempterTest::SessionIdTestInDownloadAction() {
465 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
466 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
467 string header_value;
468 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
469 if (aa->Type() == DownloadAction::StaticType()) {
470 DownloadAction* da = static_cast<DownloadAction*>(aa);
471 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
472 &header_value));
473 }
474 };
475 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
476 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
477 attempter_.BuildUpdateActions(false);
478 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
479 EXPECT_EQ(attempter_.session_id_, header_value);
480 ScheduleQuitMainLoop();
481}
482
483TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
484 loop_.PostTask(FROM_HERE,
485 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
486 base::Unretained(this)));
487 loop_.Run();
488}
489
Darin Petkov1b003102010-11-30 10:18:36 -0800490TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700491 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800492 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700493 DownloadAction action(prefs_,
494 nullptr,
495 nullptr,
496 nullptr,
497 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700498 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800499 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700500 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700501 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700502 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700503 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800504}
505
506TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800507 MockAction action;
508 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700509 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800510 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800511 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700512 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
513 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800514}
515
Aaron Wood9321f502017-09-07 11:18:54 -0700516TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
517 // Simple test case, where all the values match (nothing was skipped)
518 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
519 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
520 uint64_t bytes_received_1 = bytes_progressed_1;
521 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
522 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
523
524 double progress_1 =
525 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
526 double progress_2 =
527 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
528
529 EXPECT_EQ(0.0, attempter_.download_progress_);
530 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700531 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700532 attempter_.new_payload_size_ = bytes_total;
533 NiceMock<MockServiceObserver> observer;
534 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700535 SendStatusUpdate(AllOf(
536 Field(&UpdateEngineStatus::progress, progress_1),
537 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
538 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700539 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700540 SendStatusUpdate(AllOf(
541 Field(&UpdateEngineStatus::progress, progress_2),
542 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
543 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700544 attempter_.AddObserver(&observer);
545 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
546 EXPECT_EQ(progress_1, attempter_.download_progress_);
547 // This iteration validates that a later set of updates to the variables are
548 // properly handled (so that |getStatus()| will return the same progress info
549 // as the callback is receiving.
550 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
551 EXPECT_EQ(progress_2, attempter_.download_progress_);
552}
553
554TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700555 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700556 // first bytes are received.
557 uint64_t bytes_progressed = 1024 * 1024; // 1MB
558 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
559 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
560 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
561 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700562 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700563 attempter_.new_payload_size_ = bytes_total;
564 EXPECT_EQ(0.0, attempter_.download_progress_);
565 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700566 EXPECT_CALL(observer,
567 SendStatusUpdate(AllOf(
568 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
569 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700570 attempter_.AddObserver(&observer);
571 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
572 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
573}
574
575TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
576 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700577 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700578 uint64_t bytes_progressed = 0; // ignored
579 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
580 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
581 attempter_.status_ = UpdateStatus::DOWNLOADING;
582 attempter_.new_payload_size_ = bytes_total;
583 EXPECT_EQ(0.0, attempter_.download_progress_);
584 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700585 EXPECT_CALL(observer,
586 SendStatusUpdate(AllOf(
587 Field(&UpdateEngineStatus::progress, 1.0),
588 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
589 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700590 attempter_.AddObserver(&observer);
591 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
592 EXPECT_EQ(1.0, attempter_.download_progress_);
593}
594
Darin Petkov1b003102010-11-30 10:18:36 -0800595TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700596 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800597 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800598 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700599 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800600 ObjectCollectorAction<OmahaResponse> collector_action;
601 BondActions(&action, &collector_action);
602 OmahaResponse response;
603 response.poll_interval = 234;
604 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800605 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700606 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800607 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700608 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800609 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700610 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800611}
612
Alex Deymo30534502015-07-20 15:06:33 -0700613TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700614 FakePrefs fake_prefs;
615 string boot_id;
616 EXPECT_TRUE(utils::GetBootId(&boot_id));
617 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
618 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700619 attempter_.Init();
620 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700621}
622
623TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700624 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700625 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700626
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700627 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800628 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700629 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700630 EXPECT_EQ(ErrorCode::kOmahaRequestError,
631 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700632 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800633 EXPECT_EQ(
634 ErrorCode::kOmahaResponseHandlerError,
635 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Sen Jiange6e4bb92016-04-05 14:59:12 -0700636 FilesystemVerifierAction filesystem_verifier_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800637 EXPECT_EQ(
638 ErrorCode::kFilesystemVerifierError,
639 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300640 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700641 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800642 EXPECT_EQ(
643 ErrorCode::kPostinstallRunnerError,
644 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800645 MockAction action_mock;
646 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700647 EXPECT_EQ(ErrorCode::kError,
648 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700649}
650
Darin Petkov36275772010-10-01 11:40:57 -0700651TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700652 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800653 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700654 .WillOnce(Return(false));
655 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700656 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800657 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800658 .WillOnce(
659 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
660 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700661 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700662 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800663 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800664 .WillOnce(
665 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
666 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700667 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700668 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800669 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700670 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700671 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700672}
673
674TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800675 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700676 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700677 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
678 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800679 .WillOnce(
680 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
681 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800682 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700683 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800684 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700685 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800686 EXPECT_CALL(*prefs_,
687 SetInt64(kPrefsDeltaUpdateFailures,
688 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
689 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700690 attempter_.MarkDeltaUpdateFailure();
691}
692
Darin Petkov1b003102010-11-30 10:18:36 -0800693TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
694 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
695 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700696 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800697 .Times(0);
698 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700699 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800700 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700701 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700702 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700703 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800704 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700705 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800706}
707
708TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
709 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700710 EnqueueAction(Pointee(Property(
711 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700712 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700713 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700714 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800715 attempter_.error_event_.reset(new OmahaEvent(
716 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800717 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700718 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800719}
720
Darin Petkove6ef2f82011-03-07 17:31:11 -0800721namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700722// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200723vector<string> GetUpdateActionTypes() {
724 return {OmahaRequestAction::StaticType(),
725 OmahaResponseHandlerAction::StaticType(),
726 UpdateBootFlagsAction::StaticType(),
727 OmahaRequestAction::StaticType(),
728 DownloadAction::StaticType(),
729 OmahaRequestAction::StaticType(),
730 FilesystemVerifierAction::StaticType(),
731 PostinstallRunnerAction::StaticType(),
732 OmahaRequestAction::StaticType()};
733}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700734
735// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200736vector<string> GetRollbackActionTypes() {
737 return {InstallPlanAction::StaticType(),
738 PostinstallRunnerAction::StaticType()};
739}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700740
Adolfo Victoria497044c2018-07-18 07:51:42 -0700741const StagingSchedule kValidStagingSchedule = {
742 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
743
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700744} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800745
746void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700747 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700748
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700749 // Expect that the device policy is loaded by the |UpdateAttempter| at some
750 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100751 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700752 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800753 .Times(testing::AtLeast(1))
754 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100755 attempter_.policy_provider_.reset(
756 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700757
758 {
759 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200760 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700761 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700762 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200763 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700764 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700765 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700766 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700767
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800768 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700769 loop_.PostTask(FROM_HERE,
770 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
771 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800772}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700773
Darin Petkove6ef2f82011-03-07 17:31:11 -0800774void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700775 EXPECT_EQ(0, attempter_.http_response_code());
776 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700777 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700778 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800779}
780
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800781void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
782 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700783 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100784 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700785 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100786 fake_system_state_.set_device_policy(device_policy.get());
787 if (enterprise_rollback) {
788 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800789 EXPECT_CALL(*device_policy, GetOwner(_))
790 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100791 } else {
792 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800793 EXPECT_CALL(*device_policy, GetOwner(_))
794 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
795 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100796 }
797
798 attempter_.policy_provider_.reset(
799 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700800
Alex Deymo763e7db2015-08-27 21:08:08 -0700801 if (valid_slot) {
802 BootControlInterface::Slot rollback_slot = 1;
803 LOG(INFO) << "Test Mark Bootable: "
804 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700805 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
806 true);
Don Garrett6646b442013-11-13 15:29:11 -0800807 }
808
Chris Sosa28e479c2013-07-12 11:39:53 -0700809 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700810
Chris Sosad38b1132014-03-25 10:43:59 -0700811 // We only allow rollback on devices that are not enterprise enrolled and
812 // which have a valid slot to rollback to.
813 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800814 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700815 }
816
Chris Sosa28e479c2013-07-12 11:39:53 -0700817 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700818 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200819 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700820 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200821 EnqueueAction(Pointee(
822 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700823 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700824 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700825
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700826 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700827 loop_.PostTask(FROM_HERE,
828 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
829 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700830 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700831 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700832 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700833 }
834}
835
836void UpdateAttempterTest::RollbackTestVerify() {
837 // Verifies the actions that were enqueued.
838 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700839 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700840 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
841 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700842 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700843}
844
Darin Petkove6ef2f82011-03-07 17:31:11 -0800845TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700846 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700847 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700848}
849
Chris Sosa76a29ae2013-07-11 17:59:24 -0700850TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700851 loop_.PostTask(FROM_HERE,
852 base::Bind(&UpdateAttempterTest::RollbackTestStart,
853 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800854 false,
855 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700856 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700857}
858
Don Garrett6646b442013-11-13 15:29:11 -0800859TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700860 loop_.PostTask(FROM_HERE,
861 base::Bind(&UpdateAttempterTest::RollbackTestStart,
862 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800863 false,
864 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700865 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800866}
867
Chris Sosa76a29ae2013-07-11 17:59:24 -0700868TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700869 loop_.PostTask(FROM_HERE,
870 base::Bind(&UpdateAttempterTest::RollbackTestStart,
871 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800872 true,
873 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700874 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700875}
876
Thieu Le116fda32011-04-19 11:01:54 -0700877void UpdateAttempterTest::PingOmahaTestStart() {
878 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700879 EnqueueAction(Pointee(Property(
880 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700881 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700882 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700883 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700884}
885
886TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700887 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700888 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700889 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700890 // testing, which is more permissive than we want to handle here.
891 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700892 loop_.PostTask(FROM_HERE,
893 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
894 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700895 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700896 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700897 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700898}
899
Darin Petkov18c7bce2011-06-16 14:07:00 -0700900TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800901 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700902 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700903 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700904 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700905 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
906 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700907 EXPECT_EQ(
908 static_cast<ErrorCode>(static_cast<int>(kCode) |
909 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
910 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700911}
912
913TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700914 attempter_.install_plan_.reset(new InstallPlan);
915 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800916 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700917 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700918 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700919 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700920 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
921 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700922 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800923 static_cast<ErrorCode>(static_cast<int>(kCode) |
924 static_cast<int>(ErrorCode::kResumedFlag) |
925 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700926 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700927}
928
David Zeuthen8f191b22013-08-06 12:27:50 -0700929TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
930 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700931 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700932 mock_p2p_manager.fake().SetP2PEnabled(false);
933 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
934 attempter_.UpdateEngineStarted();
935}
936
937TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
938 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700939 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700940 mock_p2p_manager.fake().SetP2PEnabled(true);
941 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
942 attempter_.UpdateEngineStarted();
943}
944
945TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
946 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700947 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700948 mock_p2p_manager.fake().SetP2PEnabled(true);
949 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700950 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700951 attempter_.UpdateEngineStarted();
952}
953
954TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700955 loop_.PostTask(FROM_HERE,
956 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
957 base::Unretained(this)));
958 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700959}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700960
David Zeuthen8f191b22013-08-06 12:27:50 -0700961void UpdateAttempterTest::P2PNotEnabledStart() {
962 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700963 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700964 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700965 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700966 mock_p2p_manager.fake().SetP2PEnabled(false);
967 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800968 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700969 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700970 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700971 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700972}
973
974TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700975 loop_.PostTask(FROM_HERE,
976 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
977 base::Unretained(this)));
978 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700979}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700980
David Zeuthen8f191b22013-08-06 12:27:50 -0700981void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700982 // If P2P is enabled, but starting it fails ensure we don't do
983 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700984 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700985 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700986 mock_p2p_manager.fake().SetP2PEnabled(true);
987 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
988 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
989 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800990 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700991 EXPECT_FALSE(actual_using_p2p_for_downloading());
992 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700993 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700994}
995
996TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700997 loop_.PostTask(
998 FROM_HERE,
999 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
1000 base::Unretained(this)));
1001 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001002}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001003
David Zeuthen8f191b22013-08-06 12:27:50 -07001004void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001005 // If P2P is enabled, starting it works but housekeeping fails, ensure
1006 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001007 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001008 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001009 mock_p2p_manager.fake().SetP2PEnabled(true);
1010 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1011 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001012 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001013 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001014 EXPECT_FALSE(actual_using_p2p_for_downloading());
1015 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001016 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001017}
1018
1019TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001020 loop_.PostTask(FROM_HERE,
1021 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1022 base::Unretained(this)));
1023 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001024}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001025
David Zeuthen8f191b22013-08-06 12:27:50 -07001026void UpdateAttempterTest::P2PEnabledStart() {
1027 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001028 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001029 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001030 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -07001031 mock_p2p_manager.fake().SetP2PEnabled(true);
1032 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1033 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001034 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001035 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001036 EXPECT_TRUE(actual_using_p2p_for_downloading());
1037 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001038 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001039}
1040
1041TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001042 loop_.PostTask(FROM_HERE,
1043 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1044 base::Unretained(this)));
1045 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -07001046}
Alex Deymo60ca1a72015-06-18 18:19:15 -07001047
David Zeuthen8f191b22013-08-06 12:27:50 -07001048void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1049 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001050 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001051 // For an interactive check, if P2P is enabled and starting it
1052 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001053 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001054 mock_p2p_manager.fake().SetP2PEnabled(true);
1055 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1056 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001057 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001058 attempter_.Update("",
1059 "",
1060 "",
1061 "",
1062 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001063 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001064 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001065 false,
1066 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001067 EXPECT_FALSE(actual_using_p2p_for_downloading());
1068 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001069 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001070}
1071
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001072TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001073 loop_.PostTask(
1074 FROM_HERE,
1075 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1076 base::Unretained(this)));
1077 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001078}
1079
1080// Tests that the scatter_factor_in_seconds value is properly fetched
1081// from the device policy.
1082void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001083 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001084
Igor9fd76b62017-12-11 15:24:18 +01001085 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001086 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001087 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001088
1089 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001090 .WillRepeatedly(
1091 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001092
Igor9fd76b62017-12-11 15:24:18 +01001093 attempter_.policy_provider_.reset(
1094 new policy::PolicyProvider(std::move(device_policy)));
1095
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001096 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001097 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1098
Alex Deymo60ca1a72015-06-18 18:19:15 -07001099 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001100}
1101
1102TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001103 loop_.PostTask(
1104 FROM_HERE,
1105 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1106 base::Unretained(this)));
1107 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108}
1109
1110void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1111 // Tests that the scatter_factor_in_seconds value is properly fetched
1112 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001113 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001114 FakePrefs fake_prefs;
1115 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001116
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001117 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001118
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001119 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001120
Ben Chan9abb7632014-08-07 00:10:53 -07001121 int64_t scatter_factor_in_seconds = 10;
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
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001134 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001135 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1136
1137 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001138 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001139
Ben Chan9abb7632014-08-07 00:10:53 -07001140 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001141 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001142 EXPECT_EQ(initial_value - 1, new_value);
1143
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001144 EXPECT_TRUE(
1145 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001146
1147 // However, if the count is already 0, it's not decremented. Test that.
1148 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001149 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001150 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001151 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1152 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001153 EXPECT_EQ(initial_value, new_value);
1154
Alex Deymo60ca1a72015-06-18 18:19:15 -07001155 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001156}
1157
Jay Srinivasan08fce042012-06-07 16:31:01 -07001158TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001159 loop_.PostTask(
1160 FROM_HERE,
1161 base::Bind(
1162 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1163 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001164 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001165}
1166
1167void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1168 // Tests that no scattering logic is enabled if the update check
1169 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001170 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001171 FakePrefs fake_prefs;
1172 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001173
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001174 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001175 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001176
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001177 EXPECT_TRUE(
1178 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001179 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001180
1181 // make sure scatter_factor is non-zero as scattering is disabled
1182 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001183 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001184
Igor9fd76b62017-12-11 15:24:18 +01001185 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001186 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001187 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001188
1189 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001190 .WillRepeatedly(
1191 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001192
Igor9fd76b62017-12-11 15:24:18 +01001193 attempter_.policy_provider_.reset(
1194 new policy::PolicyProvider(std::move(device_policy)));
1195
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001196 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001197 attempter_.Update("",
1198 "",
1199 "",
1200 "",
1201 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001202 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001203 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001204 false,
1205 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001206 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1207
1208 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001209 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001210 EXPECT_FALSE(
1211 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001212 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001213 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1214 EXPECT_FALSE(
1215 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001216 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001217
Alex Deymo60ca1a72015-06-18 18:19:15 -07001218 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001219}
1220
Adolfo Victoria497044c2018-07-18 07:51:42 -07001221void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1222 FakePrefs* prefs) {
1223 attempter_.prefs_ = prefs;
1224 fake_system_state_.set_prefs(prefs);
1225
1226 int64_t initial_value = 8;
1227 EXPECT_TRUE(
1228 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1229 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1230 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1231
1232 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1233 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1234 fake_system_state_.set_device_policy(device_policy.get());
1235 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1236 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1237
1238 attempter_.policy_provider_.reset(
1239 new policy::PolicyProvider(std::move(device_policy)));
1240}
1241
1242TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1243 loop_.PostTask(
1244 FROM_HERE,
1245 base::Bind(
1246 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1247 base::Unretained(this)));
1248 loop_.Run();
1249}
1250
1251void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1252 // Tests that staging sets its prefs properly and turns off scattering.
1253 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1254 FakePrefs fake_prefs;
1255 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1256
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001257 attempter_.Update("", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001258 // Check that prefs have the correct values.
1259 int64_t update_count;
1260 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1261 int64_t waiting_time_days;
1262 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1263 &waiting_time_days));
1264 EXPECT_GT(waiting_time_days, 0);
1265 // Update count should have been decremented.
1266 EXPECT_EQ(7, update_count);
1267 // Check that Omaha parameters were updated correctly.
1268 EXPECT_TRUE(
1269 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1270 EXPECT_TRUE(
1271 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1272 EXPECT_EQ(waiting_time_days,
1273 attempter_.omaha_request_params_->waiting_period().InDays());
1274 // Check class variables.
1275 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1276 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1277 // Check that scattering is turned off
1278 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1279 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1280
1281 ScheduleQuitMainLoop();
1282}
1283
1284void UpdateAttempterTest::CheckStagingOff() {
1285 // Check that all prefs were removed.
1286 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1287 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1288 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1289 // Check that the Omaha parameters have the correct value.
1290 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1291 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1292 attempter_.staging_wait_time_);
1293 EXPECT_FALSE(
1294 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1295 EXPECT_FALSE(
1296 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1297 // Check that scattering is turned off too.
1298 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1299}
1300
1301TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1302 loop_.PostTask(FROM_HERE,
1303 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1304 base::Unretained(this)));
1305 loop_.Run();
1306}
1307
1308void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1309 // Tests that staging is turned off when an interactive update is requested.
1310 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1311 FakePrefs fake_prefs;
1312 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1313
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001314 attempter_.Update(
1315 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001316 CheckStagingOff();
1317
1318 ScheduleQuitMainLoop();
1319}
1320
1321TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1322 loop_.PostTask(FROM_HERE,
1323 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1324 base::Unretained(this)));
1325 loop_.Run();
1326}
1327
1328void UpdateAttempterTest::StagingOffIfOobeStart() {
1329 // Tests that staging is turned off if OOBE hasn't been completed.
1330 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1331 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1332 FakePrefs fake_prefs;
1333 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1334
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001335 attempter_.Update(
1336 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001337 CheckStagingOff();
1338
1339 ScheduleQuitMainLoop();
1340}
1341
David Zeuthen985b1122013-10-09 12:13:15 -07001342// Checks that we only report daily metrics at most every 24 hours.
1343TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1344 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001345 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001346
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001347 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001348 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001349
1350 Time epoch = Time::FromInternalValue(0);
1351 fake_clock.SetWallclockTime(epoch);
1352
1353 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1354 // we should report.
1355 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1356 // We should not report again if no time has passed.
1357 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1358
1359 // We should not report if only 10 hours has passed.
1360 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1361 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1362
1363 // We should not report if only 24 hours - 1 sec has passed.
1364 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1365 TimeDelta::FromSeconds(1));
1366 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1367
1368 // We should report if 24 hours has passed.
1369 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1370 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1371
1372 // But then we should not report again..
1373 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1374
1375 // .. until another 24 hours has passed
1376 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1377 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1378 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1379 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1380 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1381
1382 // .. and another 24 hours
1383 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1384 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1385 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1386 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1387 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1388
1389 // If the span between time of reporting and present time is
1390 // negative, we report. This is in order to reset the timestamp and
1391 // avoid an edge condition whereby a distant point in the future is
1392 // in the state variable resulting in us never ever reporting again.
1393 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1394 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1395 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1396
1397 // In this case we should not update until the clock reads 71 + 24 = 95.
1398 // Check that.
1399 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1400 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1401 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1402 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1403 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001404}
1405
David Zeuthen3c55abd2013-10-14 12:48:03 -07001406TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001407 FakeClock fake_clock;
1408 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001409 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001410 FakePrefs fake_prefs;
1411 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001412 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001413
1414 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001415 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001416
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001417 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001418
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001419 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001420 EXPECT_EQ(boot_time.ToTimeT(), 42);
1421}
1422
David Pursell02c18642014-11-06 11:26:11 -08001423TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1424 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1425 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1426}
1427
1428TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1429 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001430 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001431 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1432}
1433
1434TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1435 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001436 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001437 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1438}
1439
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001440// TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1441// When adding, remove older tests related to |CheckForInstall()|.
1442TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1443 for (const auto status : kNonIdleUpdateStatuses) {
1444 // GIVEN a non-idle status.
1445 attempter_.status_ = status;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001446
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001447 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1448 }
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001449}
1450
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001451TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1452 for (const auto status : kNonIdleUpdateStatuses) {
1453 // GIVEN a non-idle status.
1454 cfu_params_.status = status;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001455
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001456 // THEN |ScheduleUpdates()| should not be called.
1457 cfu_params_.should_schedule_updates_be_called = false;
1458 // THEN result should indicate failure.
1459 cfu_params_.expected_result = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001460
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001461 TestCheckForUpdate();
1462 }
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001463}
1464
1465TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1466 // GIVEN a official build.
1467
1468 // THEN we except forced app version + forced omaha url to be cleared.
1469
1470 TestCheckForUpdate();
1471}
1472
1473TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001474 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001475 cfu_params_.is_official_build = false;
1476 cfu_params_.are_dev_features_enabled = true;
1477
1478 // THEN the forced app version + forced omaha url changes based on input.
1479 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1480 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1481
1482 TestCheckForUpdate();
1483}
1484
1485TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1486 // GIVEN a scheduled autest omaha url.
1487 cfu_params_.omaha_url = "autest-scheduled";
1488
1489 // THEN forced app version is cleared.
1490 // THEN forced omaha url changes to default constant.
1491 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1492
1493 TestCheckForUpdate();
1494}
1495
1496TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1497 // GIVEN a scheduled autest omaha url.
1498 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001499 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001500 cfu_params_.is_official_build = false;
1501 cfu_params_.are_dev_features_enabled = true;
1502
1503 // THEN forced app version changes based on input.
1504 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1505 // THEN forced omaha url changes to default constant.
1506 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1507
1508 TestCheckForUpdate();
1509}
1510
1511TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1512 // GIVEN a autest omaha url.
1513 cfu_params_.omaha_url = "autest";
1514
1515 // THEN forced app version is cleared.
1516 // THEN forced omaha url changes to default constant.
1517 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1518
1519 TestCheckForUpdate();
1520}
1521
1522TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1523 // GIVEN a autest omha url.
1524 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001525 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001526 cfu_params_.is_official_build = false;
1527 cfu_params_.are_dev_features_enabled = true;
1528
1529 // THEN forced app version changes based on input.
1530 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1531 // THEN forced omaha url changes to default constant.
1532 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1533
1534 TestCheckForUpdate();
1535}
1536
1537TEST_F(UpdateAttempterTest,
1538 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1539 // GIVEN a scheduled autest omaha url.
1540 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001541 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001542 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1543
1544 // THEN forced app version is cleared.
1545 // THEN forced omaha url changes to default constant.
1546 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1547
1548 TestCheckForUpdate();
1549}
1550
1551TEST_F(UpdateAttempterTest,
1552 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1553 // GIVEN a scheduled autest omaha url.
1554 cfu_params_.omaha_url = "autest-scheduled";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001555 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001556 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
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, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1570 // GIVEN a autest omaha url.
1571 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001572 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001573 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1574
1575 // THEN forced app version is cleared.
1576 // THEN forced omaha url changes to default constant.
1577 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1578
1579 TestCheckForUpdate();
1580}
1581
1582TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1583 // GIVEN a autest omaha url.
1584 cfu_params_.omaha_url = "autest";
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001585 // GIVEN a noninteractive update.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001586 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001587 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001588 cfu_params_.is_official_build = false;
1589 cfu_params_.are_dev_features_enabled = true;
1590
1591 // THEN forced app version changes based on input.
1592 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1593 // THEN forced omaha url changes to default constant.
1594 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1595
1596 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001597}
1598
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001599TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1600 // GIVEN a official build.
1601 // GIVEN forced callback is not set.
1602 attempter_.set_forced_update_pending_callback(nullptr);
1603
1604 // THEN we except forced app version + forced omaha url to be cleared.
1605 // THEN |ScheduleUpdates()| should not be called.
1606 cfu_params_.should_schedule_updates_be_called = false;
1607
1608 TestCheckForUpdate();
1609}
1610
1611TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
Jae Hoon Kimc437ea52019-07-11 11:20:38 -07001612 // GIVEN a nonofficial build with dev features enabled.
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001613 cfu_params_.is_official_build = false;
1614 cfu_params_.are_dev_features_enabled = true;
1615 // GIVEN forced callback is not set.
1616 attempter_.set_forced_update_pending_callback(nullptr);
1617
1618 // THEN the forced app version + forced omaha url changes based on input.
1619 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1620 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1621 // THEN |ScheduleUpdates()| should not be called.
1622 cfu_params_.should_schedule_updates_be_called = false;
1623
1624 TestCheckForUpdate();
1625}
1626
Xiaochu Liu88d90382018-08-29 16:09:11 -07001627TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1628 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1629 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1630 attempter_.CheckForInstall({}, "autest");
1631 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1632
1633 attempter_.CheckForInstall({}, "autest-scheduled");
1634 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1635
1636 attempter_.CheckForInstall({}, "http://omaha.phishing");
1637 EXPECT_EQ("", attempter_.forced_omaha_url());
1638}
1639
Colin Howesac170d92018-11-20 16:29:28 -08001640TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1641 attempter_.CheckForInstall({}, "http://foo.bar");
1642 attempter_.status_ = UpdateStatus::DOWNLOADING;
1643 EXPECT_TRUE(attempter_.is_install_);
1644 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1645 UpdateEngineStatus status;
1646 attempter_.GetStatus(&status);
1647 // Should set status to idle after an install operation.
1648 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1649}
1650
Colin Howes978c1082018-12-03 11:46:12 -08001651TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1652 attempter_.is_install_ = true;
1653 attempter_.Rollback(false);
1654 EXPECT_FALSE(attempter_.is_install_);
1655}
1656
1657TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1658 attempter_.is_install_ = true;
1659 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1660 EXPECT_FALSE(attempter_.is_install_);
1661}
1662
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001663TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001664 attempter_.CalculateUpdateParams(
1665 "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001666 EXPECT_EQ("1234",
1667 fake_system_state_.request_params()->target_version_prefix());
1668
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001669 attempter_.CalculateUpdateParams(
1670 "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001671 EXPECT_TRUE(
1672 fake_system_state_.request_params()->target_version_prefix().empty());
1673}
1674
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001675TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1676 attempter_.CalculateUpdateParams("",
1677 "",
1678 "",
1679 "1234",
1680 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001681 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001682 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001683 false,
1684 false);
1685 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001686 EXPECT_EQ(4,
1687 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001688
1689 attempter_.CalculateUpdateParams("",
1690 "",
1691 "",
1692 "1234",
1693 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001694 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001695 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001696 false,
1697 false);
1698 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001699 EXPECT_EQ(4,
1700 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001701}
1702
Aaron Wood23bd3392017-10-06 14:48:25 -07001703TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1704 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1705 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001706 OmahaResponseHandlerAction response_action(&fake_system_state_);
1707 response_action.install_plan_.version = "a.b.c.d";
1708 response_action.install_plan_.system_version = "b.c.d.e";
1709 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001710 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001711 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1712 // completed, with the deferred-update error code.
1713 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001714 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001715 {
1716 UpdateEngineStatus status;
1717 attempter_.GetStatus(&status);
1718 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001719 EXPECT_TRUE(attempter_.install_plan_);
1720 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001721 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001722 status.new_size_bytes);
1723 }
1724 // An "error" event should have been created to tell Omaha that the update is
1725 // being deferred.
1726 EXPECT_TRUE(nullptr != attempter_.error_event_);
1727 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1728 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1729 ErrorCode expected_code = static_cast<ErrorCode>(
1730 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1731 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1732 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1733 // End the processing
1734 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1735 // Validate the state of the attempter.
1736 {
1737 UpdateEngineStatus status;
1738 attempter_.GetStatus(&status);
1739 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001740 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001741 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001742 status.new_size_bytes);
1743 }
1744}
1745
1746TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001747 // Default construction for |waiting_for_scheduled_check_| is false.
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001748 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001749 // Verify in-progress update with UPDATE_AVAILABLE is running
1750 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
Jae Hoon Kimba2fdce2019-07-11 13:18:58 -07001751 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
Aaron Wood23bd3392017-10-06 14:48:25 -07001752}
1753
Aaron Woodbf5a2522017-10-04 10:58:36 -07001754TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1755 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1756
1757 UpdateCheckParams params = {.updates_enabled = true};
1758 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1759
1760 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1761 attempter_.GetCurrentUpdateAttemptFlags());
1762}
1763
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001764TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1765 UpdateCheckParams params = {.updates_enabled = true,
1766 .rollback_allowed = false};
1767 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1768 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1769}
1770
1771TEST_F(UpdateAttempterTest, RollbackAllowed) {
1772 UpdateCheckParams params = {.updates_enabled = true,
1773 .rollback_allowed = true};
1774 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1775 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1776}
1777
Aaron Wood081c0232017-10-19 17:14:58 -07001778TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1779 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1780
1781 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1782 EXPECT_EQ(UpdateAttemptFlags::kNone,
1783 attempter_.GetCurrentUpdateAttemptFlags());
1784}
1785
1786TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1787 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1788
1789 // This tests that when CheckForUpdate() is called with the non-interactive
1790 // flag set, that it doesn't change the current UpdateAttemptFlags.
1791 attempter_.CheckForUpdate("",
1792 "",
1793 UpdateAttemptFlags::kFlagNonInteractive |
1794 UpdateAttemptFlags::kFlagRestrictDownload);
1795 EXPECT_EQ(UpdateAttemptFlags::kNone,
1796 attempter_.GetCurrentUpdateAttemptFlags());
1797}
1798
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001799void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1800 bool is_policy_loaded,
1801 bool expected_reset) {
1802 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1803 .WillRepeatedly(Return(true));
1804 auto mock_policy_provider =
1805 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1806 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1807 .WillRepeatedly(Return(is_consumer));
1808 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1809 .WillRepeatedly(Return(is_policy_loaded));
1810 const policy::MockDevicePolicy device_policy;
1811 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1812 .WillRepeatedly(ReturnRef(device_policy));
1813 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1814 SetRollbackHappened(false))
1815 .Times(expected_reset ? 1 : 0);
1816 attempter_.policy_provider_ = std::move(mock_policy_provider);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001817 attempter_.Update("", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001818 ScheduleQuitMainLoop();
1819}
1820
1821TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1822 loop_.PostTask(FROM_HERE,
1823 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1824 base::Unretained(this),
1825 /*is_consumer=*/false,
1826 /*is_policy_loaded=*/false,
1827 /*expected_reset=*/false));
1828 loop_.Run();
1829}
1830
1831TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1832 loop_.PostTask(FROM_HERE,
1833 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1834 base::Unretained(this),
1835 /*is_consumer=*/true,
1836 /*is_policy_loaded=*/false,
1837 /*expected_reset=*/true));
1838 loop_.Run();
1839}
1840
1841TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1842 loop_.PostTask(FROM_HERE,
1843 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1844 base::Unretained(this),
1845 /*is_consumer=*/false,
1846 /*is_policy_loaded=*/true,
1847 /*expected_reset=*/true));
1848 loop_.Run();
1849}
1850
Marton Hunyady199152d2018-05-07 19:08:48 +02001851TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001852 attempter_.install_plan_.reset(new InstallPlan);
1853 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001854
1855 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1856 SetRollbackHappened(true))
1857 .Times(1);
1858 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1859}
1860
1861TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001862 attempter_.install_plan_.reset(new InstallPlan);
1863 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001864
1865 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1866 SetRollbackHappened(true))
1867 .Times(0);
1868 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1869}
1870
Marton Hunyadya0302682018-05-16 18:52:13 +02001871TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001872 attempter_.install_plan_.reset(new InstallPlan);
1873 attempter_.install_plan_->is_rollback = true;
1874 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001875
1876 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1877 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1878 .Times(1);
1879 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1880}
1881
1882TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001883 attempter_.install_plan_.reset(new InstallPlan);
1884 attempter_.install_plan_->is_rollback = false;
1885 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001886
1887 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1888 ReportEnterpriseRollbackMetrics(_, _))
1889 .Times(0);
1890 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1891}
1892
1893TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001894 attempter_.install_plan_.reset(new InstallPlan);
1895 attempter_.install_plan_->is_rollback = true;
1896 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001897
1898 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1899 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1900 .Times(1);
1901 MockAction action;
1902 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1903 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1904}
1905
1906TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001907 attempter_.install_plan_.reset(new InstallPlan);
1908 attempter_.install_plan_->is_rollback = false;
1909 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001910
1911 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1912 ReportEnterpriseRollbackMetrics(_, _))
1913 .Times(0);
1914 MockAction action;
1915 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1916 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1917}
1918
May Lippert60aa3ca2018-08-15 16:55:29 -07001919TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1920 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1921 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1922 .Times(0);
1923 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1924}
1925
1926TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1927 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1928 fake_system_state_.set_device_policy(device_policy.get());
1929 // Make device policy return that this is not enterprise enrolled
1930 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1931
1932 // Ensure that the metric is not recorded.
1933 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1934 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1935 .Times(0);
1936 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1937}
1938
1939TEST_F(UpdateAttempterTest,
1940 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1941 constexpr int kDaysToUpdate = 15;
1942 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1943 fake_system_state_.set_device_policy(device_policy.get());
1944 // Make device policy return that this is enterprise enrolled
1945 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1946 // Pretend that there's a time restriction policy in place
1947 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1948 .WillOnce(Return(true));
1949
1950 FakePrefs fake_prefs;
1951 Time update_first_seen_at = Time::Now();
1952 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1953 update_first_seen_at.ToInternalValue());
1954
1955 FakeClock fake_clock;
1956 Time update_finished_at =
1957 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1958 fake_clock.SetWallclockTime(update_finished_at);
1959
1960 fake_system_state_.set_clock(&fake_clock);
1961 fake_system_state_.set_prefs(&fake_prefs);
1962
1963 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1964 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1965 .Times(1);
1966 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1967}
1968
1969TEST_F(UpdateAttempterTest,
1970 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1971 constexpr int kDaysToUpdate = 15;
1972 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1973 fake_system_state_.set_device_policy(device_policy.get());
1974 // Make device policy return that this is enterprise enrolled
1975 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1976 // Pretend that there's no time restriction policy in place
1977 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1978 .WillOnce(Return(false));
1979
1980 FakePrefs fake_prefs;
1981 Time update_first_seen_at = Time::Now();
1982 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1983 update_first_seen_at.ToInternalValue());
1984
1985 FakeClock fake_clock;
1986 Time update_finished_at =
1987 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1988 fake_clock.SetWallclockTime(update_finished_at);
1989
1990 fake_system_state_.set_clock(&fake_clock);
1991 fake_system_state_.set_prefs(&fake_prefs);
1992
1993 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1994 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1995 .Times(1);
1996 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1997}
1998
Jae Hoon Kimed3fcc02019-07-11 14:35:38 -07001999TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
2000 // GIVEN an update finished.
2001
2002 // THEN need reboot since update applied.
2003 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
2004 // THEN install indication should be false.
2005
2006 TestProcessingDone();
2007}
2008
2009TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
2010 // GIVEN an install finished.
2011 pd_params_.is_install = true;
2012
2013 // THEN go idle.
2014 // THEN install indication should be false.
2015
2016 TestProcessingDone();
2017}
2018
2019TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2020 // GIVEN an install finished.
2021 pd_params_.is_install = true;
2022 // GIVEN a reporting error occurred.
2023 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2024
2025 // THEN go idle.
2026 // THEN install indication should be false.
2027
2028 TestProcessingDone();
2029}
2030
2031TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2032 // GIVEN an update finished.
2033 // GIVEN an action error occured.
2034 pd_params_.code = ErrorCode::kNoUpdate;
2035
2036 // THEN go idle.
2037 // THEN install indication should be false.
2038
2039 TestProcessingDone();
2040}
2041
2042TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2043 // GIVEN an install finished.
2044 pd_params_.is_install = true;
2045 // GIVEN an action error occured.
2046 pd_params_.code = ErrorCode::kNoUpdate;
2047
2048 // THEN go idle.
2049 // THEN install indication should be false.
2050
2051 TestProcessingDone();
2052}
2053
2054TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2055 // GIVEN an update finished.
2056 // GIVEN an action error occured.
2057 pd_params_.code = ErrorCode::kError;
2058 // GIVEN an event error is set.
2059 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2060 OmahaEvent::kResultError,
2061 ErrorCode::kError));
2062
2063 // THEN indicate a error event.
2064 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2065 // THEN install indication should be false.
2066
2067 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2068 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2069 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2070 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2071 pd_params_.should_schedule_updates_be_called = false;
2072
2073 TestProcessingDone();
2074}
2075
2076TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2077 // GIVEN an install finished.
2078 pd_params_.is_install = true;
2079 // GIVEN an action error occured.
2080 pd_params_.code = ErrorCode::kError;
2081 // GIVEN an event error is set.
2082 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2083 OmahaEvent::kResultError,
2084 ErrorCode::kError));
2085
2086 // THEN indicate a error event.
2087 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2088 // THEN install indication should be false.
2089
2090 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2091 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2092 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2093 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2094 pd_params_.should_schedule_updates_be_called = false;
2095
2096 TestProcessingDone();
2097}
2098
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002099void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
2100 // Tests that checks if |device_quick_fix_build_token| arrives when
2101 // policy is set and the device is enterprise enrolled based on |set_token|.
2102 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02002103 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
2104 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002105 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002106
2107 if (set_token)
2108 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2109 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
2110 else
2111 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
2112 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002113 attempter_.policy_provider_.reset(
2114 new policy::PolicyProvider(std::move(device_policy)));
2115 attempter_.Update("", "", "", "", false, false, 0, false, false);
2116
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002117 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02002118 ScheduleQuitMainLoop();
2119}
2120
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002121TEST_F(UpdateAttempterTest,
2122 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02002123 loop_.PostTask(FROM_HERE,
2124 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02002125 base::Unretained(this),
2126 /*set_token=*/true));
2127 loop_.Run();
2128}
2129
2130TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2131 loop_.PostTask(FROM_HERE,
2132 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2133 base::Unretained(this),
2134 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002135 loop_.Run();
2136}
2137
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002138TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2139 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2140 .Times(1);
2141 EXPECT_TRUE(attempter_.ScheduleUpdates());
2142 // Now there is an update scheduled which means that all subsequent
2143 // |ScheduleUpdates()| should fail.
2144 EXPECT_FALSE(attempter_.ScheduleUpdates());
2145 EXPECT_FALSE(attempter_.ScheduleUpdates());
2146 EXPECT_FALSE(attempter_.ScheduleUpdates());
2147}
2148
2149// Critical tests to always make sure that an update is scheduled. The following
2150// unittest(s) try and cover the correctness in synergy between
2151// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2152// actions that happen in the flow when |UpdateAttempter| get callbacked on
2153// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2154void UpdateAttempterTest::TestOnUpdateScheduled() {
2155 // Setup
2156 attempter_.SetWaitingForScheduledCheck(true);
2157 attempter_.DisableUpdate();
2158 attempter_.DisableScheduleUpdates();
2159
2160 // Invocation
2161 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2162
2163 // Verify
2164 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2165 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2166 attempter_.WasScheduleUpdatesCalled());
2167 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2168}
2169
2170TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2171 // GIVEN failed status.
2172
2173 // THEN update should be scheduled.
2174 ous_params_.should_schedule_updates_be_called = true;
2175
2176 TestOnUpdateScheduled();
2177}
2178
2179TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2180 // GIVEN ask me again later status.
2181 ous_params_.status = EvalStatus::kAskMeAgainLater;
2182
2183 // THEN update should be scheduled.
2184 ous_params_.should_schedule_updates_be_called = true;
2185
2186 TestOnUpdateScheduled();
2187}
2188
2189TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2190 // GIVEN continue status.
2191 ous_params_.status = EvalStatus::kContinue;
2192
2193 // THEN update should be scheduled.
2194 ous_params_.should_schedule_updates_be_called = true;
2195
2196 TestOnUpdateScheduled();
2197}
2198
2199TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2200 // GIVEN updates disabled.
2201 ous_params_.params = {.updates_enabled = false};
2202 // GIVEN succeeded status.
2203 ous_params_.status = EvalStatus::kSucceeded;
2204
2205 // THEN update should not be scheduled.
2206
2207 TestOnUpdateScheduled();
2208}
2209
2210TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2211 // GIVEN updates enabled.
2212 ous_params_.params = {.updates_enabled = true};
2213 // GIVEN succeeded status.
2214 ous_params_.status = EvalStatus::kSucceeded;
2215
2216 // THEN update should be called indicating status change.
2217 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2218 ous_params_.should_update_be_called = true;
2219
2220 TestOnUpdateScheduled();
2221}
2222
Amin Hassani9be122e2019-08-29 09:20:12 -07002223TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2224 UpdateEngineStatus status;
2225 attempter_.GetStatus(&status);
2226 EXPECT_FALSE(status.is_enterprise_rollback);
2227}
2228
2229TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2230 attempter_.install_plan_.reset(new InstallPlan);
2231 attempter_.install_plan_->is_rollback = false;
2232
2233 UpdateEngineStatus status;
2234 attempter_.GetStatus(&status);
2235 EXPECT_FALSE(status.is_enterprise_rollback);
2236}
2237
2238TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2239 attempter_.install_plan_.reset(new InstallPlan);
2240 attempter_.install_plan_->is_rollback = true;
2241
2242 UpdateEngineStatus status;
2243 attempter_.GetStatus(&status);
2244 EXPECT_TRUE(status.is_enterprise_rollback);
2245}
2246
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002247} // namespace chromeos_update_engine