blob: f20f107fd25eddfb537647f9928184efa2d48451 [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 = "";
103 bool expected_result = true;
104};
105
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800106class MockDlcService : public DlcServiceInterface {
107 public:
108 MOCK_METHOD1(GetInstalled, bool(vector<string>*));
109};
110
111} // namespace
112
Marton Hunyadya0302682018-05-16 18:52:13 +0200113const char kRollbackVersion[] = "10575.39.2";
114
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700115// Test a subclass rather than the main class directly so that we can mock out
Darin Petkovcd1666f2010-09-23 09:53:44 -0700116// methods within the class. There're explicit unit tests for the mocked out
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700117// methods.
118class UpdateAttempterUnderTest : public UpdateAttempter {
119 public:
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700120 explicit UpdateAttempterUnderTest(SystemState* system_state)
121 : UpdateAttempter(system_state, nullptr) {}
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700122
123 // Wrap the update scheduling method, allowing us to opt out of scheduled
124 // updates for testing purposes.
Xiaochu Liu88d90382018-08-29 16:09:11 -0700125 bool ScheduleUpdates() override {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700126 schedule_updates_called_ = true;
127 if (do_schedule_updates_) {
128 UpdateAttempter::ScheduleUpdates();
129 } else {
130 LOG(INFO) << "[TEST] Update scheduling disabled.";
131 }
Xiaochu Liu88d90382018-08-29 16:09:11 -0700132 return true;
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700133 }
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700134
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700135 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
136
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700137 // Indicates whether |ScheduleUpdates()| was called.
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700138 bool schedule_updates_called() const { return schedule_updates_called_; }
139
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700140 // Need to expose following private members of |UpdateAttempter| for tests.
141 const string& forced_app_version() const { return forced_app_version_; }
Alex Deymo60ca1a72015-06-18 18:19:15 -0700142 const string& forced_omaha_url() const { return forced_omaha_url_; }
David Pursell02c18642014-11-06 11:26:11 -0800143
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700144 private:
145 bool schedule_updates_called_ = false;
146 bool do_schedule_updates_ = true;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700147};
148
149class UpdateAttempterTest : public ::testing::Test {
150 protected:
Jay Srinivasan43488792012-06-19 00:25:31 -0700151 UpdateAttempterTest()
Daniel Erate5f6f252017-04-20 12:09:58 -0600152 : certificate_checker_(fake_system_state_.mock_prefs(),
Alex Deymo33e91e72015-12-01 18:26:08 -0300153 &openssl_wrapper_) {
Gilad Arnold1f847232014-04-07 12:07:49 -0700154 // Override system state members.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700155 fake_system_state_.set_connection_manager(&mock_connection_manager);
156 fake_system_state_.set_update_attempter(&attempter_);
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800157 fake_system_state_.set_dlcservice(&mock_dlcservice_);
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700158 fake_system_state_.set_update_manager(&mock_update_manager_);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700159 loop_.SetAsCurrent();
Gilad Arnold1f847232014-04-07 12:07:49 -0700160
Alex Deymo33e91e72015-12-01 18:26:08 -0300161 certificate_checker_.Init();
162
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800163 attempter_.set_forced_update_pending_callback(
164 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
Sen Jiange67bb5b2016-06-20 15:53:56 -0700165 // Finish initializing the attempter.
Gilad Arnold1f847232014-04-07 12:07:49 -0700166 attempter_.Init();
Jay Srinivasan43488792012-06-19 00:25:31 -0700167 }
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700168
Alex Deymo610277e2014-11-11 21:18:11 -0800169 void SetUp() override {
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700170 EXPECT_NE(nullptr, attempter_.system_state_);
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700171 EXPECT_NE(nullptr, attempter_.system_state_->update_manager());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700172 EXPECT_EQ(0, attempter_.http_response_code_);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700173 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700174 EXPECT_EQ(0.0, attempter_.download_progress_);
175 EXPECT_EQ(0, attempter_.last_checked_time_);
176 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700177 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
Alex Deymo8427b4a2014-11-05 14:00:32 -0800178 processor_ = new NiceMock<MockActionProcessor>();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700179 attempter_.processor_.reset(processor_); // Transfers ownership.
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700180 prefs_ = fake_system_state_.mock_prefs();
Gilad Arnold74b5f552014-10-07 08:17:16 -0700181
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700182 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
Gilad Arnold74b5f552014-10-07 08:17:16 -0700183 actual_using_p2p_for_downloading_ = false;
184 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
185 SetUsingP2PForDownloading(_))
186 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
187 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
188 GetUsingP2PForDownloading())
189 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
190 actual_using_p2p_for_sharing_ = false;
191 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
192 SetUsingP2PForSharing(_))
193 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
194 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
195 GetUsingP2PForDownloading())
196 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700197 }
198
Alex Deymo60ca1a72015-06-18 18:19:15 -0700199 public:
200 void ScheduleQuitMainLoop();
Patrick Dubroy7fbbe8a2011-08-01 17:28:22 +0200201
Alex Deymo60ca1a72015-06-18 18:19:15 -0700202 // Callbacks to run the different tests from the main loop.
Darin Petkove6ef2f82011-03-07 17:31:11 -0800203 void UpdateTestStart();
204 void UpdateTestVerify();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700205 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
Chris Sosa76a29ae2013-07-11 17:59:24 -0700206 void RollbackTestVerify();
Thieu Le116fda32011-04-19 11:01:54 -0700207 void PingOmahaTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700208 void ReadScatterFactorFromPolicyTestStart();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700209 void DecrementUpdateCheckCountTestStart();
Jay Srinivasan08fce042012-06-07 16:31:01 -0700210 void NoScatteringDoneDuringManualUpdateTestStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700211 void P2PNotEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700212 void P2PEnabledStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700213 void P2PEnabledInteractiveStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700214 void P2PEnabledStartingFailsStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700215 void P2PEnabledHousekeepingFailsStart();
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700216 void SessionIdTestChange();
217 void SessionIdTestEnforceEmptyStrPingOmaha();
218 void SessionIdTestConsistencyInUpdateFlow();
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700219 void SessionIdTestInDownloadAction();
Amr Aboelkher21ac9962019-05-15 14:50:05 +0200220 void UpdateToQuickFixBuildStart(bool set_token);
Marton Hunyadye58bddb2018-04-10 20:27:26 +0200221 void ResetRollbackHappenedStart(bool is_consumer,
222 bool is_policy_available,
223 bool expected_reset);
Adolfo Victoria497044c2018-07-18 07:51:42 -0700224 // Staging related callbacks.
225 void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
226 void CheckStagingOff();
227 void StagingSetsPrefsAndTurnsOffScatteringStart();
228 void StagingOffIfInteractiveStart();
229 void StagingOffIfOobeStart();
David Zeuthen8f191b22013-08-06 12:27:50 -0700230
Gilad Arnold74b5f552014-10-07 08:17:16 -0700231 bool actual_using_p2p_for_downloading() {
232 return actual_using_p2p_for_downloading_;
233 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800234 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700235
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700236 // |CheckForUpdate()| related member functions.
237 void TestCheckForUpdate();
238
Alex Deymo0b3db6b2015-08-10 15:19:37 -0700239 base::MessageLoopForIO base_loop_;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700240 brillo::BaseMessageLoop loop_{&base_loop_};
Alex Deymo60ca1a72015-06-18 18:19:15 -0700241
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700242 FakeSystemState fake_system_state_;
Jeffrey Kardatzkecf5f1f12017-10-02 16:08:44 -0700243 UpdateAttempterUnderTest attempter_{&fake_system_state_};
Alex Deymo33e91e72015-12-01 18:26:08 -0300244 OpenSSLWrapper openssl_wrapper_;
245 CertificateChecker certificate_checker_;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -0800246 MockDlcService mock_dlcservice_;
Jae Hoon Kim504c3cb2019-07-02 11:17:24 -0700247 MockUpdateManager mock_update_manager_;
Alex Deymo30534502015-07-20 15:06:33 -0700248
Alex Deymo8427b4a2014-11-05 14:00:32 -0800249 NiceMock<MockActionProcessor>* processor_;
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700250 NiceMock<MockPrefs>*
251 prefs_; // Shortcut to |fake_system_state_->mock_prefs()|.
Jay Srinivasan55f50c22013-01-10 19:24:35 -0800252 NiceMock<MockConnectionManager> mock_connection_manager;
Gilad Arnoldeff87cc2013-07-22 18:32:09 -0700253
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700254 // |CheckForUpdate()| test params.
255 CheckForUpdateTestParams cfu_params_;
256
Gilad Arnold74b5f552014-10-07 08:17:16 -0700257 bool actual_using_p2p_for_downloading_;
258 bool actual_using_p2p_for_sharing_;
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700259};
260
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -0700261void UpdateAttempterTest::TestCheckForUpdate() {
262 // Setup
263 attempter_.status_ = cfu_params_.status;
264 fake_system_state_.fake_hardware()->SetIsOfficialBuild(
265 cfu_params_.is_official_build);
266 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(
267 cfu_params_.are_dev_features_enabled);
268
269 // Invocation
270 EXPECT_EQ(
271 cfu_params_.expected_result,
272 attempter_.CheckForUpdate(
273 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
274
275 // Verify
276 EXPECT_EQ(cfu_params_.expected_forced_app_version,
277 attempter_.forced_app_version());
278 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
279 attempter_.forced_omaha_url());
280}
281
Alex Deymo60ca1a72015-06-18 18:19:15 -0700282void UpdateAttempterTest::ScheduleQuitMainLoop() {
Luis Hector Chavezf1cf3482016-07-19 14:29:19 -0700283 loop_.PostTask(
284 FROM_HERE,
285 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
286 base::Unretained(&loop_)));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700287}
288
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700289void UpdateAttempterTest::SessionIdTestChange() {
290 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
291 const auto old_session_id = attempter_.session_id_;
292 attempter_.Update("", "", "", "", false, false, 0, false, false);
293 EXPECT_NE(old_session_id, attempter_.session_id_);
294 ScheduleQuitMainLoop();
295}
296
297TEST_F(UpdateAttempterTest, SessionIdTestChange) {
298 loop_.PostTask(FROM_HERE,
299 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
300 base::Unretained(this)));
301 loop_.Run();
302}
303
304void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
305 // The |session_id_| should not be changed and should remain as an empty
306 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
307 // and |PingOmaha()| is called.
308 attempter_.DisableScheduleUpdates();
309 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
310 const auto old_session_id = attempter_.session_id_;
311 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
312 if (aa->Type() == OmahaRequestAction::StaticType()) {
313 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
314 }
315 };
316 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
317 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
318 EXPECT_CALL(*processor_, StartProcessing());
319 attempter_.PingOmaha();
320 EXPECT_EQ(old_session_id, attempter_.session_id_);
321 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
322 ScheduleQuitMainLoop();
323}
324
325TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
326 loop_.PostTask(
327 FROM_HERE,
328 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
329 base::Unretained(this)));
330 loop_.Run();
331}
332
333void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
334 // All session IDs passed into |OmahaRequestActions| should be enforced to
335 // have the same value in |BuildUpdateActions()|.
336 unordered_set<string> session_ids;
337 // Gather all the session IDs being passed to |OmahaRequestActions|.
338 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
339 if (aa->Type() == OmahaRequestAction::StaticType())
340 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
341 };
342 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
343 .WillRepeatedly(Invoke(CheckSessionId));
344 attempter_.BuildUpdateActions(false);
345 // Validate that all the session IDs are the same.
346 EXPECT_EQ(1, session_ids.size());
347 ScheduleQuitMainLoop();
348}
349
350TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
351 loop_.PostTask(
352 FROM_HERE,
353 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
354 base::Unretained(this)));
355 loop_.Run();
356}
357
Jae Hoon Kim0ae8fe12019-06-26 14:32:50 -0700358void UpdateAttempterTest::SessionIdTestInDownloadAction() {
359 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
360 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
361 string header_value;
362 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
363 if (aa->Type() == DownloadAction::StaticType()) {
364 DownloadAction* da = static_cast<DownloadAction*>(aa);
365 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
366 &header_value));
367 }
368 };
369 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
370 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
371 attempter_.BuildUpdateActions(false);
372 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
373 EXPECT_EQ(attempter_.session_id_, header_value);
374 ScheduleQuitMainLoop();
375}
376
377TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
378 loop_.PostTask(FROM_HERE,
379 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
380 base::Unretained(this)));
381 loop_.Run();
382}
383
Darin Petkov1b003102010-11-30 10:18:36 -0800384TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700385 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800386 fetcher->FailTransfer(503); // Sets the HTTP response code.
Amin Hassani7ecda262017-07-11 17:10:50 -0700387 DownloadAction action(prefs_,
388 nullptr,
389 nullptr,
390 nullptr,
391 fetcher.release(),
Amin Hassanied37d682018-04-06 13:22:00 -0700392 false /* interactive */);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800393 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700394 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700395 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
Aaron Wood9321f502017-09-07 11:18:54 -0700396 EXPECT_EQ(0.0, attempter_.download_progress_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700397 ASSERT_EQ(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800398}
399
400TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800401 MockAction action;
402 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700403 attempter_.status_ = UpdateStatus::DOWNLOADING;
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800404 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov1b003102010-11-30 10:18:36 -0800405 .WillOnce(Return(false));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700406 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
407 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov1b003102010-11-30 10:18:36 -0800408}
409
Aaron Wood9321f502017-09-07 11:18:54 -0700410TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
411 // Simple test case, where all the values match (nothing was skipped)
412 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
413 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
414 uint64_t bytes_received_1 = bytes_progressed_1;
415 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
416 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
417
418 double progress_1 =
419 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
420 double progress_2 =
421 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
422
423 EXPECT_EQ(0.0, attempter_.download_progress_);
424 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700425 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700426 attempter_.new_payload_size_ = bytes_total;
427 NiceMock<MockServiceObserver> observer;
428 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700429 SendStatusUpdate(AllOf(
430 Field(&UpdateEngineStatus::progress, progress_1),
431 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
432 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700433 EXPECT_CALL(observer,
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700434 SendStatusUpdate(AllOf(
435 Field(&UpdateEngineStatus::progress, progress_2),
436 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
437 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700438 attempter_.AddObserver(&observer);
439 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
440 EXPECT_EQ(progress_1, attempter_.download_progress_);
441 // This iteration validates that a later set of updates to the variables are
442 // properly handled (so that |getStatus()| will return the same progress info
443 // as the callback is receiving.
444 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
445 EXPECT_EQ(progress_2, attempter_.download_progress_);
446}
447
448TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700449 // The transition into |UpdateStatus::DOWNLOADING| happens when the
Aaron Wood9321f502017-09-07 11:18:54 -0700450 // first bytes are received.
451 uint64_t bytes_progressed = 1024 * 1024; // 1MB
452 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
453 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
454 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
455 // This is set via inspecting the InstallPlan payloads when the
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700456 // |OmahaResponseAction| is completed.
Aaron Wood9321f502017-09-07 11:18:54 -0700457 attempter_.new_payload_size_ = bytes_total;
458 EXPECT_EQ(0.0, attempter_.download_progress_);
459 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700460 EXPECT_CALL(observer,
461 SendStatusUpdate(AllOf(
462 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
463 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700464 attempter_.AddObserver(&observer);
465 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
466 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
467}
468
469TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
470 // There is a special case to ensure that at 100% downloaded,
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700471 // |download_progress_| is updated and broadcastest.
Aaron Wood9321f502017-09-07 11:18:54 -0700472 uint64_t bytes_progressed = 0; // ignored
473 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
474 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
475 attempter_.status_ = UpdateStatus::DOWNLOADING;
476 attempter_.new_payload_size_ = bytes_total;
477 EXPECT_EQ(0.0, attempter_.download_progress_);
478 NiceMock<MockServiceObserver> observer;
Aaron Wood7f92e2b2017-08-28 14:51:21 -0700479 EXPECT_CALL(observer,
480 SendStatusUpdate(AllOf(
481 Field(&UpdateEngineStatus::progress, 1.0),
482 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
483 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
Aaron Wood9321f502017-09-07 11:18:54 -0700484 attempter_.AddObserver(&observer);
485 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
486 EXPECT_EQ(1.0, attempter_.download_progress_);
487}
488
Darin Petkov1b003102010-11-30 10:18:36 -0800489TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
Ben Chan02f7c1d2014-10-18 15:18:02 -0700490 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
Darin Petkov1b003102010-11-30 10:18:36 -0800491 fetcher->FailTransfer(500); // Sets the HTTP response code.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800492 OmahaRequestAction action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700493 &fake_system_state_, nullptr, std::move(fetcher), false, "");
Darin Petkov1b003102010-11-30 10:18:36 -0800494 ObjectCollectorAction<OmahaResponse> collector_action;
495 BondActions(&action, &collector_action);
496 OmahaResponse response;
497 response.poll_interval = 234;
498 action.SetOutputObject(response);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800499 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700500 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
Darin Petkov1b003102010-11-30 10:18:36 -0800501 EXPECT_EQ(500, attempter_.http_response_code());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700502 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
Alex Deymo80f70ff2016-02-10 16:08:11 -0800503 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700504 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
Darin Petkov1b003102010-11-30 10:18:36 -0800505}
506
Alex Deymo30534502015-07-20 15:06:33 -0700507TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
Alex Deymo906191f2015-10-12 12:22:44 -0700508 FakePrefs fake_prefs;
509 string boot_id;
510 EXPECT_TRUE(utils::GetBootId(&boot_id));
511 fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
512 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -0700513 attempter_.Init();
514 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700515}
516
517TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700518 EXPECT_EQ(ErrorCode::kSuccess,
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700519 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700520
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700521 FakeSystemState fake_system_state;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800522 OmahaRequestAction omaha_request_action(
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700523 &fake_system_state, nullptr, nullptr, false, "");
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700524 EXPECT_EQ(ErrorCode::kOmahaRequestError,
525 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700526 OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800527 EXPECT_EQ(
528 ErrorCode::kOmahaResponseHandlerError,
529 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
Sen Jiange6e4bb92016-04-05 14:59:12 -0700530 FilesystemVerifierAction filesystem_verifier_action;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800531 EXPECT_EQ(
532 ErrorCode::kFilesystemVerifierError,
533 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
Alex Deymob15a0b82015-11-25 20:30:40 -0300534 PostinstallRunnerAction postinstall_runner_action(
Alex Deymofb905d92016-06-03 19:26:58 -0700535 fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800536 EXPECT_EQ(
537 ErrorCode::kPostinstallRunnerError,
538 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
Alex Deymo8427b4a2014-11-05 14:00:32 -0800539 MockAction action_mock;
540 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700541 EXPECT_EQ(ErrorCode::kError,
542 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700543}
544
Darin Petkov36275772010-10-01 11:40:57 -0700545TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700546 attempter_.omaha_request_params_->set_delta_okay(true);
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800547 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700548 .WillOnce(Return(false));
549 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700550 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800551 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800552 .WillOnce(
553 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
554 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700555 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700556 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800557 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800558 .WillOnce(
559 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
560 Return(true)));
Darin Petkov36275772010-10-01 11:40:57 -0700561 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700562 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800563 EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
Darin Petkov36275772010-10-01 11:40:57 -0700564 attempter_.DisableDeltaUpdateIfNeeded();
Jay Srinivasanae4697c2013-03-18 17:08:08 -0700565 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
Darin Petkov36275772010-10-01 11:40:57 -0700566}
567
568TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800569 EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
Darin Petkov36275772010-10-01 11:40:57 -0700570 .WillOnce(Return(false))
Ben Chan672c1f52017-10-23 15:41:39 -0700571 .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
572 .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800573 .WillOnce(
574 DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
575 Return(true)));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800576 EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
Darin Petkov2dd01092010-10-08 15:43:05 -0700577 .WillRepeatedly(Return(true));
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800578 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700579 EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800580 EXPECT_CALL(*prefs_,
581 SetInt64(kPrefsDeltaUpdateFailures,
582 UpdateAttempter::kMaxDeltaUpdateFailures + 1));
583 for (int i = 0; i < 4; i++)
Darin Petkov36275772010-10-01 11:40:57 -0700584 attempter_.MarkDeltaUpdateFailure();
585}
586
Darin Petkov1b003102010-11-30 10:18:36 -0800587TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
588 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
589 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700590 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
Jay Srinivasan6f6ea002012-12-14 11:26:28 -0800591 .Times(0);
592 OmahaResponse response;
Jay Srinivasan53173b92013-05-17 17:13:01 -0700593 string url1 = "http://url1";
Sen Jiang0affc2c2017-02-10 15:55:05 -0800594 response.packages.push_back({.payload_urls = {url1, "https://url"}});
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700595 EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
Jay Srinivasan53173b92013-05-17 17:13:01 -0700596 .WillRepeatedly(Return(url1));
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700597 fake_system_state_.mock_payload_state()->SetResponse(response);
Darin Petkov1b003102010-11-30 10:18:36 -0800598 attempter_.ScheduleErrorEventAction();
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700599 EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
Darin Petkov1b003102010-11-30 10:18:36 -0800600}
601
602TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
603 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700604 EnqueueAction(Pointee(Property(
605 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700606 EXPECT_CALL(*processor_, StartProcessing());
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700607 ErrorCode err = ErrorCode::kError;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700608 EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800609 attempter_.error_event_.reset(new OmahaEvent(
610 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
Darin Petkov1b003102010-11-30 10:18:36 -0800611 attempter_.ScheduleErrorEventAction();
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700612 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
Darin Petkov1b003102010-11-30 10:18:36 -0800613}
614
Darin Petkove6ef2f82011-03-07 17:31:11 -0800615namespace {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700616// Actions that will be built as part of an update check.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200617vector<string> GetUpdateActionTypes() {
618 return {OmahaRequestAction::StaticType(),
619 OmahaResponseHandlerAction::StaticType(),
620 UpdateBootFlagsAction::StaticType(),
621 OmahaRequestAction::StaticType(),
622 DownloadAction::StaticType(),
623 OmahaRequestAction::StaticType(),
624 FilesystemVerifierAction::StaticType(),
625 PostinstallRunnerAction::StaticType(),
626 OmahaRequestAction::StaticType()};
627}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700628
629// Actions that will be built as part of a user-initiated rollback.
Askar Aitzhan570ca872019-04-24 11:16:12 +0200630vector<string> GetRollbackActionTypes() {
631 return {InstallPlanAction::StaticType(),
632 PostinstallRunnerAction::StaticType()};
633}
Chris Sosa76a29ae2013-07-11 17:59:24 -0700634
Adolfo Victoria497044c2018-07-18 07:51:42 -0700635const StagingSchedule kValidStagingSchedule = {
636 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
637
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700638} // namespace
Darin Petkove6ef2f82011-03-07 17:31:11 -0800639
640void UpdateAttempterTest::UpdateTestStart() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700641 attempter_.set_http_response_code(200);
Alex Deymo749ecf12014-10-21 20:06:57 -0700642
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700643 // Expect that the device policy is loaded by the |UpdateAttempter| at some
644 // point by calling |RefreshDevicePolicy()|.
Igor9fd76b62017-12-11 15:24:18 +0100645 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Alex Deymo749ecf12014-10-21 20:06:57 -0700646 EXPECT_CALL(*device_policy, LoadPolicy())
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800647 .Times(testing::AtLeast(1))
648 .WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100649 attempter_.policy_provider_.reset(
650 new policy::PolicyProvider(std::move(device_policy)));
Alex Deymo749ecf12014-10-21 20:06:57 -0700651
652 {
653 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200654 for (const auto& update_action_type : GetUpdateActionTypes()) {
Alex Deymo749ecf12014-10-21 20:06:57 -0700655 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700656 EnqueueAction(Pointee(
Askar Aitzhan570ca872019-04-24 11:16:12 +0200657 Property(&AbstractAction::Type, update_action_type))));
Alex Deymo749ecf12014-10-21 20:06:57 -0700658 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700659 EXPECT_CALL(*processor_, StartProcessing());
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700660 }
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700661
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800662 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700663 loop_.PostTask(FROM_HERE,
664 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
665 base::Unretained(this)));
Darin Petkove6ef2f82011-03-07 17:31:11 -0800666}
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700667
Darin Petkove6ef2f82011-03-07 17:31:11 -0800668void UpdateAttempterTest::UpdateTestVerify() {
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700669 EXPECT_EQ(0, attempter_.http_response_code());
670 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700671 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700672 loop_.BreakLoop();
Darin Petkove6ef2f82011-03-07 17:31:11 -0800673}
674
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800675void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
676 bool valid_slot) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700677 // Create a device policy so that we can change settings.
Igor9fd76b62017-12-11 15:24:18 +0100678 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700679 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100680 fake_system_state_.set_device_policy(device_policy.get());
681 if (enterprise_rollback) {
682 // We return an empty owner as this is an enterprise.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800683 EXPECT_CALL(*device_policy, GetOwner(_))
684 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100685 } else {
686 // We return a fake owner as this is an owned consumer device.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800687 EXPECT_CALL(*device_policy, GetOwner(_))
688 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
689 Return(true)));
Igor9fd76b62017-12-11 15:24:18 +0100690 }
691
692 attempter_.policy_provider_.reset(
693 new policy::PolicyProvider(std::move(device_policy)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700694
Alex Deymo763e7db2015-08-27 21:08:08 -0700695 if (valid_slot) {
696 BootControlInterface::Slot rollback_slot = 1;
697 LOG(INFO) << "Test Mark Bootable: "
698 << BootControlInterface::SlotName(rollback_slot);
Alex Deymoe5e5fe92015-10-05 09:28:19 -0700699 fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
700 true);
Don Garrett6646b442013-11-13 15:29:11 -0800701 }
702
Chris Sosa28e479c2013-07-12 11:39:53 -0700703 bool is_rollback_allowed = false;
Chris Sosa76a29ae2013-07-11 17:59:24 -0700704
Chris Sosad38b1132014-03-25 10:43:59 -0700705 // We only allow rollback on devices that are not enterprise enrolled and
706 // which have a valid slot to rollback to.
707 if (!enterprise_rollback && valid_slot) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800708 is_rollback_allowed = true;
Chris Sosa28e479c2013-07-12 11:39:53 -0700709 }
710
Chris Sosa28e479c2013-07-12 11:39:53 -0700711 if (is_rollback_allowed) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700712 InSequence s;
Askar Aitzhan570ca872019-04-24 11:16:12 +0200713 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
Chris Sosa76a29ae2013-07-11 17:59:24 -0700714 EXPECT_CALL(*processor_,
Askar Aitzhan570ca872019-04-24 11:16:12 +0200715 EnqueueAction(Pointee(
716 Property(&AbstractAction::Type, rollback_action_type))));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700717 }
Gilad Arnold74b5f552014-10-07 08:17:16 -0700718 EXPECT_CALL(*processor_, StartProcessing());
Chris Sosa76a29ae2013-07-11 17:59:24 -0700719
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700720 EXPECT_TRUE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700721 loop_.PostTask(FROM_HERE,
722 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
723 base::Unretained(this)));
Chris Sosa76a29ae2013-07-11 17:59:24 -0700724 } else {
Chris Sosa44b9b7e2014-04-02 13:53:46 -0700725 EXPECT_FALSE(attempter_.Rollback(true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700726 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700727 }
728}
729
730void UpdateAttempterTest::RollbackTestVerify() {
731 // Verifies the actions that were enqueued.
732 EXPECT_EQ(&attempter_, processor_->delegate());
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700733 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700734 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
735 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700736 loop_.BreakLoop();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700737}
738
Darin Petkove6ef2f82011-03-07 17:31:11 -0800739TEST_F(UpdateAttempterTest, UpdateTest) {
Alex Deymo461b2592015-07-24 20:10:52 -0700740 UpdateTestStart();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700741 loop_.Run();
Darin Petkovf42cc1c2010-09-01 09:03:02 -0700742}
743
Chris Sosa76a29ae2013-07-11 17:59:24 -0700744TEST_F(UpdateAttempterTest, RollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700745 loop_.PostTask(FROM_HERE,
746 base::Bind(&UpdateAttempterTest::RollbackTestStart,
747 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800748 false,
749 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700750 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700751}
752
Don Garrett6646b442013-11-13 15:29:11 -0800753TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700754 loop_.PostTask(FROM_HERE,
755 base::Bind(&UpdateAttempterTest::RollbackTestStart,
756 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800757 false,
758 false));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700759 loop_.Run();
Don Garrett6646b442013-11-13 15:29:11 -0800760}
761
Chris Sosa76a29ae2013-07-11 17:59:24 -0700762TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700763 loop_.PostTask(FROM_HERE,
764 base::Bind(&UpdateAttempterTest::RollbackTestStart,
765 base::Unretained(this),
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800766 true,
767 true));
Alex Deymo60ca1a72015-06-18 18:19:15 -0700768 loop_.Run();
Chris Sosa76a29ae2013-07-11 17:59:24 -0700769}
770
Thieu Le116fda32011-04-19 11:01:54 -0700771void UpdateAttempterTest::PingOmahaTestStart() {
772 EXPECT_CALL(*processor_,
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700773 EnqueueAction(Pointee(Property(
774 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
Gilad Arnold74b5f552014-10-07 08:17:16 -0700775 EXPECT_CALL(*processor_, StartProcessing());
Thieu Le116fda32011-04-19 11:01:54 -0700776 attempter_.PingOmaha();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700777 ScheduleQuitMainLoop();
Thieu Le116fda32011-04-19 11:01:54 -0700778}
779
780TEST_F(UpdateAttempterTest, PingOmahaTest) {
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700781 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
782 EXPECT_FALSE(attempter_.schedule_updates_called());
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700783 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700784 // testing, which is more permissive than we want to handle here.
785 attempter_.DisableScheduleUpdates();
Alex Deymo60ca1a72015-06-18 18:19:15 -0700786 loop_.PostTask(FROM_HERE,
787 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
788 base::Unretained(this)));
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700789 brillo::MessageLoopRunMaxIterations(&loop_, 100);
Christopher Wiley6b6cc1b2015-10-05 17:50:07 -0700790 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
Gilad Arnoldec7f9162014-07-15 13:24:46 -0700791 EXPECT_TRUE(attempter_.schedule_updates_called());
Thieu Le116fda32011-04-19 11:01:54 -0700792}
793
Darin Petkov18c7bce2011-06-16 14:07:00 -0700794TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
Alex Deymo8427b4a2014-11-05 14:00:32 -0800795 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700796 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700797 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700798 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700799 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
800 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700801 EXPECT_EQ(
802 static_cast<ErrorCode>(static_cast<int>(kCode) |
803 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
804 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700805}
806
807TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -0700808 attempter_.install_plan_.reset(new InstallPlan);
809 attempter_.install_plan_->is_resume = true;
Alex Deymo8427b4a2014-11-05 14:00:32 -0800810 MockAction action;
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700811 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
Darin Petkov18c7bce2011-06-16 14:07:00 -0700812 attempter_.CreatePendingErrorEvent(&action, kCode);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700813 ASSERT_NE(nullptr, attempter_.error_event_.get());
Darin Petkov18c7bce2011-06-16 14:07:00 -0700814 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
815 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700816 EXPECT_EQ(
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800817 static_cast<ErrorCode>(static_cast<int>(kCode) |
818 static_cast<int>(ErrorCode::kResumedFlag) |
819 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
Gilad Arnoldd1c4d2d2014-06-05 14:07:53 -0700820 attempter_.error_event_->error_code);
Darin Petkov18c7bce2011-06-16 14:07:00 -0700821}
822
David Zeuthen8f191b22013-08-06 12:27:50 -0700823TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
824 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700825 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700826 mock_p2p_manager.fake().SetP2PEnabled(false);
827 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
828 attempter_.UpdateEngineStarted();
829}
830
831TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
832 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700833 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700834 mock_p2p_manager.fake().SetP2PEnabled(true);
835 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
836 attempter_.UpdateEngineStarted();
837}
838
839TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
840 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700841 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700842 mock_p2p_manager.fake().SetP2PEnabled(true);
843 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700844 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
David Zeuthen8f191b22013-08-06 12:27:50 -0700845 attempter_.UpdateEngineStarted();
846}
847
848TEST_F(UpdateAttempterTest, P2PNotEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700849 loop_.PostTask(FROM_HERE,
850 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
851 base::Unretained(this)));
852 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700853}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700854
David Zeuthen8f191b22013-08-06 12:27:50 -0700855void UpdateAttempterTest::P2PNotEnabledStart() {
856 // If P2P is not enabled, check that we do not attempt housekeeping
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700857 // and do not convey that P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700858 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700859 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700860 mock_p2p_manager.fake().SetP2PEnabled(false);
861 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800862 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo60ca1a72015-06-18 18:19:15 -0700863 EXPECT_FALSE(actual_using_p2p_for_downloading_);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700864 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700865 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700866}
867
868TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700869 loop_.PostTask(FROM_HERE,
870 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
871 base::Unretained(this)));
872 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700873}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700874
David Zeuthen8f191b22013-08-06 12:27:50 -0700875void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700876 // If P2P is enabled, but starting it fails ensure we don't do
877 // any housekeeping and do not convey that P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700878 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700879 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700880 mock_p2p_manager.fake().SetP2PEnabled(true);
881 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
882 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
883 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800884 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700885 EXPECT_FALSE(actual_using_p2p_for_downloading());
886 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700887 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700888}
889
890TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700891 loop_.PostTask(
892 FROM_HERE,
893 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
894 base::Unretained(this)));
895 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700896}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700897
David Zeuthen8f191b22013-08-06 12:27:50 -0700898void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700899 // If P2P is enabled, starting it works but housekeeping fails, ensure
900 // we do not convey P2P is to be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700901 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700902 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700903 mock_p2p_manager.fake().SetP2PEnabled(true);
904 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
905 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700906 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800907 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700908 EXPECT_FALSE(actual_using_p2p_for_downloading());
909 EXPECT_FALSE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700910 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700911}
912
913TEST_F(UpdateAttempterTest, P2PEnabled) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700914 loop_.PostTask(FROM_HERE,
915 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
916 base::Unretained(this)));
917 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700918}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700919
David Zeuthen8f191b22013-08-06 12:27:50 -0700920void UpdateAttempterTest::P2PEnabledStart() {
921 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700922 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700923 // If P2P is enabled and starting it works, check that we performed
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700924 // housekeeping and that we convey P2P should be used.
David Zeuthen8f191b22013-08-06 12:27:50 -0700925 mock_p2p_manager.fake().SetP2PEnabled(true);
926 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
927 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700928 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800929 attempter_.Update("", "", "", "", false, false, 0, false, false);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700930 EXPECT_TRUE(actual_using_p2p_for_downloading());
931 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700932 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700933}
934
935TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700936 loop_.PostTask(FROM_HERE,
937 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
938 base::Unretained(this)));
939 loop_.Run();
David Zeuthen8f191b22013-08-06 12:27:50 -0700940}
Alex Deymo60ca1a72015-06-18 18:19:15 -0700941
David Zeuthen8f191b22013-08-06 12:27:50 -0700942void UpdateAttempterTest::P2PEnabledInteractiveStart() {
943 MockP2PManager mock_p2p_manager;
Gilad Arnold5bb4c902014-04-10 12:32:13 -0700944 fake_system_state_.set_p2p_manager(&mock_p2p_manager);
David Zeuthen8f191b22013-08-06 12:27:50 -0700945 // For an interactive check, if P2P is enabled and starting it
946 // works, check that we performed housekeeping and that we convey
Jae Hoon Kimedb65502019-06-14 11:52:17 -0700947 // P2P should be used for sharing but NOT for downloading.
David Zeuthen8f191b22013-08-06 12:27:50 -0700948 mock_p2p_manager.fake().SetP2PEnabled(true);
949 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
950 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700951 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200952 attempter_.Update("",
953 "",
954 "",
955 "",
956 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800957 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -0700958 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +0200959 false,
960 /*interactive=*/true);
Gilad Arnold74b5f552014-10-07 08:17:16 -0700961 EXPECT_FALSE(actual_using_p2p_for_downloading());
962 EXPECT_TRUE(actual_using_p2p_for_sharing());
Alex Deymo60ca1a72015-06-18 18:19:15 -0700963 ScheduleQuitMainLoop();
David Zeuthen8f191b22013-08-06 12:27:50 -0700964}
965
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700966TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700967 loop_.PostTask(
968 FROM_HERE,
969 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
970 base::Unretained(this)));
971 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700972}
973
974// Tests that the scatter_factor_in_seconds value is properly fetched
975// from the device policy.
976void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
Ben Chan9abb7632014-08-07 00:10:53 -0700977 int64_t scatter_factor_in_seconds = 36000;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700978
Igor9fd76b62017-12-11 15:24:18 +0100979 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700980 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +0100981 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700982
983 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800984 .WillRepeatedly(
985 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700986
Igor9fd76b62017-12-11 15:24:18 +0100987 attempter_.policy_provider_.reset(
988 new policy::PolicyProvider(std::move(device_policy)));
989
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -0800990 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700991 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
992
Alex Deymo60ca1a72015-06-18 18:19:15 -0700993 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -0700994}
995
996TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
Alex Deymo60ca1a72015-06-18 18:19:15 -0700997 loop_.PostTask(
998 FROM_HERE,
999 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1000 base::Unretained(this)));
1001 loop_.Run();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001002}
1003
1004void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1005 // Tests that the scatter_factor_in_seconds value is properly fetched
1006 // from the device policy and is decremented if value > 0.
Ben Chan9abb7632014-08-07 00:10:53 -07001007 int64_t initial_value = 5;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001008 FakePrefs fake_prefs;
1009 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001010
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001011 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001012
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001013 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001014
Ben Chan9abb7632014-08-07 00:10:53 -07001015 int64_t scatter_factor_in_seconds = 10;
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001016
Igor9fd76b62017-12-11 15:24:18 +01001017 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001018 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001019 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001020
1021 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001022 .WillRepeatedly(
1023 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001024
Igor9fd76b62017-12-11 15:24:18 +01001025 attempter_.policy_provider_.reset(
1026 new policy::PolicyProvider(std::move(device_policy)));
1027
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001028 attempter_.Update("", "", "", "", false, false, 0, false, false);
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001029 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1030
1031 // Make sure the file still exists.
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001032 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001033
Ben Chan9abb7632014-08-07 00:10:53 -07001034 int64_t new_value;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001035 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001036 EXPECT_EQ(initial_value - 1, new_value);
1037
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001038 EXPECT_TRUE(
1039 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001040
1041 // However, if the count is already 0, it's not decremented. Test that.
1042 initial_value = 0;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001043 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001044 attempter_.Update("", "", "", "", false, false, 0, false, false);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001045 EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
1046 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001047 EXPECT_EQ(initial_value, new_value);
1048
Alex Deymo60ca1a72015-06-18 18:19:15 -07001049 ScheduleQuitMainLoop();
Jay Srinivasan480ddfa2012-06-01 19:15:26 -07001050}
1051
Jay Srinivasan08fce042012-06-07 16:31:01 -07001052TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001053 loop_.PostTask(
1054 FROM_HERE,
1055 base::Bind(
1056 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1057 base::Unretained(this)));
Alex Deymo60ca1a72015-06-18 18:19:15 -07001058 loop_.Run();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001059}
1060
1061void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1062 // Tests that no scattering logic is enabled if the update check
1063 // is manually done (as opposed to a scheduled update check)
Ben Chan9abb7632014-08-07 00:10:53 -07001064 int64_t initial_value = 8;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001065 FakePrefs fake_prefs;
1066 attempter_.prefs_ = &fake_prefs;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001067
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001068 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001069 fake_system_state_.set_prefs(&fake_prefs);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001070
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001071 EXPECT_TRUE(
1072 fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001073 EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001074
1075 // make sure scatter_factor is non-zero as scattering is disabled
1076 // otherwise.
Ben Chan9abb7632014-08-07 00:10:53 -07001077 int64_t scatter_factor_in_seconds = 50;
Jay Srinivasan08fce042012-06-07 16:31:01 -07001078
Igor9fd76b62017-12-11 15:24:18 +01001079 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001080 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Igor9fd76b62017-12-11 15:24:18 +01001081 fake_system_state_.set_device_policy(device_policy.get());
Jay Srinivasan08fce042012-06-07 16:31:01 -07001082
1083 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
Amin Hassani7cc8bb02019-01-14 16:29:47 -08001084 .WillRepeatedly(
1085 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001086
Igor9fd76b62017-12-11 15:24:18 +01001087 attempter_.policy_provider_.reset(
1088 new policy::PolicyProvider(std::move(device_policy)));
1089
Gilad Arnoldb92f0df2013-01-10 16:32:45 -08001090 // Trigger an interactive check so we can test that scattering is disabled.
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001091 attempter_.Update("",
1092 "",
1093 "",
1094 "",
1095 false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001096 false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001097 /*rollback_allowed_milestones=*/0,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001098 false,
1099 /*interactive=*/true);
Jay Srinivasan08fce042012-06-07 16:31:01 -07001100 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1101
1102 // Make sure scattering is disabled for manual (i.e. user initiated) update
Jay Srinivasan21be0752012-07-25 15:44:56 -07001103 // checks and all artifacts are removed.
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001104 EXPECT_FALSE(
1105 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
Adolfo Victoriad3a1e352018-07-16 11:40:47 -07001106 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
Jay Srinivasanae4697c2013-03-18 17:08:08 -07001107 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1108 EXPECT_FALSE(
1109 attempter_.omaha_request_params_->update_check_count_wait_enabled());
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001110 EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
Jay Srinivasan08fce042012-06-07 16:31:01 -07001111
Alex Deymo60ca1a72015-06-18 18:19:15 -07001112 ScheduleQuitMainLoop();
Jay Srinivasan08fce042012-06-07 16:31:01 -07001113}
1114
Adolfo Victoria497044c2018-07-18 07:51:42 -07001115void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
1116 FakePrefs* prefs) {
1117 attempter_.prefs_ = prefs;
1118 fake_system_state_.set_prefs(prefs);
1119
1120 int64_t initial_value = 8;
1121 EXPECT_TRUE(
1122 prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1123 EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1124 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1125
1126 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1127 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1128 fake_system_state_.set_device_policy(device_policy.get());
1129 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1130 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1131
1132 attempter_.policy_provider_.reset(
1133 new policy::PolicyProvider(std::move(device_policy)));
1134}
1135
1136TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1137 loop_.PostTask(
1138 FROM_HERE,
1139 base::Bind(
1140 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1141 base::Unretained(this)));
1142 loop_.Run();
1143}
1144
1145void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1146 // Tests that staging sets its prefs properly and turns off scattering.
1147 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1148 FakePrefs fake_prefs;
1149 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1150
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001151 attempter_.Update("", "", "", "", false, false, 0, false, false);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001152 // Check that prefs have the correct values.
1153 int64_t update_count;
1154 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
1155 int64_t waiting_time_days;
1156 EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
1157 &waiting_time_days));
1158 EXPECT_GT(waiting_time_days, 0);
1159 // Update count should have been decremented.
1160 EXPECT_EQ(7, update_count);
1161 // Check that Omaha parameters were updated correctly.
1162 EXPECT_TRUE(
1163 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1164 EXPECT_TRUE(
1165 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1166 EXPECT_EQ(waiting_time_days,
1167 attempter_.omaha_request_params_->waiting_period().InDays());
1168 // Check class variables.
1169 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1170 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1171 // Check that scattering is turned off
1172 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1173 EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
1174
1175 ScheduleQuitMainLoop();
1176}
1177
1178void UpdateAttempterTest::CheckStagingOff() {
1179 // Check that all prefs were removed.
1180 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
1181 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1182 EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1183 // Check that the Omaha parameters have the correct value.
1184 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1185 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1186 attempter_.staging_wait_time_);
1187 EXPECT_FALSE(
1188 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1189 EXPECT_FALSE(
1190 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1191 // Check that scattering is turned off too.
1192 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1193}
1194
1195TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1196 loop_.PostTask(FROM_HERE,
1197 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1198 base::Unretained(this)));
1199 loop_.Run();
1200}
1201
1202void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1203 // Tests that staging is turned off when an interactive update is requested.
1204 fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1205 FakePrefs fake_prefs;
1206 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1207
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001208 attempter_.Update(
1209 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001210 CheckStagingOff();
1211
1212 ScheduleQuitMainLoop();
1213}
1214
1215TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1216 loop_.PostTask(FROM_HERE,
1217 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1218 base::Unretained(this)));
1219 loop_.Run();
1220}
1221
1222void UpdateAttempterTest::StagingOffIfOobeStart() {
1223 // Tests that staging is turned off if OOBE hasn't been completed.
1224 fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
1225 fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
1226 FakePrefs fake_prefs;
1227 SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
1228
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001229 attempter_.Update(
1230 "", "", "", "", false, false, 0, false, /* interactive = */ true);
Adolfo Victoria497044c2018-07-18 07:51:42 -07001231 CheckStagingOff();
1232
1233 ScheduleQuitMainLoop();
1234}
1235
David Zeuthen985b1122013-10-09 12:13:15 -07001236// Checks that we only report daily metrics at most every 24 hours.
1237TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1238 FakeClock fake_clock;
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001239 FakePrefs fake_prefs;
David Zeuthen985b1122013-10-09 12:13:15 -07001240
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001241 fake_system_state_.set_clock(&fake_clock);
Alex Deymo2c0db7b2014-11-04 12:23:39 -08001242 fake_system_state_.set_prefs(&fake_prefs);
David Zeuthen985b1122013-10-09 12:13:15 -07001243
1244 Time epoch = Time::FromInternalValue(0);
1245 fake_clock.SetWallclockTime(epoch);
1246
1247 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1248 // we should report.
1249 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1250 // We should not report again if no time has passed.
1251 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1252
1253 // We should not report if only 10 hours has passed.
1254 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
1255 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1256
1257 // We should not report if only 24 hours - 1 sec has passed.
1258 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1259 TimeDelta::FromSeconds(1));
1260 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1261
1262 // We should report if 24 hours has passed.
1263 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
1264 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1265
1266 // But then we should not report again..
1267 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1268
1269 // .. until another 24 hours has passed
1270 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
1271 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1272 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
1273 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1274 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1275
1276 // .. and another 24 hours
1277 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1278 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1279 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
1280 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1281 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1282
1283 // If the span between time of reporting and present time is
1284 // negative, we report. This is in order to reset the timestamp and
1285 // avoid an edge condition whereby a distant point in the future is
1286 // in the state variable resulting in us never ever reporting again.
1287 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
1288 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1289 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1290
1291 // In this case we should not update until the clock reads 71 + 24 = 95.
1292 // Check that.
1293 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
1294 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1295 fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
1296 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1297 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
David Zeuthen985b1122013-10-09 12:13:15 -07001298}
1299
David Zeuthen3c55abd2013-10-14 12:48:03 -07001300TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
David Zeuthen3c55abd2013-10-14 12:48:03 -07001301 FakeClock fake_clock;
1302 fake_clock.SetBootTime(Time::FromTimeT(42));
Gilad Arnold5bb4c902014-04-10 12:32:13 -07001303 fake_system_state_.set_clock(&fake_clock);
Alex Deymo906191f2015-10-12 12:22:44 -07001304 FakePrefs fake_prefs;
1305 fake_system_state_.set_prefs(&fake_prefs);
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001306 attempter_.Init();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001307
1308 Time boot_time;
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001309 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001310
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001311 attempter_.WriteUpdateCompletedMarker();
David Zeuthen3c55abd2013-10-14 12:48:03 -07001312
Sen Jiangaeeb2e02016-06-09 15:00:16 -07001313 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
David Zeuthen3c55abd2013-10-14 12:48:03 -07001314 EXPECT_EQ(boot_time.ToTimeT(), 42);
1315}
1316
David Pursell02c18642014-11-06 11:26:11 -08001317TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1318 fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
1319 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1320}
1321
1322TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1323 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001324 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
David Pursell02c18642014-11-06 11:26:11 -08001325 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1326}
1327
1328TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1329 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
Sen Jiange67bb5b2016-06-20 15:53:56 -07001330 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
David Pursell02c18642014-11-06 11:26:11 -08001331 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1332}
1333
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001334TEST_F(UpdateAttempterTest, CheckForUpdateInteractiveNotIdleFails) {
1335 // GIVEN an update is in progress.
1336 cfu_params_.status = UpdateStatus::CHECKING_FOR_UPDATE;
1337 // GIVEN a interactive update.
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001338
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001339 // THEN result should indicate failure.
1340 cfu_params_.expected_result = false;
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001341
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001342 TestCheckForUpdate();
Xiaochu Liu8ba486f2018-11-06 11:14:10 -08001343}
1344
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001345// TODO(b/137217982): Currently, since the logic is to flow through, the app
1346// version and omaha url are cleared.
1347TEST_F(UpdateAttempterTest,
1348 CheckForUpdateNonInteractiveNotIdleOfficialBuildSucceeds) {
1349 // GIVEN an update is in progress.
1350 cfu_params_.status = UpdateStatus::CHECKING_FOR_UPDATE;
1351 // GIVEN a non interactive update.
1352 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1353
1354 // THEN we except forced app version + forced omaha url to be cleared.
1355
1356 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001357}
1358
Jae Hoon Kim51ea9ae2019-07-03 16:56:30 -07001359// TODO(b/137217982): Currently, since the logic is to flow through, the app
1360// version and omaha url are set based on inputs.
1361TEST_F(UpdateAttempterTest,
1362 CheckForUpdateNonInteractiveNotIdleUnofficialBuildSucceeds) {
1363 // GIVEN an update is in progress.
1364 cfu_params_.status = UpdateStatus::CHECKING_FOR_UPDATE;
1365 // GIVEN a non interactive update.
1366 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1367 // GIVEN a non offical build with dev features enabled.
1368 cfu_params_.is_official_build = false;
1369 cfu_params_.are_dev_features_enabled = true;
1370
1371 // THEN the forced app version + forced omaha url changes based on input.
1372 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1373 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1374
1375 TestCheckForUpdate();
1376}
1377
1378TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1379 // GIVEN a official build.
1380
1381 // THEN we except forced app version + forced omaha url to be cleared.
1382
1383 TestCheckForUpdate();
1384}
1385
1386TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
1387 // GIVEN a non offical build with dev features enabled.
1388 cfu_params_.is_official_build = false;
1389 cfu_params_.are_dev_features_enabled = true;
1390
1391 // THEN the forced app version + forced omaha url changes based on input.
1392 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1393 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1394
1395 TestCheckForUpdate();
1396}
1397
1398TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1399 // GIVEN a scheduled autest omaha url.
1400 cfu_params_.omaha_url = "autest-scheduled";
1401
1402 // THEN forced app version is cleared.
1403 // THEN forced omaha url changes to default constant.
1404 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1405
1406 TestCheckForUpdate();
1407}
1408
1409TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1410 // GIVEN a scheduled autest omaha url.
1411 cfu_params_.omaha_url = "autest-scheduled";
1412 // GIVEN a non offical build with dev features enabled.
1413 cfu_params_.is_official_build = false;
1414 cfu_params_.are_dev_features_enabled = true;
1415
1416 // THEN forced app version changes based on input.
1417 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1418 // THEN forced omaha url changes to default constant.
1419 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1420
1421 TestCheckForUpdate();
1422}
1423
1424TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1425 // GIVEN a autest omaha url.
1426 cfu_params_.omaha_url = "autest";
1427
1428 // THEN forced app version is cleared.
1429 // THEN forced omaha url changes to default constant.
1430 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1431
1432 TestCheckForUpdate();
1433}
1434
1435TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1436 // GIVEN a autest omha url.
1437 cfu_params_.omaha_url = "autest";
1438 // GIVEN a non offical build with dev features enabled.
1439 cfu_params_.is_official_build = false;
1440 cfu_params_.are_dev_features_enabled = true;
1441
1442 // THEN forced app version changes based on input.
1443 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1444 // THEN forced omaha url changes to default constant.
1445 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1446
1447 TestCheckForUpdate();
1448}
1449
1450TEST_F(UpdateAttempterTest,
1451 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1452 // GIVEN a scheduled autest omaha url.
1453 cfu_params_.omaha_url = "autest-scheduled";
1454 // GIVEN a non interactive update.
1455 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1456
1457 // THEN forced app version is cleared.
1458 // THEN forced omaha url changes to default constant.
1459 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1460
1461 TestCheckForUpdate();
1462}
1463
1464TEST_F(UpdateAttempterTest,
1465 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1466 // GIVEN a scheduled autest omaha url.
1467 cfu_params_.omaha_url = "autest-scheduled";
1468 // GIVEN a non interactive update.
1469 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1470 // GIVEN a non offical build with dev features enabled.
1471 cfu_params_.is_official_build = false;
1472 cfu_params_.are_dev_features_enabled = true;
1473
1474 // THEN forced app version changes based on input.
1475 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1476 // THEN forced omaha url changes to default constant.
1477 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1478
1479 TestCheckForUpdate();
1480}
1481
1482TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1483 // GIVEN a autest omaha url.
1484 cfu_params_.omaha_url = "autest";
1485 // GIVEN a non interactive update.
1486 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
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, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1496 // GIVEN a autest omaha url.
1497 cfu_params_.omaha_url = "autest";
1498 // GIVEN a non interactive update.
1499 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1500 // GIVEN a non offical build with dev features enabled.
1501 cfu_params_.is_official_build = false;
1502 cfu_params_.are_dev_features_enabled = true;
1503
1504 // THEN forced app version changes based on input.
1505 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1506 // THEN forced omaha url changes to default constant.
1507 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1508
1509 TestCheckForUpdate();
David Pursell02c18642014-11-06 11:26:11 -08001510}
1511
Xiaochu Liu88d90382018-08-29 16:09:11 -07001512TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1513 fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
1514 fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
1515 attempter_.CheckForInstall({}, "autest");
1516 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1517
1518 attempter_.CheckForInstall({}, "autest-scheduled");
1519 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1520
1521 attempter_.CheckForInstall({}, "http://omaha.phishing");
1522 EXPECT_EQ("", attempter_.forced_omaha_url());
1523}
1524
Colin Howesac170d92018-11-20 16:29:28 -08001525TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1526 attempter_.CheckForInstall({}, "http://foo.bar");
1527 attempter_.status_ = UpdateStatus::DOWNLOADING;
1528 EXPECT_TRUE(attempter_.is_install_);
1529 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1530 UpdateEngineStatus status;
1531 attempter_.GetStatus(&status);
1532 // Should set status to idle after an install operation.
1533 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1534}
1535
Colin Howes978c1082018-12-03 11:46:12 -08001536TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1537 attempter_.is_install_ = true;
1538 attempter_.Rollback(false);
1539 EXPECT_FALSE(attempter_.is_install_);
1540}
1541
1542TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1543 attempter_.is_install_ = true;
1544 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1545 EXPECT_FALSE(attempter_.is_install_);
1546}
1547
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001548TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001549 attempter_.CalculateUpdateParams(
1550 "", "", "", "1234", false, false, 4, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001551 EXPECT_EQ("1234",
1552 fake_system_state_.request_params()->target_version_prefix());
1553
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001554 attempter_.CalculateUpdateParams(
1555 "", "", "", "", false, 4, false, false, false);
Xiyuan Xiac0e8f9a2017-02-22 13:19:35 -08001556 EXPECT_TRUE(
1557 fake_system_state_.request_params()->target_version_prefix().empty());
1558}
1559
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001560TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1561 attempter_.CalculateUpdateParams("",
1562 "",
1563 "",
1564 "1234",
1565 /*rollback_allowed=*/true,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001566 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001567 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001568 false,
1569 false);
1570 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001571 EXPECT_EQ(4,
1572 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001573
1574 attempter_.CalculateUpdateParams("",
1575 "",
1576 "",
1577 "1234",
1578 /*rollback_allowed=*/false,
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001579 /*rollback_data_save_requested=*/false,
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001580 /*rollback_allowed_milestones=*/4,
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001581 false,
1582 false);
1583 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
Zentaro Kavanagh0ef9a2f2018-07-02 12:05:07 -07001584 EXPECT_EQ(4,
1585 fake_system_state_.request_params()->rollback_allowed_milestones());
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001586}
1587
Aaron Wood23bd3392017-10-06 14:48:25 -07001588TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1589 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1590 // but the update is being deferred by the Policy.
Amin Hassani68512d42018-07-31 23:52:33 -07001591 OmahaResponseHandlerAction response_action(&fake_system_state_);
1592 response_action.install_plan_.version = "a.b.c.d";
1593 response_action.install_plan_.system_version = "b.c.d.e";
1594 response_action.install_plan_.payloads.push_back(
Aaron Wood23bd3392017-10-06 14:48:25 -07001595 {.size = 1234ULL, .type = InstallPayloadType::kFull});
Aaron Wood23bd3392017-10-06 14:48:25 -07001596 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1597 // completed, with the deferred-update error code.
1598 attempter_.ActionCompleted(
Amin Hassani68512d42018-07-31 23:52:33 -07001599 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
Aaron Wood23bd3392017-10-06 14:48:25 -07001600 {
1601 UpdateEngineStatus status;
1602 attempter_.GetStatus(&status);
1603 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001604 EXPECT_TRUE(attempter_.install_plan_);
1605 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001606 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001607 status.new_size_bytes);
1608 }
1609 // An "error" event should have been created to tell Omaha that the update is
1610 // being deferred.
1611 EXPECT_TRUE(nullptr != attempter_.error_event_);
1612 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1613 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1614 ErrorCode expected_code = static_cast<ErrorCode>(
1615 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1616 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1617 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1618 // End the processing
1619 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1620 // Validate the state of the attempter.
1621 {
1622 UpdateEngineStatus status;
1623 attempter_.GetStatus(&status);
1624 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
Amin Hassani68512d42018-07-31 23:52:33 -07001625 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
Amin Hassani68512d42018-07-31 23:52:33 -07001626 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
Aaron Wood23bd3392017-10-06 14:48:25 -07001627 status.new_size_bytes);
1628 }
1629}
1630
1631TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
1632 EXPECT_FALSE(attempter_.IsUpdateRunningOrScheduled());
1633 // Verify in-progress update with UPDATE_AVAILABLE is running
1634 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
1635 EXPECT_TRUE(attempter_.IsUpdateRunningOrScheduled());
1636}
1637
Aaron Woodbf5a2522017-10-04 10:58:36 -07001638TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1639 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1640
1641 UpdateCheckParams params = {.updates_enabled = true};
1642 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1643
1644 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1645 attempter_.GetCurrentUpdateAttemptFlags());
1646}
1647
Marton Hunyadyba51c3f2018-04-25 15:18:10 +02001648TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1649 UpdateCheckParams params = {.updates_enabled = true,
1650 .rollback_allowed = false};
1651 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1652 EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
1653}
1654
1655TEST_F(UpdateAttempterTest, RollbackAllowed) {
1656 UpdateCheckParams params = {.updates_enabled = true,
1657 .rollback_allowed = true};
1658 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1659 EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
1660}
1661
Aaron Wood081c0232017-10-19 17:14:58 -07001662TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1663 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1664
1665 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1666 EXPECT_EQ(UpdateAttemptFlags::kNone,
1667 attempter_.GetCurrentUpdateAttemptFlags());
1668}
1669
1670TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1671 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1672
1673 // This tests that when CheckForUpdate() is called with the non-interactive
1674 // flag set, that it doesn't change the current UpdateAttemptFlags.
1675 attempter_.CheckForUpdate("",
1676 "",
1677 UpdateAttemptFlags::kFlagNonInteractive |
1678 UpdateAttemptFlags::kFlagRestrictDownload);
1679 EXPECT_EQ(UpdateAttemptFlags::kNone,
1680 attempter_.GetCurrentUpdateAttemptFlags());
1681}
1682
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001683void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1684 bool is_policy_loaded,
1685 bool expected_reset) {
1686 EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
1687 .WillRepeatedly(Return(true));
1688 auto mock_policy_provider =
1689 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1690 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1691 .WillRepeatedly(Return(is_consumer));
1692 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1693 .WillRepeatedly(Return(is_policy_loaded));
1694 const policy::MockDevicePolicy device_policy;
1695 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1696 .WillRepeatedly(ReturnRef(device_policy));
1697 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1698 SetRollbackHappened(false))
1699 .Times(expected_reset ? 1 : 0);
1700 attempter_.policy_provider_ = std::move(mock_policy_provider);
Zentaro Kavanagh28def4f2019-01-15 17:15:01 -08001701 attempter_.Update("", "", "", "", false, false, 0, false, false);
Marton Hunyadye58bddb2018-04-10 20:27:26 +02001702 ScheduleQuitMainLoop();
1703}
1704
1705TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1706 loop_.PostTask(FROM_HERE,
1707 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1708 base::Unretained(this),
1709 /*is_consumer=*/false,
1710 /*is_policy_loaded=*/false,
1711 /*expected_reset=*/false));
1712 loop_.Run();
1713}
1714
1715TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1716 loop_.PostTask(FROM_HERE,
1717 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1718 base::Unretained(this),
1719 /*is_consumer=*/true,
1720 /*is_policy_loaded=*/false,
1721 /*expected_reset=*/true));
1722 loop_.Run();
1723}
1724
1725TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1726 loop_.PostTask(FROM_HERE,
1727 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1728 base::Unretained(this),
1729 /*is_consumer=*/false,
1730 /*is_policy_loaded=*/true,
1731 /*expected_reset=*/true));
1732 loop_.Run();
1733}
1734
Marton Hunyady199152d2018-05-07 19:08:48 +02001735TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001736 attempter_.install_plan_.reset(new InstallPlan);
1737 attempter_.install_plan_->is_rollback = true;
Marton Hunyady199152d2018-05-07 19:08:48 +02001738
1739 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1740 SetRollbackHappened(true))
1741 .Times(1);
1742 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1743}
1744
1745TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001746 attempter_.install_plan_.reset(new InstallPlan);
1747 attempter_.install_plan_->is_rollback = false;
Marton Hunyady199152d2018-05-07 19:08:48 +02001748
1749 EXPECT_CALL(*fake_system_state_.mock_payload_state(),
1750 SetRollbackHappened(true))
1751 .Times(0);
1752 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1753}
1754
Marton Hunyadya0302682018-05-16 18:52:13 +02001755TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001756 attempter_.install_plan_.reset(new InstallPlan);
1757 attempter_.install_plan_->is_rollback = true;
1758 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001759
1760 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1761 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1762 .Times(1);
1763 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1764}
1765
1766TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001767 attempter_.install_plan_.reset(new InstallPlan);
1768 attempter_.install_plan_->is_rollback = false;
1769 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001770
1771 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1772 ReportEnterpriseRollbackMetrics(_, _))
1773 .Times(0);
1774 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1775}
1776
1777TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001778 attempter_.install_plan_.reset(new InstallPlan);
1779 attempter_.install_plan_->is_rollback = true;
1780 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001781
1782 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1783 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1784 .Times(1);
1785 MockAction action;
1786 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1787 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1788}
1789
1790TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
Amin Hassanid3f4bea2018-04-30 14:52:40 -07001791 attempter_.install_plan_.reset(new InstallPlan);
1792 attempter_.install_plan_->is_rollback = false;
1793 attempter_.install_plan_->version = kRollbackVersion;
Marton Hunyadya0302682018-05-16 18:52:13 +02001794
1795 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1796 ReportEnterpriseRollbackMetrics(_, _))
1797 .Times(0);
1798 MockAction action;
1799 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1800 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1801}
1802
May Lippert60aa3ca2018-08-15 16:55:29 -07001803TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1804 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1805 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1806 .Times(0);
1807 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1808}
1809
1810TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1811 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1812 fake_system_state_.set_device_policy(device_policy.get());
1813 // Make device policy return that this is not enterprise enrolled
1814 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1815
1816 // Ensure that the metric is not recorded.
1817 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1818 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1819 .Times(0);
1820 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1821}
1822
1823TEST_F(UpdateAttempterTest,
1824 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1825 constexpr int kDaysToUpdate = 15;
1826 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1827 fake_system_state_.set_device_policy(device_policy.get());
1828 // Make device policy return that this is enterprise enrolled
1829 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1830 // Pretend that there's a time restriction policy in place
1831 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1832 .WillOnce(Return(true));
1833
1834 FakePrefs fake_prefs;
1835 Time update_first_seen_at = Time::Now();
1836 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1837 update_first_seen_at.ToInternalValue());
1838
1839 FakeClock fake_clock;
1840 Time update_finished_at =
1841 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1842 fake_clock.SetWallclockTime(update_finished_at);
1843
1844 fake_system_state_.set_clock(&fake_clock);
1845 fake_system_state_.set_prefs(&fake_prefs);
1846
1847 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1848 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1849 .Times(1);
1850 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1851}
1852
1853TEST_F(UpdateAttempterTest,
1854 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1855 constexpr int kDaysToUpdate = 15;
1856 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1857 fake_system_state_.set_device_policy(device_policy.get());
1858 // Make device policy return that this is enterprise enrolled
1859 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1860 // Pretend that there's no time restriction policy in place
1861 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1862 .WillOnce(Return(false));
1863
1864 FakePrefs fake_prefs;
1865 Time update_first_seen_at = Time::Now();
1866 fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
1867 update_first_seen_at.ToInternalValue());
1868
1869 FakeClock fake_clock;
1870 Time update_finished_at =
1871 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1872 fake_clock.SetWallclockTime(update_finished_at);
1873
1874 fake_system_state_.set_clock(&fake_clock);
1875 fake_system_state_.set_prefs(&fake_prefs);
1876
1877 EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
1878 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1879 .Times(1);
1880 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1881}
1882
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001883void UpdateAttempterTest::UpdateToQuickFixBuildStart(bool set_token) {
1884 // Tests that checks if |device_quick_fix_build_token| arrives when
1885 // policy is set and the device is enterprise enrolled based on |set_token|.
1886 string token = set_token ? "some_token" : "";
Askar Aitzhan570ca872019-04-24 11:16:12 +02001887 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1888 fake_system_state_.set_device_policy(device_policy.get());
Askar Aitzhan570ca872019-04-24 11:16:12 +02001889 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001890
1891 if (set_token)
1892 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
1893 .WillOnce(DoAll(SetArgPointee<0>(token), Return(true)));
1894 else
1895 EXPECT_CALL(*device_policy, GetDeviceQuickFixBuildToken(_))
1896 .WillOnce(Return(false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02001897 attempter_.policy_provider_.reset(
1898 new policy::PolicyProvider(std::move(device_policy)));
1899 attempter_.Update("", "", "", "", false, false, 0, false, false);
1900
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001901 EXPECT_EQ(token, attempter_.omaha_request_params_->autoupdate_token());
Askar Aitzhan570ca872019-04-24 11:16:12 +02001902 ScheduleQuitMainLoop();
1903}
1904
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001905TEST_F(UpdateAttempterTest,
1906 QuickFixTokenWhenDeviceIsEnterpriseEnrolledAndPolicyIsSet) {
Askar Aitzhan570ca872019-04-24 11:16:12 +02001907 loop_.PostTask(FROM_HERE,
1908 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
Amr Aboelkher21ac9962019-05-15 14:50:05 +02001909 base::Unretained(this),
1910 /*set_token=*/true));
1911 loop_.Run();
1912}
1913
1914TEST_F(UpdateAttempterTest, EmptyQuickFixToken) {
1915 loop_.PostTask(FROM_HERE,
1916 base::Bind(&UpdateAttempterTest::UpdateToQuickFixBuildStart,
1917 base::Unretained(this),
1918 /*set_token=*/false));
Askar Aitzhan570ca872019-04-24 11:16:12 +02001919 loop_.Run();
1920}
1921
Darin Petkovf42cc1c2010-09-01 09:03:02 -07001922} // namespace chromeos_update_engine