blob: b7d09971b7a6ebb1cac0644ad0ded96da3331478 [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 Kim51ea9ae2019-07-03 16:56:30 -070091struct CheckForUpdateTestParams {
92 // Setups + Inputs:
93 UpdateStatus status = UpdateStatus::IDLE;
94 string app_version = "fake_app_version";
95 string omaha_url = "fake_omaha_url";
96 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
97 bool is_official_build = true;
98 bool are_dev_features_enabled = false;
99
100 // Expects:
101 string expected_forced_app_version = "";
102 string expected_forced_omaha_url = "";
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700103 bool should_schedule_updates_be_called = true;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700104 bool expected_result = true;
105};
106
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700107struct OnUpdateScheduledTestParams {
108 // Setups + Inputs:
109 UpdateCheckParams params = {};
110 EvalStatus status = EvalStatus::kFailed;
111 // Expects:
112 UpdateStatus exit_status = UpdateStatus::IDLE;
113 bool should_schedule_updates_be_called = false;
114 bool should_update_be_called = false;
115};
116
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800117class MockDlcService : public DlcServiceInterface {
118 public:
119 MOCK_METHOD1(GetInstalled, bool(vector<string>*));
120};
121
122} // namespace
123
Marton Hunyadya0302682018-05-16 18:52:13 +0200124const char kRollbackVersion[] = "10575.39.2";
125
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700126// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700127// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700128// methods.
129class UpdateAttempterUnderTest : public UpdateAttempter {
130 public:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700131 explicit UpdateAttempterUnderTest(SystemState* system_state)
132 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700133
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700134 void Update(const std::string& app_version,
135 const std::string& omaha_url,
136 const std::string& target_channel,
137 const std::string& target_version_prefix,
138 bool rollback_allowed,
139 bool rollback_data_save_requested,
140 int rollback_allowed_milestones,
141 bool obey_proxies,
142 bool interactive) override {
143 update_called_ = true;
144 if (do_update_) {
145 UpdateAttempter::Update(app_version,
146 omaha_url,
147 target_channel,
148 target_version_prefix,
149 rollback_allowed,
150 rollback_data_save_requested,
151 rollback_allowed_milestones,
152 obey_proxies,
153 interactive);
154 return;
155 }
156 LOG(INFO) << "[TEST] Update() disabled.";
157 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
158 }
159
160 void DisableUpdate() { do_update_ = false; }
161
162 bool WasUpdateCalled() const { return update_called_; }
163
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700164 // Wrap the update scheduling method, allowing us to opt out of scheduled
165 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700166 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700167 schedule_updates_called_ = true;
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700168 if (do_schedule_updates_)
169 return UpdateAttempter::ScheduleUpdates();
170 LOG(INFO) << "[TEST] Update scheduling disabled.";
171 waiting_for_scheduled_check_ = true;
Xiaochu Liu88d90382018-08-29 16:09:11 -0700172 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700173 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700174
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700175 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
176
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700177 // Indicates whether |ScheduleUpdates()| was called.
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700178 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700179
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700180 // Need to expose following private members of |UpdateAttempter| for tests.
181 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700182 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800183
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700184 // Need to expose |waiting_for_scheduled_check_| for testing.
185 void SetWaitingForScheduledCheck(bool waiting) {
186 waiting_for_scheduled_check_ = waiting;
187 }
188
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700189 private:
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700190 // Used for overrides of |Update()|.
191 bool update_called_ = false;
192 bool do_update_ = true;
193
194 // Used for overrides of |ScheduleUpdates()|.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700195 bool schedule_updates_called_ = false;
196 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700197};
198
199class UpdateAttempterTest : public ::testing::Test {
200 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700201 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600202 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300203 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700204 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700205 fake_system_state_.set_connection_manager(&mock_connection_manager);
206 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800207 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700208 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700209 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700210
Alex Deymo33e91e72015-12-01 18:26:08 -0300211 certificate_checker_.Init();
212
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800213 attempter_.set_forced_update_pending_callback(
214 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700215 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700216 attempter_.Init();
Jay Srinivasan43488792012-06-19 00:25:31 -0700217 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700218
Alex Deymo610277e2014-11-11 21:18:11 -0800219 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700220 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700221 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700222 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700223 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700224 EXPECT_EQ(0.0, attempter_.download_progress_);
225 EXPECT_EQ(0, attempter_.last_checked_time_);
226 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700227 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800228 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700229 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700230 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700231
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700232 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700233 actual_using_p2p_for_downloading_ = false;
234 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
235 SetUsingP2PForDownloading(_))
236 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
237 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
238 GetUsingP2PForDownloading())
239 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
240 actual_using_p2p_for_sharing_ = false;
241 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
242 SetUsingP2PForSharing(_))
243 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
244 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
245 GetUsingP2PForDownloading())
246 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700247 }
248
Alex Deymo60ca1a72015-06-18 18:19:15 -0700249 public:
250 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200251
Alex Deymo60ca1a72015-06-18 18:19:15 -0700252 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800253 void UpdateTestStart();
254 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700255 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700256 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700257 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700258 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700259 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700260 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700261 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700262 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700263 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700264 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700265 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700266 void SessionIdTestChange();
267 void SessionIdTestEnforceEmptyStrPingOmaha();
268 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700269 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200270 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200271 void ResetRollbackHappenedStart(bool is_consumer,
272 bool is_policy_available,
273 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700274 // Staging related callbacks.
275 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
276 void CheckStagingOff();
277 void StagingSetsPrefsAndTurnsOffScatteringStart();
278 void StagingOffIfInteractiveStart();
279 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700280
Gilad Arnold74b5f552014-10-07 08:17:16 -0700281 bool actual_using_p2p_for_downloading() {
282 return actual_using_p2p_for_downloading_;
283 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800284 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700285
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700286 // |CheckForUpdate()| related member functions.
287 void TestCheckForUpdate();
288
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700289 // |OnUpdateScheduled()| related member functions.
290 void TestOnUpdateScheduled();
291
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700292 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700293 brillo::BaseMessageLoop loop_{&base_loop_};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700294
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700295 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700296 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300297 OpenSSLWrapper openssl_wrapper_;
298 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800299 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700300 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700301
Alex Deymo8427b4a2014-11-05 14:00:32 -0800302 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700303 NiceMock<MockPrefs>*
304 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800305 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700306
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700307 // |CheckForUpdate()| test params.
308 CheckForUpdateTestParams cfu_params_;
309
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700310 // |OnUpdateScheduled()| test params.
311 OnUpdateScheduledTestParams ous_params_;
312
Gilad Arnold74b5f552014-10-07 08:17:16 -0700313 bool actual_using_p2p_for_downloading_;
314 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700315};
316
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700317void UpdateAttempterTest::TestCheckForUpdate() {
318 // Setup
319 attempter_.status_ = cfu_params_.status;
320 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
321 cfu_params_.is_official_build);
322 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
323 cfu_params_.are_dev_features_enabled);
324
325 // Invocation
326 EXPECT_EQ(
327 cfu_params_.expected_result,
328 attempter_.CheckForUpdate(
329 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
330
331 // Verify
332 EXPECT_EQ(cfu_params_.expected_forced_app_version,
333 attempter_.forced_app_version());
334 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
335 attempter_.forced_omaha_url());
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -0700336 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
337 attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700338}
339
Alex Deymo60ca1a72015-06-18 18:19:15 -0700340void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700341 loop_.PostTask(
342 FROM_HERE,
343 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
344 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700345}
346
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700347void UpdateAttempterTest::SessionIdTestChange() {
348 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
349 const auto old_session_id = attempter_.session_id_;
350 attempter_.Update("", "", "", "", false, false, 0, false, false);
351 EXPECT_NE(old_session_id, attempter_.session_id_);
352 ScheduleQuitMainLoop();
353}
354
355TEST_F(UpdateAttempterTest, SessionIdTestChange) {
356 loop_.PostTask(FROM_HERE,
357 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
358 base::Unretained(this)));
359 loop_.Run();
360}
361
362void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
363 // The |session_id_| should not be changed and should remain as an empty
364 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
365 // and |PingOmaha()| is called.
366 attempter_.DisableScheduleUpdates();
367 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
368 const auto old_session_id = attempter_.session_id_;
369 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
370 if (aa->Type() == OmahaRequestAction::StaticType()) {
371 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
372 }
373 };
374 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
375 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
376 EXPECT_CALL(*processor_, StartProcessing());
377 attempter_.PingOmaha();
378 EXPECT_EQ(old_session_id, attempter_.session_id_);
379 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
380 ScheduleQuitMainLoop();
381}
382
383TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
384 loop_.PostTask(
385 FROM_HERE,
386 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
387 base::Unretained(this)));
388 loop_.Run();
389}
390
391void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
392 // All session IDs passed into |OmahaRequestActions| should be enforced to
393 // have the same value in |BuildUpdateActions()|.
394 unordered_set<string> session_ids;
395 // Gather all the session IDs being passed to |OmahaRequestActions|.
396 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
397 if (aa->Type() == OmahaRequestAction::StaticType())
398 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
399 };
400 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
401 .WillRepeatedly(Invoke(CheckSessionId));
402 attempter_.BuildUpdateActions(false);
403 // Validate that all the session IDs are the same.
404 EXPECT_EQ(1, session_ids.size());
405 ScheduleQuitMainLoop();
406}
407
408TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
409 loop_.PostTask(
410 FROM_HERE,
411 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
412 base::Unretained(this)));
413 loop_.Run();
414}
415
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700416void UpdateAttempterTest::SessionIdTestInDownloadAction() {
417 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
418 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
419 string header_value;
420 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
421 if (aa->Type() == DownloadAction::StaticType()) {
422 DownloadAction* da = static_cast<DownloadAction*>(aa);
423 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
424 &header_value));
425 }
426 };
427 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
428 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
429 attempter_.BuildUpdateActions(false);
430 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
431 EXPECT_EQ(attempter_.session_id_, header_value);
432 ScheduleQuitMainLoop();
433}
434
435TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
436 loop_.PostTask(FROM_HERE,
437 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
438 base::Unretained(this)));
439 loop_.Run();
440}
441
Darin Petkov1b003102010-11-30 10:18:36 -0800442TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700443 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800444 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700445 DownloadAction action(prefs_,
446 nullptr,
447 nullptr,
448 nullptr,
449 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700450 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800451 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700452 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700453 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700454 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700455 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800456}
457
458TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800459 MockAction action;
460 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700461 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800462 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800463 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700464 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
465 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800466}
467
Aaron Wood9321f502017-09-07 11:18:54 -0700468TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
469 // Simple test case, where all the values match (nothing was skipped)
470 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
471 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
472 uint64_t bytes_received_1 = bytes_progressed_1;
473 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
474 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
475
476 double progress_1 =
477 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
478 double progress_2 =
479 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
480
481 EXPECT_EQ(0.0, attempter_.download_progress_);
482 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700483 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700484 attempter_.new_payload_size_ = bytes_total;
485 NiceMock<MockServiceObserver> observer;
486 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700487 SendStatusUpdate(AllOf(
488 Field(&UpdateEngineStatus::progress, progress_1),
489 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
490 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700491 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700492 SendStatusUpdate(AllOf(
493 Field(&UpdateEngineStatus::progress, progress_2),
494 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
495 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700496 attempter_.AddObserver(&observer);
497 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
498 EXPECT_EQ(progress_1, attempter_.download_progress_);
499 // This iteration validates that a later set of updates to the variables are
500 // properly handled (so that |getStatus()| will return the same progress info
501 // as the callback is receiving.
502 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
503 EXPECT_EQ(progress_2, attempter_.download_progress_);
504}
505
506TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700507 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700508 // first bytes are received.
509 uint64_t bytes_progressed = 1024 * 1024; // 1MB
510 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
511 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
512 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
513 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700514 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700515 attempter_.new_payload_size_ = bytes_total;
516 EXPECT_EQ(0.0, attempter_.download_progress_);
517 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700518 EXPECT_CALL(observer,
519 SendStatusUpdate(AllOf(
520 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
521 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700522 attempter_.AddObserver(&observer);
523 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
524 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
525}
526
527TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
528 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700529 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700530 uint64_t bytes_progressed = 0; // ignored
531 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
532 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
533 attempter_.status_ = UpdateStatus::DOWNLOADING;
534 attempter_.new_payload_size_ = bytes_total;
535 EXPECT_EQ(0.0, attempter_.download_progress_);
536 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700537 EXPECT_CALL(observer,
538 SendStatusUpdate(AllOf(
539 Field(&UpdateEngineStatus::progress, 1.0),
540 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
541 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700542 attempter_.AddObserver(&observer);
543 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
544 EXPECT_EQ(1.0, attempter_.download_progress_);
545}
546
Darin Petkov1b003102010-11-30 10:18:36 -0800547TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700548 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800549 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800550 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700551 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800552 ObjectCollectorAction<OmahaResponse> collector_action;
553 BondActions(&action, &collector_action);
554 OmahaResponse response;
555 response.poll_interval = 234;
556 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800557 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700558 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800559 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700560 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800561 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700562 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800563}
564
Alex Deymo30534502015-07-20 15:06:33 -0700565TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700566 FakePrefs fake_prefs;
567 string boot_id;
568 EXPECT_TRUE(utils::GetBootId(&boot_id));
569 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
570 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700571 attempter_.Init();
572 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700573}
574
575TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700576 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700577 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700578
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700579 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800580 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700581 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700582 EXPECT_EQ(ErrorCode::kOmahaRequestError,
583 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700584 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800585 EXPECT_EQ(
586 ErrorCode::kOmahaResponseHandlerError,
587 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Sen Jiange6e4bb92016-04-05 14:59:12 -0700588 FilesystemVerifierAction filesystem_verifier_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800589 EXPECT_EQ(
590 ErrorCode::kFilesystemVerifierError,
591 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300592 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700593 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800594 EXPECT_EQ(
595 ErrorCode::kPostinstallRunnerError,
596 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800597 MockAction action_mock;
598 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700599 EXPECT_EQ(ErrorCode::kError,
600 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700601}
602
Darin Petkov36275772010-10-01 11:40:57 -0700603TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700604 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800605 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700606 .WillOnce(Return(false));
607 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700608 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800609 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800610 .WillOnce(
611 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
612 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700613 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700614 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800615 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800616 .WillOnce(
617 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
618 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700619 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700620 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800621 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700622 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700623 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700624}
625
626TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800627 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700628 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700629 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
630 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800631 .WillOnce(
632 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
633 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800634 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700635 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800636 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700637 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800638 EXPECT_CALL(*prefs_,
639 SetInt64(kPrefsDeltaUpdateFailures,
640 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
641 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700642 attempter_.MarkDeltaUpdateFailure();
643}
644
Darin Petkov1b003102010-11-30 10:18:36 -0800645TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
646 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
647 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700648 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800649 .Times(0);
650 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700651 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800652 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700653 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700654 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700655 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800656 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700657 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800658}
659
660TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
661 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700662 EnqueueAction(Pointee(Property(
663 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700664 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700665 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700666 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800667 attempter_.error_event_.reset(new OmahaEvent(
668 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800669 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700670 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800671}
672
Darin Petkove6ef2f82011-03-07 17:31:11 -0800673namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700674// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200675vector<string> GetUpdateActionTypes() {
676 return {OmahaRequestAction::StaticType(),
677 OmahaResponseHandlerAction::StaticType(),
678 UpdateBootFlagsAction::StaticType(),
679 OmahaRequestAction::StaticType(),
680 DownloadAction::StaticType(),
681 OmahaRequestAction::StaticType(),
682 FilesystemVerifierAction::StaticType(),
683 PostinstallRunnerAction::StaticType(),
684 OmahaRequestAction::StaticType()};
685}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700686
687// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200688vector<string> GetRollbackActionTypes() {
689 return {InstallPlanAction::StaticType(),
690 PostinstallRunnerAction::StaticType()};
691}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700692
Adolfo Victoria497044c2018-07-18 07:51:42 -0700693const StagingSchedule kValidStagingSchedule = {
694 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
695
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700696} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800697
698void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700699 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700700
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700701 // Expect that the device policy is loaded by the |UpdateAttempter| at some
702 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100703 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700704 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800705 .Times(testing::AtLeast(1))
706 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100707 attempter_.policy_provider_.reset(
708 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700709
710 {
711 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200712 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700713 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700714 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200715 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700716 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700717 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700718 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700719
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800720 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700721 loop_.PostTask(FROM_HERE,
722 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
723 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800724}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700725
Darin Petkove6ef2f82011-03-07 17:31:11 -0800726void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700727 EXPECT_EQ(0, attempter_.http_response_code());
728 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700729 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700730 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800731}
732
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800733void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
734 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700735 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100736 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700737 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100738 fake_system_state_.set_device_policy(device_policy.get());
739 if (enterprise_rollback) {
740 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800741 EXPECT_CALL(*device_policy, GetOwner(_))
742 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100743 } else {
744 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800745 EXPECT_CALL(*device_policy, GetOwner(_))
746 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
747 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100748 }
749
750 attempter_.policy_provider_.reset(
751 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700752
Alex Deymo763e7db2015-08-27 21:08:08 -0700753 if (valid_slot) {
754 BootControlInterface::Slot rollback_slot = 1;
755 LOG(INFO) << "Test Mark Bootable: "
756 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700757 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
758 true);
Don Garrett6646b442013-11-13 15:29:11 -0800759 }
760
Chris Sosa28e479c2013-07-12 11:39:53 -0700761 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700762
Chris Sosad38b1132014-03-25 10:43:59 -0700763 // We only allow rollback on devices that are not enterprise enrolled and
764 // which have a valid slot to rollback to.
765 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800766 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700767 }
768
Chris Sosa28e479c2013-07-12 11:39:53 -0700769 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700770 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200771 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700772 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200773 EnqueueAction(Pointee(
774 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700775 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700776 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700777
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700778 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700779 loop_.PostTask(FROM_HERE,
780 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
781 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700782 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700783 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700784 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700785 }
786}
787
788void UpdateAttempterTest::RollbackTestVerify() {
789 // Verifies the actions that were enqueued.
790 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700791 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700792 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
793 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700794 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700795}
796
Darin Petkove6ef2f82011-03-07 17:31:11 -0800797TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700798 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700799 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700800}
801
Chris Sosa76a29ae2013-07-11 17:59:24 -0700802TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700803 loop_.PostTask(FROM_HERE,
804 base::Bind(&UpdateAttempterTest::RollbackTestStart,
805 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800806 false,
807 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700808 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700809}
810
Don Garrett6646b442013-11-13 15:29:11 -0800811TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700812 loop_.PostTask(FROM_HERE,
813 base::Bind(&UpdateAttempterTest::RollbackTestStart,
814 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800815 false,
816 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700817 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800818}
819
Chris Sosa76a29ae2013-07-11 17:59:24 -0700820TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700821 loop_.PostTask(FROM_HERE,
822 base::Bind(&UpdateAttempterTest::RollbackTestStart,
823 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800824 true,
825 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700826 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700827}
828
Thieu Le116fda32011-04-19 11:01:54 -0700829void UpdateAttempterTest::PingOmahaTestStart() {
830 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700831 EnqueueAction(Pointee(Property(
832 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700833 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700834 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700835 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700836}
837
838TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700839 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700840 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700841 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700842 // testing, which is more permissive than we want to handle here.
843 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700844 loop_.PostTask(FROM_HERE,
845 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
846 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700847 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700848 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Jae Hoon Kim75daa382019-07-02 11:17:24 -0700849 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
Thieu Le116fda32011-04-19 11:01:54 -0700850}
851
Darin Petkov18c7bce2011-06-16 14:07:00 -0700852TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800853 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700854 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700855 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700856 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700857 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
858 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700859 EXPECT_EQ(
860 static_cast<ErrorCode>(static_cast<int>(kCode) |
861 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
862 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700863}
864
865TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700866 attempter_.install_plan_.reset(new InstallPlan);
867 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800868 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700869 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700870 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700871 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700872 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
873 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700874 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800875 static_cast<ErrorCode>(static_cast<int>(kCode) |
876 static_cast<int>(ErrorCode::kResumedFlag) |
877 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700878 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700879}
880
David Zeuthen8f191b22013-08-06 12:27:50 -0700881TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
882 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700883 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700884 mock_p2p_manager.fake().SetP2PEnabled(false);
885 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
886 attempter_.UpdateEngineStarted();
887}
888
889TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
890 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700891 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700892 mock_p2p_manager.fake().SetP2PEnabled(true);
893 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
894 attempter_.UpdateEngineStarted();
895}
896
897TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
898 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700899 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700900 mock_p2p_manager.fake().SetP2PEnabled(true);
901 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700902 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700903 attempter_.UpdateEngineStarted();
904}
905
906TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700907 loop_.PostTask(FROM_HERE,
908 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
909 base::Unretained(this)));
910 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700911}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700912
David Zeuthen8f191b22013-08-06 12:27:50 -0700913void UpdateAttempterTest::P2PNotEnabledStart() {
914 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700915 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700916 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700917 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700918 mock_p2p_manager.fake().SetP2PEnabled(false);
919 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800920 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700921 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700922 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700923 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700924}
925
926TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700927 loop_.PostTask(FROM_HERE,
928 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
929 base::Unretained(this)));
930 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700931}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700932
David Zeuthen8f191b22013-08-06 12:27:50 -0700933void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700934 // If P2P is enabled, but starting it fails ensure we don't do
935 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700936 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700937 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700938 mock_p2p_manager.fake().SetP2PEnabled(true);
939 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
940 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
941 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800942 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700943 EXPECT_FALSE(actual_using_p2p_for_downloading());
944 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700945 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700946}
947
948TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700949 loop_.PostTask(
950 FROM_HERE,
951 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
952 base::Unretained(this)));
953 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700954}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700955
David Zeuthen8f191b22013-08-06 12:27:50 -0700956void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700957 // If P2P is enabled, starting it works but housekeeping fails, ensure
958 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700959 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700960 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700961 mock_p2p_manager.fake().SetP2PEnabled(true);
962 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
963 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700964 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800965 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700966 EXPECT_FALSE(actual_using_p2p_for_downloading());
967 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700968 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700969}
970
971TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700972 loop_.PostTask(FROM_HERE,
973 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
974 base::Unretained(this)));
975 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700976}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700977
David Zeuthen8f191b22013-08-06 12:27:50 -0700978void UpdateAttempterTest::P2PEnabledStart() {
979 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700980 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700981 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700982 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700983 mock_p2p_manager.fake().SetP2PEnabled(true);
984 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
985 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700986 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800987 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700988 EXPECT_TRUE(actual_using_p2p_for_downloading());
989 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700990 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700991}
992
993TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700994 loop_.PostTask(FROM_HERE,
995 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
996 base::Unretained(this)));
997 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700998}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700999
David Zeuthen8f191b22013-08-06 12:27:50 -07001000void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1001 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001002 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -07001003 // For an interactive check, if P2P is enabled and starting it
1004 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -07001005 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -07001006 mock_p2p_manager.fake().SetP2PEnabled(true);
1007 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1008 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001009 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001010 attempter_.Update("",
1011 "",
1012 "",
1013 "",
1014 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001015 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001016 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001017 false,
1018 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -07001019 EXPECT_FALSE(actual_using_p2p_for_downloading());
1020 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -07001021 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -07001022}
1023
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001024TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001025 loop_.PostTask(
1026 FROM_HERE,
1027 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1028 base::Unretained(this)));
1029 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001030}
1031
1032// Tests that the scatter_factor_in_seconds value is properly fetched
1033// from the device policy.
1034void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -07001035 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001036
Igor9fd76b62017-12-11 15:24:18 +01001037 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001038 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001039 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001040
1041 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001042 .WillRepeatedly(
1043 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001044
Igor9fd76b62017-12-11 15:24:18 +01001045 attempter_.policy_provider_.reset(
1046 new policy::PolicyProvider(std::move(device_policy)));
1047
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001048 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001049 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1050
Alex Deymo60ca1a72015-06-18 18:19:15 -07001051 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001052}
1053
1054TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -07001055 loop_.PostTask(
1056 FROM_HERE,
1057 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1058 base::Unretained(this)));
1059 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001060}
1061
1062void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1063 // Tests that the scatter_factor_in_seconds value is properly fetched
1064 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001065 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001066 FakePrefs fake_prefs;
1067 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001068
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001069 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001070
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001071 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001072
Ben Chan9abb7632014-08-07 00:10:53 -07001073 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001074
Igor9fd76b62017-12-11 15:24:18 +01001075 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001076 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001077 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001078
1079 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001080 .WillRepeatedly(
1081 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001082
Igor9fd76b62017-12-11 15:24:18 +01001083 attempter_.policy_provider_.reset(
1084 new policy::PolicyProvider(std::move(device_policy)));
1085
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001086 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001087 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1088
1089 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001090 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001091
Ben Chan9abb7632014-08-07 00:10:53 -07001092 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001093 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001094 EXPECT_EQ(initial_value - 1, new_value);
1095
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001096 EXPECT_TRUE(
1097 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001098
1099 // However, if the count is already 0, it's not decremented. Test that.
1100 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001101 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001102 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001103 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1104 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001105 EXPECT_EQ(initial_value, new_value);
1106
Alex Deymo60ca1a72015-06-18 18:19:15 -07001107 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001108}
1109
Jay Srinivasan08fce042012-06-07 16:31:01 -07001110TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001111 loop_.PostTask(
1112 FROM_HERE,
1113 base::Bind(
1114 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1115 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001116 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001117}
1118
1119void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1120 // Tests that no scattering logic is enabled if the update check
1121 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001122 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001123 FakePrefs fake_prefs;
1124 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001125
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001126 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001127 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001128
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001129 EXPECT_TRUE(
1130 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001131 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001132
1133 // make sure scatter_factor is non-zero as scattering is disabled
1134 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001135 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001136
Igor9fd76b62017-12-11 15:24:18 +01001137 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001138 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001139 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001140
1141 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001142 .WillRepeatedly(
1143 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001144
Igor9fd76b62017-12-11 15:24:18 +01001145 attempter_.policy_provider_.reset(
1146 new policy::PolicyProvider(std::move(device_policy)));
1147
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001148 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001149 attempter_.Update("",
1150 "",
1151 "",
1152 "",
1153 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001154 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001155 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001156 false,
1157 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001158 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1159
1160 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001161 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001162 EXPECT_FALSE(
1163 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001164 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001165 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1166 EXPECT_FALSE(
1167 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001168 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001169
Alex Deymo60ca1a72015-06-18 18:19:15 -07001170 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001171}
1172
Adolfo Victoria497044c2018-07-18 07:51:42 -07001173void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1174 FakePrefs* prefs) {
1175 attempter_.prefs_ = prefs;
1176 fake_system_state_.set_prefs(prefs);
1177
1178 int64_t initial_value = 8;
1179 EXPECT_TRUE(
1180 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1181 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1182 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1183
1184 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1185 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1186 fake_system_state_.set_device_policy(device_policy.get());
1187 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1188 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1189
1190 attempter_.policy_provider_.reset(
1191 new policy::PolicyProvider(std::move(device_policy)));
1192}
1193
1194TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1195 loop_.PostTask(
1196 FROM_HERE,
1197 base::Bind(
1198 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1199 base::Unretained(this)));
1200 loop_.Run();
1201}
1202
1203void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1204 // Tests that staging sets its prefs properly and turns off scattering.
1205 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1206 FakePrefs fake_prefs;
1207 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1208
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001209 attempter_.Update("", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001210 // Check that prefs have the correct values.
1211 int64_t update_count;
1212 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1213 int64_t waiting_time_days;
1214 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1215 &waiting_time_days));
1216 EXPECT_GT(waiting_time_days, 0);
1217 // Update count should have been decremented.
1218 EXPECT_EQ(7, update_count);
1219 // Check that Omaha parameters were updated correctly.
1220 EXPECT_TRUE(
1221 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1222 EXPECT_TRUE(
1223 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1224 EXPECT_EQ(waiting_time_days,
1225 attempter_.omaha_request_params_->waiting_period().InDays());
1226 // Check class variables.
1227 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1228 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1229 // Check that scattering is turned off
1230 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1231 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1232
1233 ScheduleQuitMainLoop();
1234}
1235
1236void UpdateAttempterTest::CheckStagingOff() {
1237 // Check that all prefs were removed.
1238 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1239 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1240 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1241 // Check that the Omaha parameters have the correct value.
1242 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1243 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1244 attempter_.staging_wait_time_);
1245 EXPECT_FALSE(
1246 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1247 EXPECT_FALSE(
1248 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1249 // Check that scattering is turned off too.
1250 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1251}
1252
1253TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1254 loop_.PostTask(FROM_HERE,
1255 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1256 base::Unretained(this)));
1257 loop_.Run();
1258}
1259
1260void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1261 // Tests that staging is turned off when an interactive update is requested.
1262 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1263 FakePrefs fake_prefs;
1264 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1265
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001266 attempter_.Update(
1267 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001268 CheckStagingOff();
1269
1270 ScheduleQuitMainLoop();
1271}
1272
1273TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1274 loop_.PostTask(FROM_HERE,
1275 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1276 base::Unretained(this)));
1277 loop_.Run();
1278}
1279
1280void UpdateAttempterTest::StagingOffIfOobeStart() {
1281 // Tests that staging is turned off if OOBE hasn't been completed.
1282 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1283 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1284 FakePrefs fake_prefs;
1285 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1286
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001287 attempter_.Update(
1288 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001289 CheckStagingOff();
1290
1291 ScheduleQuitMainLoop();
1292}
1293
David Zeuthen985b1122013-10-09 12:13:15 -07001294// Checks that we only report daily metrics at most every 24 hours.
1295TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1296 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001297 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001298
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001299 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001300 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001301
1302 Time epoch = Time::FromInternalValue(0);
1303 fake_clock.SetWallclockTime(epoch);
1304
1305 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1306 // we should report.
1307 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1308 // We should not report again if no time has passed.
1309 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1310
1311 // We should not report if only 10 hours has passed.
1312 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1313 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1314
1315 // We should not report if only 24 hours - 1 sec has passed.
1316 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1317 TimeDelta::FromSeconds(1));
1318 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1319
1320 // We should report if 24 hours has passed.
1321 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1322 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1323
1324 // But then we should not report again..
1325 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1326
1327 // .. until another 24 hours has passed
1328 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1329 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1330 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1331 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1332 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1333
1334 // .. and another 24 hours
1335 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1336 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1337 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1338 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1339 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1340
1341 // If the span between time of reporting and present time is
1342 // negative, we report. This is in order to reset the timestamp and
1343 // avoid an edge condition whereby a distant point in the future is
1344 // in the state variable resulting in us never ever reporting again.
1345 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1346 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1347 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1348
1349 // In this case we should not update until the clock reads 71 + 24 = 95.
1350 // Check that.
1351 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1352 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1353 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1354 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1355 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001356}
1357
David Zeuthen3c55abd2013-10-14 12:48:03 -07001358TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001359 FakeClock fake_clock;
1360 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001361 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001362 FakePrefs fake_prefs;
1363 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001364 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001365
1366 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001367 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001368
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001369 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001370
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001371 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001372 EXPECT_EQ(boot_time.ToTimeT(), 42);
1373}
1374
David Pursell02c18642014-11-06 11:26:11 -08001375TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1376 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1377 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1378}
1379
1380TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1381 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001382 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001383 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1384}
1385
1386TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1387 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001388 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001389 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1390}
1391
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001392TEST_F(UpdateAttempterTest, CheckForUpdateInteractiveNotIdleFails) {
1393 // GIVEN an update is in progress.
1394 cfu_params_.status = UpdateStatus::CHECKING_FOR_UPDATE;
1395 // GIVEN a interactive update.
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001396
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001397 // THEN |ScheduleUpdates()| should not be called.
1398 cfu_params_.should_schedule_updates_be_called = false;
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001399 // THEN result should indicate failure.
1400 cfu_params_.expected_result = false;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001401
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001402 TestCheckForUpdate();
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001403}
1404
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001405// TODO(b/137217982): Currently, since the logic is to flow through, the app
1406// version and omaha url are cleared.
1407TEST_F(UpdateAttempterTest,
1408 CheckForUpdateNonInteractiveNotIdleOfficialBuildSucceeds) {
1409 // GIVEN an update is in progress.
1410 cfu_params_.status = UpdateStatus::CHECKING_FOR_UPDATE;
1411 // GIVEN a non interactive update.
1412 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1413
1414 // THEN we except forced app version + forced omaha url to be cleared.
1415
1416 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001417}
1418
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001419// TODO(b/137217982): Currently, since the logic is to flow through, the app
1420// version and omaha url are set based on inputs.
1421TEST_F(UpdateAttempterTest,
1422 CheckForUpdateNonInteractiveNotIdleUnofficialBuildSucceeds) {
1423 // GIVEN an update is in progress.
1424 cfu_params_.status = UpdateStatus::CHECKING_FOR_UPDATE;
1425 // GIVEN a non interactive update.
1426 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1427 // GIVEN a non offical build with dev features enabled.
1428 cfu_params_.is_official_build = false;
1429 cfu_params_.are_dev_features_enabled = true;
1430
1431 // THEN the forced app version + forced omaha url changes based on input.
1432 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1433 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1434
1435 TestCheckForUpdate();
1436}
1437
1438TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1439 // GIVEN a official build.
1440
1441 // THEN we except forced app version + forced omaha url to be cleared.
1442
1443 TestCheckForUpdate();
1444}
1445
1446TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
1447 // GIVEN a non offical build with dev features enabled.
1448 cfu_params_.is_official_build = false;
1449 cfu_params_.are_dev_features_enabled = true;
1450
1451 // THEN the forced app version + forced omaha url changes based on input.
1452 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1453 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1454
1455 TestCheckForUpdate();
1456}
1457
1458TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1459 // GIVEN a scheduled autest omaha url.
1460 cfu_params_.omaha_url = "autest-scheduled";
1461
1462 // THEN forced app version is cleared.
1463 // THEN forced omaha url changes to default constant.
1464 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1465
1466 TestCheckForUpdate();
1467}
1468
1469TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1470 // GIVEN a scheduled autest omaha url.
1471 cfu_params_.omaha_url = "autest-scheduled";
1472 // GIVEN a non offical build with dev features enabled.
1473 cfu_params_.is_official_build = false;
1474 cfu_params_.are_dev_features_enabled = true;
1475
1476 // THEN forced app version changes based on input.
1477 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1478 // THEN forced omaha url changes to default constant.
1479 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1480
1481 TestCheckForUpdate();
1482}
1483
1484TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1485 // GIVEN a autest omaha url.
1486 cfu_params_.omaha_url = "autest";
1487
1488 // THEN forced app version is cleared.
1489 // THEN forced omaha url changes to default constant.
1490 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1491
1492 TestCheckForUpdate();
1493}
1494
1495TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1496 // GIVEN a autest omha url.
1497 cfu_params_.omaha_url = "autest";
1498 // GIVEN a non offical build with dev features enabled.
1499 cfu_params_.is_official_build = false;
1500 cfu_params_.are_dev_features_enabled = true;
1501
1502 // THEN forced app version changes based on input.
1503 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1504 // THEN forced omaha url changes to default constant.
1505 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1506
1507 TestCheckForUpdate();
1508}
1509
1510TEST_F(UpdateAttempterTest,
1511 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1512 // GIVEN a scheduled autest omaha url.
1513 cfu_params_.omaha_url = "autest-scheduled";
1514 // GIVEN a non interactive update.
1515 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1516
1517 // THEN forced app version is cleared.
1518 // THEN forced omaha url changes to default constant.
1519 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1520
1521 TestCheckForUpdate();
1522}
1523
1524TEST_F(UpdateAttempterTest,
1525 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1526 // GIVEN a scheduled autest omaha url.
1527 cfu_params_.omaha_url = "autest-scheduled";
1528 // GIVEN a non interactive update.
1529 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1530 // GIVEN a non offical build with dev features enabled.
1531 cfu_params_.is_official_build = false;
1532 cfu_params_.are_dev_features_enabled = true;
1533
1534 // THEN forced app version changes based on input.
1535 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1536 // THEN forced omaha url changes to default constant.
1537 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1538
1539 TestCheckForUpdate();
1540}
1541
1542TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1543 // GIVEN a autest omaha url.
1544 cfu_params_.omaha_url = "autest";
1545 // GIVEN a non interactive update.
1546 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1547
1548 // THEN forced app version is cleared.
1549 // THEN forced omaha url changes to default constant.
1550 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1551
1552 TestCheckForUpdate();
1553}
1554
1555TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1556 // GIVEN a autest omaha url.
1557 cfu_params_.omaha_url = "autest";
1558 // GIVEN a non interactive update.
1559 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1560 // GIVEN a non offical build with dev features enabled.
1561 cfu_params_.is_official_build = false;
1562 cfu_params_.are_dev_features_enabled = true;
1563
1564 // THEN forced app version changes based on input.
1565 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1566 // THEN forced omaha url changes to default constant.
1567 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1568
1569 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001570}
1571
Jae Hoon Kim2b73ac22019-07-02 11:17:24 -07001572TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1573 // GIVEN a official build.
1574 // GIVEN forced callback is not set.
1575 attempter_.set_forced_update_pending_callback(nullptr);
1576
1577 // THEN we except forced app version + forced omaha url to be cleared.
1578 // THEN |ScheduleUpdates()| should not be called.
1579 cfu_params_.should_schedule_updates_be_called = false;
1580
1581 TestCheckForUpdate();
1582}
1583
1584TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
1585 // GIVEN a non offical build with dev features enabled.
1586 cfu_params_.is_official_build = false;
1587 cfu_params_.are_dev_features_enabled = true;
1588 // GIVEN forced callback is not set.
1589 attempter_.set_forced_update_pending_callback(nullptr);
1590
1591 // THEN the forced app version + forced omaha url changes based on input.
1592 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1593 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1594 // THEN |ScheduleUpdates()| should not be called.
1595 cfu_params_.should_schedule_updates_be_called = false;
1596
1597 TestCheckForUpdate();
1598}
1599
Xiaochu Liu88d90382018-08-29 16:09:11 -07001600TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1601 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1602 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1603 attempter_.CheckForInstall({}, "autest");
1604 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1605
1606 attempter_.CheckForInstall({}, "autest-scheduled");
1607 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1608
1609 attempter_.CheckForInstall({}, "http://omaha.phishing");
1610 EXPECT_EQ("", attempter_.forced_omaha_url());
1611}
1612
Colin Howesac170d92018-11-20 16:29:28 -08001613TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1614 attempter_.CheckForInstall({}, "http://foo.bar");
1615 attempter_.status_ = UpdateStatus::DOWNLOADING;
1616 EXPECT_TRUE(attempter_.is_install_);
1617 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1618 UpdateEngineStatus status;
1619 attempter_.GetStatus(&status);
1620 // Should set status to idle after an install operation.
1621 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1622}
1623
Colin Howes978c1082018-12-03 11:46:12 -08001624TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1625 attempter_.is_install_ = true;
1626 attempter_.Rollback(false);
1627 EXPECT_FALSE(attempter_.is_install_);
1628}
1629
1630TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1631 attempter_.is_install_ = true;
1632 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1633 EXPECT_FALSE(attempter_.is_install_);
1634}
1635
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001636TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001637 attempter_.CalculateUpdateParams(
1638 "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001639 EXPECT_EQ("1234",
1640 fake_system_state_.request_params()->target_version_prefix());
1641
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001642 attempter_.CalculateUpdateParams(
1643 "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001644 EXPECT_TRUE(
1645 fake_system_state_.request_params()->target_version_prefix().empty());
1646}
1647
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001648TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1649 attempter_.CalculateUpdateParams("",
1650 "",
1651 "",
1652 "1234",
1653 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001654 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001655 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001656 false,
1657 false);
1658 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001659 EXPECT_EQ(4,
1660 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001661
1662 attempter_.CalculateUpdateParams("",
1663 "",
1664 "",
1665 "1234",
1666 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001667 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001668 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001669 false,
1670 false);
1671 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001672 EXPECT_EQ(4,
1673 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001674}
1675
Aaron Wood23bd3392017-10-06 14:48:25 -07001676TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1677 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1678 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001679 OmahaResponseHandlerAction response_action(&fake_system_state_);
1680 response_action.install_plan_.version = "a.b.c.d";
1681 response_action.install_plan_.system_version = "b.c.d.e";
1682 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001683 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001684 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1685 // completed, with the deferred-update error code.
1686 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001687 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001688 {
1689 UpdateEngineStatus status;
1690 attempter_.GetStatus(&status);
1691 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001692 EXPECT_TRUE(attempter_.install_plan_);
1693 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001694 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001695 status.new_size_bytes);
1696 }
1697 // An "error" event should have been created to tell Omaha that the update is
1698 // being deferred.
1699 EXPECT_TRUE(nullptr != attempter_.error_event_);
1700 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1701 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1702 ErrorCode expected_code = static_cast<ErrorCode>(
1703 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1704 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1705 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1706 // End the processing
1707 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1708 // Validate the state of the attempter.
1709 {
1710 UpdateEngineStatus status;
1711 attempter_.GetStatus(&status);
1712 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001713 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001714 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001715 status.new_size_bytes);
1716 }
1717}
1718
1719TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
Jae Hoon Kim75daa382019-07-02 11:17:24 -07001720 // Default construction for |waiting_for_scheduled_check_| is false.
Aaron Wood23bd3392017-10-06 14:48:25 -07001721 EXPECT_FALSE(attempter_.IsUpdateRunningOrScheduled());
1722 // Verify in-progress update with UPDATE_AVAILABLE is running
1723 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
1724 EXPECT_TRUE(attempter_.IsUpdateRunningOrScheduled());
1725}
1726
Aaron Woodbf5a2522017-10-04 10:58:36 -07001727TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1728 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1729
1730 UpdateCheckParams params = {.updates_enabled = true};
1731 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1732
1733 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1734 attempter_.GetCurrentUpdateAttemptFlags());
1735}
1736
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001737TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1738 UpdateCheckParams params = {.updates_enabled = true,
1739 .rollback_allowed = false};
1740 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1741 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1742}
1743
1744TEST_F(UpdateAttempterTest, RollbackAllowed) {
1745 UpdateCheckParams params = {.updates_enabled = true,
1746 .rollback_allowed = true};
1747 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1748 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1749}
1750
Aaron Wood081c0232017-10-19 17:14:58 -07001751TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1752 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1753
1754 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1755 EXPECT_EQ(UpdateAttemptFlags::kNone,
1756 attempter_.GetCurrentUpdateAttemptFlags());
1757}
1758
1759TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1760 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1761
1762 // This tests that when CheckForUpdate() is called with the non-interactive
1763 // flag set, that it doesn't change the current UpdateAttemptFlags.
1764 attempter_.CheckForUpdate("",
1765 "",
1766 UpdateAttemptFlags::kFlagNonInteractive |
1767 UpdateAttemptFlags::kFlagRestrictDownload);
1768 EXPECT_EQ(UpdateAttemptFlags::kNone,
1769 attempter_.GetCurrentUpdateAttemptFlags());
1770}
1771
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001772void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1773 bool is_policy_loaded,
1774 bool expected_reset) {
1775 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1776 .WillRepeatedly(Return(true));
1777 auto mock_policy_provider =
1778 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1779 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1780 .WillRepeatedly(Return(is_consumer));
1781 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1782 .WillRepeatedly(Return(is_policy_loaded));
1783 const policy::MockDevicePolicy device_policy;
1784 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1785 .WillRepeatedly(ReturnRef(device_policy));
1786 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1787 SetRollbackHappened(false))
1788 .Times(expected_reset ? 1 : 0);
1789 attempter_.policy_provider_ = std::move(mock_policy_provider);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001790 attempter_.Update("", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001791 ScheduleQuitMainLoop();
1792}
1793
1794TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1795 loop_.PostTask(FROM_HERE,
1796 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1797 base::Unretained(this),
1798 /*is_consumer=*/false,
1799 /*is_policy_loaded=*/false,
1800 /*expected_reset=*/false));
1801 loop_.Run();
1802}
1803
1804TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1805 loop_.PostTask(FROM_HERE,
1806 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1807 base::Unretained(this),
1808 /*is_consumer=*/true,
1809 /*is_policy_loaded=*/false,
1810 /*expected_reset=*/true));
1811 loop_.Run();
1812}
1813
1814TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1815 loop_.PostTask(FROM_HERE,
1816 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1817 base::Unretained(this),
1818 /*is_consumer=*/false,
1819 /*is_policy_loaded=*/true,
1820 /*expected_reset=*/true));
1821 loop_.Run();
1822}
1823
Marton Hunyady199152d2018-05-07 19:08:48 +02001824TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001825 attempter_.install_plan_.reset(new InstallPlan);
1826 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001827
1828 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1829 SetRollbackHappened(true))
1830 .Times(1);
1831 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1832}
1833
1834TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001835 attempter_.install_plan_.reset(new InstallPlan);
1836 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001837
1838 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1839 SetRollbackHappened(true))
1840 .Times(0);
1841 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1842}
1843
Marton Hunyadya0302682018-05-16 18:52:13 +02001844TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001845 attempter_.install_plan_.reset(new InstallPlan);
1846 attempter_.install_plan_->is_rollback = true;
1847 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001848
1849 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1850 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1851 .Times(1);
1852 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1853}
1854
1855TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001856 attempter_.install_plan_.reset(new InstallPlan);
1857 attempter_.install_plan_->is_rollback = false;
1858 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001859
1860 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1861 ReportEnterpriseRollbackMetrics(_, _))
1862 .Times(0);
1863 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1864}
1865
1866TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001867 attempter_.install_plan_.reset(new InstallPlan);
1868 attempter_.install_plan_->is_rollback = true;
1869 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001870
1871 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1872 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1873 .Times(1);
1874 MockAction action;
1875 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1876 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1877}
1878
1879TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001880 attempter_.install_plan_.reset(new InstallPlan);
1881 attempter_.install_plan_->is_rollback = false;
1882 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001883
1884 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1885 ReportEnterpriseRollbackMetrics(_, _))
1886 .Times(0);
1887 MockAction action;
1888 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1889 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1890}
1891
May Lippert60aa3ca2018-08-15 16:55:29 -07001892TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1893 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1894 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1895 .Times(0);
1896 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1897}
1898
1899TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1900 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1901 fake_system_state_.set_device_policy(device_policy.get());
1902 // Make device policy return that this is not enterprise enrolled
1903 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1904
1905 // Ensure that the metric is not recorded.
1906 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1907 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1908 .Times(0);
1909 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1910}
1911
1912TEST_F(UpdateAttempterTest,
1913 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1914 constexpr int kDaysToUpdate = 15;
1915 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1916 fake_system_state_.set_device_policy(device_policy.get());
1917 // Make device policy return that this is enterprise enrolled
1918 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1919 // Pretend that there's a time restriction policy in place
1920 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1921 .WillOnce(Return(true));
1922
1923 FakePrefs fake_prefs;
1924 Time update_first_seen_at = Time::Now();
1925 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1926 update_first_seen_at.ToInternalValue());
1927
1928 FakeClock fake_clock;
1929 Time update_finished_at =
1930 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1931 fake_clock.SetWallclockTime(update_finished_at);
1932
1933 fake_system_state_.set_clock(&fake_clock);
1934 fake_system_state_.set_prefs(&fake_prefs);
1935
1936 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1937 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1938 .Times(1);
1939 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1940}
1941
1942TEST_F(UpdateAttempterTest,
1943 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1944 constexpr int kDaysToUpdate = 15;
1945 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1946 fake_system_state_.set_device_policy(device_policy.get());
1947 // Make device policy return that this is enterprise enrolled
1948 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1949 // Pretend that there's no time restriction policy in place
1950 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1951 .WillOnce(Return(false));
1952
1953 FakePrefs fake_prefs;
1954 Time update_first_seen_at = Time::Now();
1955 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1956 update_first_seen_at.ToInternalValue());
1957
1958 FakeClock fake_clock;
1959 Time update_finished_at =
1960 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1961 fake_clock.SetWallclockTime(update_finished_at);
1962
1963 fake_system_state_.set_clock(&fake_clock);
1964 fake_system_state_.set_prefs(&fake_prefs);
1965
1966 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1967 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1968 .Times(1);
1969 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1970}
1971
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001972void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
1973 // Tests that checks if |device_quick_fix_build_token| arrives when
1974 // policy is set and the device is enterprise enrolled based on |set_token|.
1975 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02001976 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1977 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02001978 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001979
1980 if (set_token)
1981 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
1982 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
1983 else
1984 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
1985 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02001986 attempter_.policy_provider_.reset(
1987 new policy::PolicyProvider(std::move(device_policy)));
1988 attempter_.Update("", "", "", "", false, false, 0, false, false);
1989
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001990 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02001991 ScheduleQuitMainLoop();
1992}
1993
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001994TEST_F(UpdateAttempterTest,
1995 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02001996 loop_.PostTask(FROM_HERE,
1997 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001998 base::Unretained(this),
1999 /*set_token=*/true));
2000 loop_.Run();
2001}
2002
2003TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
2004 loop_.PostTask(FROM_HERE,
2005 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
2006 base::Unretained(this),
2007 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02002008 loop_.Run();
2009}
2010
Jae Hoon Kim75daa382019-07-02 11:17:24 -07002011TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2012 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2013 .Times(1);
2014 EXPECT_TRUE(attempter_.ScheduleUpdates());
2015 // Now there is an update scheduled which means that all subsequent
2016 // |ScheduleUpdates()| should fail.
2017 EXPECT_FALSE(attempter_.ScheduleUpdates());
2018 EXPECT_FALSE(attempter_.ScheduleUpdates());
2019 EXPECT_FALSE(attempter_.ScheduleUpdates());
2020}
2021
2022// Critical tests to always make sure that an update is scheduled. The following
2023// unittest(s) try and cover the correctness in synergy between
2024// |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2025// actions that happen in the flow when |UpdateAttempter| get callbacked on
2026// |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
2027void UpdateAttempterTest::TestOnUpdateScheduled() {
2028 // Setup
2029 attempter_.SetWaitingForScheduledCheck(true);
2030 attempter_.DisableUpdate();
2031 attempter_.DisableScheduleUpdates();
2032
2033 // Invocation
2034 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2035
2036 // Verify
2037 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2038 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2039 attempter_.WasScheduleUpdatesCalled());
2040 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2041}
2042
2043TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2044 // GIVEN failed status.
2045
2046 // THEN update should be scheduled.
2047 ous_params_.should_schedule_updates_be_called = true;
2048
2049 TestOnUpdateScheduled();
2050}
2051
2052TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2053 // GIVEN ask me again later status.
2054 ous_params_.status = EvalStatus::kAskMeAgainLater;
2055
2056 // THEN update should be scheduled.
2057 ous_params_.should_schedule_updates_be_called = true;
2058
2059 TestOnUpdateScheduled();
2060}
2061
2062TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2063 // GIVEN continue status.
2064 ous_params_.status = EvalStatus::kContinue;
2065
2066 // THEN update should be scheduled.
2067 ous_params_.should_schedule_updates_be_called = true;
2068
2069 TestOnUpdateScheduled();
2070}
2071
2072TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2073 // GIVEN updates disabled.
2074 ous_params_.params = {.updates_enabled = false};
2075 // GIVEN succeeded status.
2076 ous_params_.status = EvalStatus::kSucceeded;
2077
2078 // THEN update should not be scheduled.
2079
2080 TestOnUpdateScheduled();
2081}
2082
2083TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2084 // GIVEN updates enabled.
2085 ous_params_.params = {.updates_enabled = true};
2086 // GIVEN succeeded status.
2087 ous_params_.status = EvalStatus::kSucceeded;
2088
2089 // THEN update should be called indicating status change.
2090 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2091 ous_params_.should_update_be_called = true;
2092
2093 TestOnUpdateScheduled();
2094}
2095
Darin Petkovf42cc1c2010-09-01 09:03:02 -07002096} // namespace chromeos_update_engine