1 //
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 //
16
17 #include "update_engine/cros/update_attempter.h"
18
19 #include <stdint.h>
20
21 #include <limits>
22 #include <map>
23 #include <memory>
24 #include <string>
25 #include <unordered_set>
26
27 #include <base/files/file_util.h>
28 #include <base/files/scoped_temp_dir.h>
29 #include <base/task/single_thread_task_executor.h>
30 #include <brillo/message_loops/base_message_loop.h>
31 #include <brillo/message_loops/message_loop.h>
32 #include <brillo/message_loops/message_loop_utils.h>
33 #include <gtest/gtest.h>
34 #include <policy/libpolicy.h>
35 #include <policy/mock_device_policy.h>
36 #include <policy/mock_libpolicy.h>
37
38 #include "update_engine/common/constants.h"
39 #include "update_engine/common/dlcservice_interface.h"
40 #include "update_engine/common/mock_action.h"
41 #include "update_engine/common/mock_action_processor.h"
42 #include "update_engine/common/mock_http_fetcher.h"
43 #include "update_engine/common/mock_service_observer.h"
44 #include "update_engine/common/platform_constants.h"
45 #include "update_engine/common/prefs.h"
46 #include "update_engine/common/test_utils.h"
47 #include "update_engine/common/utils.h"
48 #include "update_engine/cros/download_action_chromeos.h"
49 #include "update_engine/cros/fake_system_state.h"
50 #include "update_engine/cros/mock_p2p_manager.h"
51 #include "update_engine/cros/mock_payload_state.h"
52 #include "update_engine/cros/omaha_utils.h"
53 #include "update_engine/libcurl_http_fetcher.h"
54 #include "update_engine/payload_consumer/filesystem_verifier_action.h"
55 #include "update_engine/payload_consumer/install_plan.h"
56 #include "update_engine/payload_consumer/payload_constants.h"
57 #include "update_engine/payload_consumer/postinstall_runner_action.h"
58 #include "update_engine/update_boot_flags_action.h"
59 #include "update_engine/update_manager/mock_update_manager.h"
60
61 using base::Time;
62 using base::TimeDelta;
63 using chromeos_update_manager::EvalStatus;
64 using chromeos_update_manager::MockUpdateManager;
65 using chromeos_update_manager::StagingSchedule;
66 using chromeos_update_manager::UpdateCheckParams;
67 using policy::DevicePolicy;
68 using std::map;
69 using std::string;
70 using std::unique_ptr;
71 using std::unordered_set;
72 using std::vector;
73 using testing::_;
74 using testing::Contains;
75 using testing::DoAll;
76 using testing::ElementsAre;
77 using testing::Field;
78 using testing::InSequence;
79 using testing::Invoke;
80 using testing::Ne;
81 using testing::NiceMock;
82 using testing::Pointee;
83 using testing::Property;
84 using testing::Return;
85 using testing::ReturnPointee;
86 using testing::ReturnRef;
87 using testing::SaveArg;
88 using testing::SetArgPointee;
89 using update_engine::UpdateAttemptFlags;
90 using update_engine::UpdateEngineStatus;
91 using update_engine::UpdateStatus;
92
93 namespace chromeos_update_engine {
94
95 namespace {
96
97 const UpdateStatus kNonIdleUpdateStatuses[] = {
98 UpdateStatus::CHECKING_FOR_UPDATE,
99 UpdateStatus::UPDATE_AVAILABLE,
100 UpdateStatus::DOWNLOADING,
101 UpdateStatus::VERIFYING,
102 UpdateStatus::FINALIZING,
103 UpdateStatus::UPDATED_NEED_REBOOT,
104 UpdateStatus::REPORTING_ERROR_EVENT,
105 UpdateStatus::ATTEMPTING_ROLLBACK,
106 UpdateStatus::DISABLED,
107 UpdateStatus::NEED_PERMISSION_TO_UPDATE,
108 };
109
110 struct CheckForUpdateTestParams {
111 // Setups + Inputs:
112 UpdateStatus status = UpdateStatus::IDLE;
113 string app_version = "fake_app_version";
114 string omaha_url = "fake_omaha_url";
115 UpdateAttemptFlags flags = UpdateAttemptFlags::kNone;
116 bool is_official_build = true;
117 bool are_dev_features_enabled = false;
118
119 // Expects:
120 string expected_forced_app_version = "";
121 string expected_forced_omaha_url = "";
122 bool should_schedule_updates_be_called = true;
123 bool expected_result = true;
124 };
125
126 struct OnUpdateScheduledTestParams {
127 // Setups + Inputs:
128 UpdateCheckParams params = {};
129 EvalStatus status = EvalStatus::kFailed;
130 // Expects:
131 UpdateStatus exit_status = UpdateStatus::IDLE;
132 bool should_schedule_updates_be_called = false;
133 bool should_update_be_called = false;
134 };
135
136 struct ProcessingDoneTestParams {
137 // Setups + Inputs:
138 bool is_install = false;
139 UpdateStatus status = UpdateStatus::CHECKING_FOR_UPDATE;
140 ActionProcessor* processor = nullptr;
141 ErrorCode code = ErrorCode::kSuccess;
142 map<string, OmahaRequestParams::AppParams> dlc_apps_params;
143
144 // Expects:
145 const bool kExpectedIsInstall = false;
146 bool should_schedule_updates_be_called = true;
147 UpdateStatus expected_exit_status = UpdateStatus::IDLE;
148 bool should_install_completed_be_called = false;
149 bool should_update_completed_be_called = false;
150 vector<string> args_to_install_completed;
151 vector<string> args_to_update_completed;
152 };
153
154 class MockDlcService : public DlcServiceInterface {
155 public:
156 MOCK_METHOD1(GetDlcsToUpdate, bool(vector<string>*));
157 MOCK_METHOD1(InstallCompleted, bool(const vector<string>&));
158 MOCK_METHOD1(UpdateCompleted, bool(const vector<string>&));
159 };
160
161 } // namespace
162
163 const char kRollbackVersion[] = "10575.39.2";
164
165 // Test a subclass rather than the main class directly so that we can mock out
166 // methods within the class. There're explicit unit tests for the mocked out
167 // methods.
168 class UpdateAttempterUnderTest : public UpdateAttempter {
169 public:
UpdateAttempterUnderTest()170 UpdateAttempterUnderTest() : UpdateAttempter(nullptr) {}
171
Update(const UpdateCheckParams & params)172 void Update(const UpdateCheckParams& params) override {
173 update_called_ = true;
174 if (do_update_) {
175 UpdateAttempter::Update(params);
176 return;
177 }
178 LOG(INFO) << "[TEST] Update() disabled.";
179 status_ = UpdateStatus::CHECKING_FOR_UPDATE;
180 }
181
DisableUpdate()182 void DisableUpdate() { do_update_ = false; }
183
WasUpdateCalled() const184 bool WasUpdateCalled() const { return update_called_; }
185
186 // Wrap the update scheduling method, allowing us to opt out of scheduled
187 // updates for testing purposes.
ScheduleUpdates()188 bool ScheduleUpdates() override {
189 schedule_updates_called_ = true;
190 if (do_schedule_updates_)
191 return UpdateAttempter::ScheduleUpdates();
192 LOG(INFO) << "[TEST] Update scheduling disabled.";
193 waiting_for_scheduled_check_ = true;
194 return true;
195 }
196
DisableScheduleUpdates()197 void DisableScheduleUpdates() { do_schedule_updates_ = false; }
198
199 // Indicates whether |ScheduleUpdates()| was called.
WasScheduleUpdatesCalled() const200 bool WasScheduleUpdatesCalled() const { return schedule_updates_called_; }
201
202 // Need to expose following private members of |UpdateAttempter| for tests.
forced_app_version() const203 const string& forced_app_version() const { return forced_app_version_; }
forced_omaha_url() const204 const string& forced_omaha_url() const { return forced_omaha_url_; }
205
206 // Need to expose |waiting_for_scheduled_check_| for testing.
SetWaitingForScheduledCheck(bool waiting)207 void SetWaitingForScheduledCheck(bool waiting) {
208 waiting_for_scheduled_check_ = waiting;
209 }
210
211 private:
212 // Used for overrides of |Update()|.
213 bool update_called_ = false;
214 bool do_update_ = true;
215
216 // Used for overrides of |ScheduleUpdates()|.
217 bool schedule_updates_called_ = false;
218 bool do_schedule_updates_ = true;
219 };
220
221 class UpdateAttempterTest : public ::testing::Test {
222 protected:
SetUp()223 void SetUp() override {
224 // Override system state members.
225 FakeSystemState::CreateInstance();
226 FakeSystemState::Get()->set_connection_manager(&mock_connection_manager);
227 FakeSystemState::Get()->set_update_attempter(&attempter_);
228 FakeSystemState::Get()->set_dlcservice(&mock_dlcservice_);
229 FakeSystemState::Get()->set_update_manager(&mock_update_manager_);
230 loop_.SetAsCurrent();
231
232 prefs_ = FakeSystemState::Get()->fake_prefs();
233 certificate_checker_.reset(
234 new CertificateChecker(prefs_, &openssl_wrapper_));
235 certificate_checker_->Init();
236
237 attempter_.set_forced_update_pending_callback(
238 new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
239 // Finish initializing the attempter.
240 attempter_.Init();
241
242 EXPECT_EQ(0, attempter_.http_response_code_);
243 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
244 EXPECT_EQ(0.0, attempter_.download_progress_);
245 EXPECT_EQ(0, attempter_.last_checked_time_);
246 EXPECT_EQ("0.0.0.0", attempter_.new_version_);
247 EXPECT_EQ(0ULL, attempter_.new_payload_size_);
248 processor_ = new NiceMock<MockActionProcessor>();
249 attempter_.processor_.reset(processor_); // Transfers ownership.
250
251 // Setup store/load semantics of P2P properties via the mock |PayloadState|.
252 actual_using_p2p_for_downloading_ = false;
253 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
254 SetUsingP2PForDownloading(_))
255 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
256 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
257 GetUsingP2PForDownloading())
258 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
259 actual_using_p2p_for_sharing_ = false;
260 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
261 SetUsingP2PForSharing(_))
262 .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
263 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
264 GetUsingP2PForDownloading())
265 .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
266 }
267
268 public:
269 void ScheduleQuitMainLoop();
270
271 // Callbacks to run the different tests from the main loop.
272 void UpdateTestStart();
273 void UpdateTestVerify();
274 void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
275 void RollbackTestVerify();
276 void PingOmahaTestStart();
277 void ReadScatterFactorFromPolicyTestStart();
278 void DecrementUpdateCheckCountTestStart();
279 void NoScatteringDoneDuringManualUpdateTestStart();
280 void P2PNotEnabledStart();
281 void P2PEnabledStart();
282 void P2PEnabledInteractiveStart();
283 void P2PEnabledStartingFailsStart();
284 void P2PEnabledHousekeepingFailsStart();
285 void SessionIdTestChange();
286 void SessionIdTestEnforceEmptyStrPingOmaha();
287 void SessionIdTestConsistencyInUpdateFlow();
288 void SessionIdTestInDownloadAction();
289 void ResetRollbackHappenedStart(bool is_consumer,
290 bool is_policy_available,
291 bool expected_reset);
292 // Staging related callbacks.
293 void SetUpStagingTest(const StagingSchedule& schedule);
294 void CheckStagingOff();
295 void StagingSetsPrefsAndTurnsOffScatteringStart();
296 void StagingOffIfInteractiveStart();
297 void StagingOffIfOobeStart();
298
actual_using_p2p_for_downloading()299 bool actual_using_p2p_for_downloading() {
300 return actual_using_p2p_for_downloading_;
301 }
actual_using_p2p_for_sharing()302 bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
303
304 // |CheckForUpdate()| related member functions.
305 void TestCheckForUpdate();
306
307 // |OnUpdateScheduled()| related member functions.
308 void TestOnUpdateScheduled();
309
310 // |ProcessingDone()| related member functions.
311 void TestProcessingDone();
312
313 base::SingleThreadTaskExecutor base_loop_{base::MessagePumpType::IO};
314 brillo::BaseMessageLoop loop_{base_loop_.task_runner()};
315
316 UpdateAttempterUnderTest attempter_;
317 OpenSSLWrapper openssl_wrapper_;
318 std::unique_ptr<CertificateChecker> certificate_checker_;
319 MockDlcService mock_dlcservice_;
320 MockUpdateManager mock_update_manager_;
321
322 NiceMock<MockActionProcessor>* processor_;
323 NiceMock<MockConnectionManager> mock_connection_manager;
324
325 FakePrefs* prefs_;
326
327 // |CheckForUpdate()| test params.
328 CheckForUpdateTestParams cfu_params_;
329
330 // |OnUpdateScheduled()| test params.
331 OnUpdateScheduledTestParams ous_params_;
332
333 // |ProcessingDone()| test params.
334 ProcessingDoneTestParams pd_params_;
335
336 bool actual_using_p2p_for_downloading_;
337 bool actual_using_p2p_for_sharing_;
338 };
339
TestCheckForUpdate()340 void UpdateAttempterTest::TestCheckForUpdate() {
341 // Setup
342 attempter_.status_ = cfu_params_.status;
343 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(
344 cfu_params_.is_official_build);
345 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(
346 cfu_params_.are_dev_features_enabled);
347
348 // Invocation
349 EXPECT_EQ(
350 cfu_params_.expected_result,
351 attempter_.CheckForUpdate(
352 cfu_params_.app_version, cfu_params_.omaha_url, cfu_params_.flags));
353
354 // Verify
355 EXPECT_EQ(cfu_params_.expected_forced_app_version,
356 attempter_.forced_app_version());
357 EXPECT_EQ(cfu_params_.expected_forced_omaha_url,
358 attempter_.forced_omaha_url());
359 EXPECT_EQ(cfu_params_.should_schedule_updates_be_called,
360 attempter_.WasScheduleUpdatesCalled());
361 }
362
TestProcessingDone()363 void UpdateAttempterTest::TestProcessingDone() {
364 // Setup
365 attempter_.DisableScheduleUpdates();
366 attempter_.is_install_ = pd_params_.is_install;
367 attempter_.status_ = pd_params_.status;
368 attempter_.omaha_request_params_->set_dlc_apps_params(
369 pd_params_.dlc_apps_params);
370
371 // Expects
372 if (pd_params_.should_install_completed_be_called)
373 EXPECT_CALL(mock_dlcservice_,
374 InstallCompleted(pd_params_.args_to_install_completed))
375 .WillOnce(Return(true));
376 else
377 EXPECT_CALL(mock_dlcservice_, InstallCompleted(_)).Times(0);
378 if (pd_params_.should_update_completed_be_called)
379 EXPECT_CALL(mock_dlcservice_,
380 UpdateCompleted(pd_params_.args_to_update_completed))
381 .WillOnce(Return(true));
382 else
383 EXPECT_CALL(mock_dlcservice_, UpdateCompleted(_)).Times(0);
384
385 // Invocation
386 attempter_.ProcessingDone(pd_params_.processor, pd_params_.code);
387
388 // Verify
389 EXPECT_EQ(pd_params_.kExpectedIsInstall, attempter_.is_install_);
390 EXPECT_EQ(pd_params_.should_schedule_updates_be_called,
391 attempter_.WasScheduleUpdatesCalled());
392 EXPECT_EQ(pd_params_.expected_exit_status, attempter_.status_);
393 }
394
ScheduleQuitMainLoop()395 void UpdateAttempterTest::ScheduleQuitMainLoop() {
396 loop_.PostTask(
397 FROM_HERE,
398 base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
399 base::Unretained(&loop_)));
400 }
401
SessionIdTestChange()402 void UpdateAttempterTest::SessionIdTestChange() {
403 EXPECT_NE(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
404 const auto old_session_id = attempter_.session_id_;
405 attempter_.Update({});
406 EXPECT_NE(old_session_id, attempter_.session_id_);
407 ScheduleQuitMainLoop();
408 }
409
TEST_F(UpdateAttempterTest,SessionIdTestChange)410 TEST_F(UpdateAttempterTest, SessionIdTestChange) {
411 loop_.PostTask(FROM_HERE,
412 base::Bind(&UpdateAttempterTest::SessionIdTestChange,
413 base::Unretained(this)));
414 loop_.Run();
415 }
416
SessionIdTestEnforceEmptyStrPingOmaha()417 void UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha() {
418 // The |session_id_| should not be changed and should remain as an empty
419 // string when |status_| is |UPDATED_NEED_REBOOT| (only for consistency)
420 // and |PingOmaha()| is called.
421 attempter_.DisableScheduleUpdates();
422 attempter_.status_ = UpdateStatus::UPDATED_NEED_REBOOT;
423 const auto old_session_id = attempter_.session_id_;
424 auto CheckIfEmptySessionId = [](AbstractAction* aa) {
425 if (aa->Type() == OmahaRequestAction::StaticType()) {
426 EXPECT_TRUE(static_cast<OmahaRequestAction*>(aa)->session_id_.empty());
427 }
428 };
429 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
430 .WillRepeatedly(Invoke(CheckIfEmptySessionId));
431 EXPECT_CALL(*processor_, StartProcessing());
432 attempter_.PingOmaha();
433 EXPECT_EQ(old_session_id, attempter_.session_id_);
434 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status_);
435 ScheduleQuitMainLoop();
436 }
437
TEST_F(UpdateAttempterTest,SessionIdTestEnforceEmptyStrPingOmaha)438 TEST_F(UpdateAttempterTest, SessionIdTestEnforceEmptyStrPingOmaha) {
439 loop_.PostTask(
440 FROM_HERE,
441 base::Bind(&UpdateAttempterTest::SessionIdTestEnforceEmptyStrPingOmaha,
442 base::Unretained(this)));
443 loop_.Run();
444 }
445
SessionIdTestConsistencyInUpdateFlow()446 void UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow() {
447 // All session IDs passed into |OmahaRequestActions| should be enforced to
448 // have the same value in |BuildUpdateActions()|.
449 unordered_set<string> session_ids;
450 // Gather all the session IDs being passed to |OmahaRequestActions|.
451 auto CheckSessionId = [&session_ids](AbstractAction* aa) {
452 if (aa->Type() == OmahaRequestAction::StaticType())
453 session_ids.insert(static_cast<OmahaRequestAction*>(aa)->session_id_);
454 };
455 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
456 .WillRepeatedly(Invoke(CheckSessionId));
457 attempter_.BuildUpdateActions(false);
458 // Validate that all the session IDs are the same.
459 EXPECT_EQ(1, session_ids.size());
460 ScheduleQuitMainLoop();
461 }
462
TEST_F(UpdateAttempterTest,SessionIdTestConsistencyInUpdateFlow)463 TEST_F(UpdateAttempterTest, SessionIdTestConsistencyInUpdateFlow) {
464 loop_.PostTask(
465 FROM_HERE,
466 base::Bind(&UpdateAttempterTest::SessionIdTestConsistencyInUpdateFlow,
467 base::Unretained(this)));
468 loop_.Run();
469 }
470
SessionIdTestInDownloadAction()471 void UpdateAttempterTest::SessionIdTestInDownloadAction() {
472 // The session ID passed into |DownloadAction|'s |LibcurlHttpFetcher| should
473 // be enforced to be included in the HTTP header as X-Goog-Update-SessionId.
474 string header_value;
475 auto CheckSessionIdInDownloadAction = [&header_value](AbstractAction* aa) {
476 if (aa->Type() == DownloadActionChromeos::StaticType()) {
477 DownloadActionChromeos* da = static_cast<DownloadActionChromeos*>(aa);
478 EXPECT_TRUE(da->http_fetcher()->GetHeader(kXGoogleUpdateSessionId,
479 &header_value));
480 }
481 };
482 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_)))
483 .WillRepeatedly(Invoke(CheckSessionIdInDownloadAction));
484 attempter_.BuildUpdateActions(false);
485 // Validate that X-Goog-Update_SessionId is set correctly in HTTP Header.
486 EXPECT_EQ(attempter_.session_id_, header_value);
487 ScheduleQuitMainLoop();
488 }
489
TEST_F(UpdateAttempterTest,SessionIdTestInDownloadAction)490 TEST_F(UpdateAttempterTest, SessionIdTestInDownloadAction) {
491 loop_.PostTask(FROM_HERE,
492 base::Bind(&UpdateAttempterTest::SessionIdTestInDownloadAction,
493 base::Unretained(this)));
494 loop_.Run();
495 }
496
TEST_F(UpdateAttempterTest,ActionCompletedDownloadTest)497 TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
498 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
499 fetcher->FailTransfer(503); // Sets the HTTP response code.
500 DownloadActionChromeos action(
501 prefs_, nullptr, nullptr, fetcher.release(), false /* interactive */);
502 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
503 EXPECT_FALSE(prefs_->Exists(kPrefsDeltaUpdateFailures));
504 EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
505 EXPECT_EQ(0.0, attempter_.download_progress_);
506 ASSERT_EQ(nullptr, attempter_.error_event_.get());
507 }
508
TEST_F(UpdateAttempterTest,ActionCompletedErrorTest)509 TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
510 MockAction action;
511 EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
512 attempter_.status_ = UpdateStatus::DOWNLOADING;
513 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
514 ASSERT_NE(nullptr, attempter_.error_event_.get());
515 }
516
TEST_F(UpdateAttempterTest,DownloadProgressAccumulationTest)517 TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
518 // Simple test case, where all the values match (nothing was skipped)
519 uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
520 uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
521 uint64_t bytes_received_1 = bytes_progressed_1;
522 uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
523 uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
524
525 double progress_1 =
526 static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
527 double progress_2 =
528 static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
529
530 EXPECT_EQ(0.0, attempter_.download_progress_);
531 // This is set via inspecting the InstallPlan payloads when the
532 // |OmahaResponseAction| is completed.
533 attempter_.new_payload_size_ = bytes_total;
534 NiceMock<MockServiceObserver> observer;
535 EXPECT_CALL(observer,
536 SendStatusUpdate(AllOf(
537 Field(&UpdateEngineStatus::progress, progress_1),
538 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
539 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
540 EXPECT_CALL(observer,
541 SendStatusUpdate(AllOf(
542 Field(&UpdateEngineStatus::progress, progress_2),
543 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
544 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
545 attempter_.AddObserver(&observer);
546 attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
547 EXPECT_EQ(progress_1, attempter_.download_progress_);
548 // This iteration validates that a later set of updates to the variables are
549 // properly handled (so that |getStatus()| will return the same progress info
550 // as the callback is receiving.
551 attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
552 EXPECT_EQ(progress_2, attempter_.download_progress_);
553 }
554
TEST_F(UpdateAttempterTest,ChangeToDownloadingOnReceivedBytesTest)555 TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
556 // The transition into |UpdateStatus::DOWNLOADING| happens when the
557 // first bytes are received.
558 uint64_t bytes_progressed = 1024 * 1024; // 1MB
559 uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
560 uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
561 attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
562 // This is set via inspecting the InstallPlan payloads when the
563 // |OmahaResponseAction| is completed.
564 attempter_.new_payload_size_ = bytes_total;
565 EXPECT_EQ(0.0, attempter_.download_progress_);
566 NiceMock<MockServiceObserver> observer;
567 EXPECT_CALL(observer,
568 SendStatusUpdate(AllOf(
569 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
570 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
571 attempter_.AddObserver(&observer);
572 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
573 EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
574 }
575
TEST_F(UpdateAttempterTest,BroadcastCompleteDownloadTest)576 TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
577 // There is a special case to ensure that at 100% downloaded,
578 // |download_progress_| is updated and broadcastest.
579 uint64_t bytes_progressed = 0; // ignored
580 uint64_t bytes_received = 5 * 1024 * 1024; // ignored
581 uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
582 attempter_.status_ = UpdateStatus::DOWNLOADING;
583 attempter_.new_payload_size_ = bytes_total;
584 EXPECT_EQ(0.0, attempter_.download_progress_);
585 NiceMock<MockServiceObserver> observer;
586 EXPECT_CALL(observer,
587 SendStatusUpdate(AllOf(
588 Field(&UpdateEngineStatus::progress, 1.0),
589 Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
590 Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
591 attempter_.AddObserver(&observer);
592 attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
593 EXPECT_EQ(1.0, attempter_.download_progress_);
594 }
595
TEST_F(UpdateAttempterTest,ActionCompletedOmahaRequestTest)596 TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
597 unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
598 fetcher->FailTransfer(500); // Sets the HTTP response code.
599 OmahaRequestAction action(nullptr, std::move(fetcher), false, "");
600 ObjectCollectorAction<OmahaResponse> collector_action;
601 BondActions(&action, &collector_action);
602 OmahaResponse response;
603 response.poll_interval = 234;
604 action.SetOutputObject(response);
605 attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
606 EXPECT_FALSE(prefs_->Exists(kPrefsDeltaUpdateFailures));
607 EXPECT_EQ(500, attempter_.http_response_code());
608 EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
609 EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
610 ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
611 }
612
TEST_F(UpdateAttempterTest,ConstructWithUpdatedMarkerTest)613 TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
614 string boot_id;
615 EXPECT_TRUE(utils::GetBootId(&boot_id));
616 FakeSystemState::Get()->fake_prefs()->SetString(kPrefsUpdateCompletedOnBootId,
617 boot_id);
618 attempter_.Init();
619 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
620 }
621
TEST_F(UpdateAttempterTest,GetErrorCodeForActionTest)622 TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
623 EXPECT_EQ(ErrorCode::kSuccess,
624 GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
625
626 OmahaRequestAction omaha_request_action(nullptr, nullptr, false, "");
627 EXPECT_EQ(ErrorCode::kOmahaRequestError,
628 GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
629 OmahaResponseHandlerAction omaha_response_handler_action;
630 EXPECT_EQ(
631 ErrorCode::kOmahaResponseHandlerError,
632 GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
633 DynamicPartitionControlStub dynamic_control_stub;
634 FilesystemVerifierAction filesystem_verifier_action(&dynamic_control_stub);
635 EXPECT_EQ(
636 ErrorCode::kFilesystemVerifierError,
637 GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
638 PostinstallRunnerAction postinstall_runner_action(
639 FakeSystemState::Get()->fake_boot_control(),
640 FakeSystemState::Get()->fake_hardware());
641 EXPECT_EQ(
642 ErrorCode::kPostinstallRunnerError,
643 GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
644 MockAction action_mock;
645 EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
646 EXPECT_EQ(ErrorCode::kError,
647 GetErrorCodeForAction(&action_mock, ErrorCode::kError));
648 }
649
TEST_F(UpdateAttempterTest,DisableDeltaUpdateIfNeededTest)650 TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
651 attempter_.omaha_request_params_->set_delta_okay(true);
652 attempter_.DisableDeltaUpdateIfNeeded();
653 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
654 prefs_->SetInt64(kPrefsDeltaUpdateFailures,
655 UpdateAttempter::kMaxDeltaUpdateFailures - 1);
656 attempter_.DisableDeltaUpdateIfNeeded();
657 EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
658 prefs_->SetInt64(kPrefsDeltaUpdateFailures,
659 UpdateAttempter::kMaxDeltaUpdateFailures);
660 attempter_.DisableDeltaUpdateIfNeeded();
661 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
662 attempter_.DisableDeltaUpdateIfNeeded();
663 EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
664 }
665
TEST_F(UpdateAttempterTest,MarkDeltaUpdateFailureTest)666 TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
667 attempter_.MarkDeltaUpdateFailure();
668
669 EXPECT_TRUE(prefs_->SetInt64(kPrefsDeltaUpdateFailures, -1));
670 attempter_.MarkDeltaUpdateFailure();
671 int64_t value = 0;
672 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
673 EXPECT_EQ(value, 1);
674
675 attempter_.MarkDeltaUpdateFailure();
676 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
677 EXPECT_EQ(value, 2);
678
679 EXPECT_TRUE(prefs_->SetInt64(kPrefsDeltaUpdateFailures,
680 UpdateAttempter::kMaxDeltaUpdateFailures));
681 attempter_.MarkDeltaUpdateFailure();
682 EXPECT_TRUE(prefs_->GetInt64(kPrefsDeltaUpdateFailures, &value));
683 EXPECT_EQ(value, UpdateAttempter::kMaxDeltaUpdateFailures + 1);
684 }
685
TEST_F(UpdateAttempterTest,ScheduleErrorEventActionNoEventTest)686 TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
687 EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
688 EXPECT_CALL(*processor_, StartProcessing()).Times(0);
689 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(_))
690 .Times(0);
691 OmahaResponse response;
692 string url1 = "http://url1";
693 response.packages.push_back({.payload_urls = {url1, "https://url"}});
694 EXPECT_CALL(*(FakeSystemState::Get()->mock_payload_state()), GetCurrentUrl())
695 .WillRepeatedly(Return(url1));
696 FakeSystemState::Get()->mock_payload_state()->SetResponse(response);
697 attempter_.ScheduleErrorEventAction();
698 EXPECT_EQ(url1,
699 FakeSystemState::Get()->mock_payload_state()->GetCurrentUrl());
700 }
701
TEST_F(UpdateAttempterTest,ScheduleErrorEventActionTest)702 TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
703 EXPECT_CALL(*processor_,
704 EnqueueAction(Pointee(Property(
705 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
706 EXPECT_CALL(*processor_, StartProcessing());
707 ErrorCode err = ErrorCode::kError;
708 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(), UpdateFailed(err));
709 attempter_.error_event_.reset(new OmahaEvent(
710 OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
711 attempter_.ScheduleErrorEventAction();
712 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
713 }
714
715 namespace {
716 // Actions that will be built as part of an update check.
GetUpdateActionTypes()717 vector<string> GetUpdateActionTypes() {
718 return {OmahaRequestAction::StaticType(),
719 OmahaResponseHandlerAction::StaticType(),
720 UpdateBootFlagsAction::StaticType(),
721 OmahaRequestAction::StaticType(),
722 DownloadActionChromeos::StaticType(),
723 OmahaRequestAction::StaticType(),
724 FilesystemVerifierAction::StaticType(),
725 PostinstallRunnerAction::StaticType(),
726 OmahaRequestAction::StaticType()};
727 }
728
729 // Actions that will be built as part of a user-initiated rollback.
GetRollbackActionTypes()730 vector<string> GetRollbackActionTypes() {
731 return {InstallPlanAction::StaticType(),
732 PostinstallRunnerAction::StaticType()};
733 }
734
735 const StagingSchedule kValidStagingSchedule = {
736 {4, 10}, {10, 40}, {19, 70}, {26, 100}};
737
738 } // namespace
739
UpdateTestStart()740 void UpdateAttempterTest::UpdateTestStart() {
741 attempter_.set_http_response_code(200);
742
743 // Expect that the device policy is loaded by the |UpdateAttempter| at some
744 // point by calling |RefreshDevicePolicy()|.
745 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
746 EXPECT_CALL(*device_policy, LoadPolicy())
747 .Times(testing::AtLeast(1))
748 .WillRepeatedly(Return(true));
749 attempter_.policy_provider_.reset(
750 new policy::PolicyProvider(std::move(device_policy)));
751
752 {
753 InSequence s;
754 for (const auto& update_action_type : GetUpdateActionTypes()) {
755 EXPECT_CALL(*processor_,
756 EnqueueAction(Pointee(
757 Property(&AbstractAction::Type, update_action_type))));
758 }
759 EXPECT_CALL(*processor_, StartProcessing());
760 }
761
762 attempter_.Update({});
763 loop_.PostTask(FROM_HERE,
764 base::Bind(&UpdateAttempterTest::UpdateTestVerify,
765 base::Unretained(this)));
766 }
767
UpdateTestVerify()768 void UpdateAttempterTest::UpdateTestVerify() {
769 EXPECT_EQ(0, attempter_.http_response_code());
770 EXPECT_EQ(&attempter_, processor_->delegate());
771 EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
772 loop_.BreakLoop();
773 }
774
RollbackTestStart(bool enterprise_rollback,bool valid_slot)775 void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
776 bool valid_slot) {
777 // Create a device policy so that we can change settings.
778 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
779 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
780 FakeSystemState::Get()->set_device_policy(device_policy.get());
781 if (enterprise_rollback) {
782 // We return an empty owner as this is an enterprise.
783 EXPECT_CALL(*device_policy, GetOwner(_))
784 .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
785 } else {
786 // We return a fake owner as this is an owned consumer device.
787 EXPECT_CALL(*device_policy, GetOwner(_))
788 .WillRepeatedly(DoAll(SetArgPointee<0>(string("fake.mail@fake.com")),
789 Return(true)));
790 }
791
792 attempter_.policy_provider_.reset(
793 new policy::PolicyProvider(std::move(device_policy)));
794
795 if (valid_slot) {
796 BootControlInterface::Slot rollback_slot = 1;
797 LOG(INFO) << "Test Mark Bootable: "
798 << BootControlInterface::SlotName(rollback_slot);
799 FakeSystemState::Get()->fake_boot_control()->SetSlotBootable(rollback_slot,
800 true);
801 }
802
803 bool is_rollback_allowed = false;
804
805 // We only allow rollback on devices that are not enterprise enrolled and
806 // which have a valid slot to rollback to.
807 if (!enterprise_rollback && valid_slot) {
808 is_rollback_allowed = true;
809 }
810
811 if (is_rollback_allowed) {
812 InSequence s;
813 for (const auto& rollback_action_type : GetRollbackActionTypes()) {
814 EXPECT_CALL(*processor_,
815 EnqueueAction(Pointee(
816 Property(&AbstractAction::Type, rollback_action_type))));
817 }
818 EXPECT_CALL(*processor_, StartProcessing());
819
820 EXPECT_TRUE(attempter_.Rollback(true));
821 loop_.PostTask(FROM_HERE,
822 base::Bind(&UpdateAttempterTest::RollbackTestVerify,
823 base::Unretained(this)));
824 } else {
825 EXPECT_FALSE(attempter_.Rollback(true));
826 loop_.BreakLoop();
827 }
828 }
829
RollbackTestVerify()830 void UpdateAttempterTest::RollbackTestVerify() {
831 // Verifies the actions that were enqueued.
832 EXPECT_EQ(&attempter_, processor_->delegate());
833 EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
834 EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
835 EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
836 loop_.BreakLoop();
837 }
838
TEST_F(UpdateAttempterTest,UpdateTest)839 TEST_F(UpdateAttempterTest, UpdateTest) {
840 UpdateTestStart();
841 loop_.Run();
842 }
843
TEST_F(UpdateAttempterTest,RollbackTest)844 TEST_F(UpdateAttempterTest, RollbackTest) {
845 loop_.PostTask(FROM_HERE,
846 base::Bind(&UpdateAttempterTest::RollbackTestStart,
847 base::Unretained(this),
848 false,
849 true));
850 loop_.Run();
851 }
852
TEST_F(UpdateAttempterTest,InvalidSlotRollbackTest)853 TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
854 loop_.PostTask(FROM_HERE,
855 base::Bind(&UpdateAttempterTest::RollbackTestStart,
856 base::Unretained(this),
857 false,
858 false));
859 loop_.Run();
860 }
861
TEST_F(UpdateAttempterTest,EnterpriseRollbackTest)862 TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
863 loop_.PostTask(FROM_HERE,
864 base::Bind(&UpdateAttempterTest::RollbackTestStart,
865 base::Unretained(this),
866 true,
867 true));
868 loop_.Run();
869 }
870
PingOmahaTestStart()871 void UpdateAttempterTest::PingOmahaTestStart() {
872 EXPECT_CALL(*processor_,
873 EnqueueAction(Pointee(Property(
874 &AbstractAction::Type, OmahaRequestAction::StaticType()))));
875 EXPECT_CALL(*processor_, StartProcessing());
876 attempter_.PingOmaha();
877 ScheduleQuitMainLoop();
878 }
879
TEST_F(UpdateAttempterTest,PingOmahaTest)880 TEST_F(UpdateAttempterTest, PingOmahaTest) {
881 EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
882 EXPECT_FALSE(attempter_.WasScheduleUpdatesCalled());
883 // Disable scheduling of subsequnet checks; we're using the |DefaultPolicy| in
884 // testing, which is more permissive than we want to handle here.
885 attempter_.DisableScheduleUpdates();
886 loop_.PostTask(FROM_HERE,
887 base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
888 base::Unretained(this)));
889 brillo::MessageLoopRunMaxIterations(&loop_, 100);
890 EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
891 EXPECT_TRUE(attempter_.WasScheduleUpdatesCalled());
892 }
893
TEST_F(UpdateAttempterTest,CreatePendingErrorEventTest)894 TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
895 MockAction action;
896 const ErrorCode kCode = ErrorCode::kDownloadTransferError;
897 attempter_.CreatePendingErrorEvent(&action, kCode);
898 ASSERT_NE(nullptr, attempter_.error_event_.get());
899 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
900 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
901 EXPECT_EQ(
902 static_cast<ErrorCode>(static_cast<int>(kCode) |
903 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
904 attempter_.error_event_->error_code);
905 }
906
TEST_F(UpdateAttempterTest,CreatePendingErrorEventResumedTest)907 TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
908 attempter_.install_plan_.reset(new InstallPlan);
909 attempter_.install_plan_->is_resume = true;
910 MockAction action;
911 const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
912 attempter_.CreatePendingErrorEvent(&action, kCode);
913 ASSERT_NE(nullptr, attempter_.error_event_.get());
914 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
915 EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
916 EXPECT_EQ(
917 static_cast<ErrorCode>(static_cast<int>(kCode) |
918 static_cast<int>(ErrorCode::kResumedFlag) |
919 static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
920 attempter_.error_event_->error_code);
921 }
922
TEST_F(UpdateAttempterTest,P2PNotStartedAtStartupWhenNotEnabled)923 TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
924 MockP2PManager mock_p2p_manager;
925 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
926 mock_p2p_manager.fake().SetP2PEnabled(false);
927 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
928 attempter_.UpdateEngineStarted();
929 }
930
TEST_F(UpdateAttempterTest,P2PNotStartedAtStartupWhenEnabledButNotSharing)931 TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
932 MockP2PManager mock_p2p_manager;
933 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
934 mock_p2p_manager.fake().SetP2PEnabled(true);
935 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
936 attempter_.UpdateEngineStarted();
937 }
938
TEST_F(UpdateAttempterTest,P2PStartedAtStartupWhenEnabledAndSharing)939 TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
940 MockP2PManager mock_p2p_manager;
941 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
942 mock_p2p_manager.fake().SetP2PEnabled(true);
943 mock_p2p_manager.fake().SetCountSharedFilesResult(1);
944 EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
945 attempter_.UpdateEngineStarted();
946 }
947
TEST_F(UpdateAttempterTest,P2PNotEnabled)948 TEST_F(UpdateAttempterTest, P2PNotEnabled) {
949 loop_.PostTask(FROM_HERE,
950 base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
951 base::Unretained(this)));
952 loop_.Run();
953 }
954
P2PNotEnabledStart()955 void UpdateAttempterTest::P2PNotEnabledStart() {
956 // If P2P is not enabled, check that we do not attempt housekeeping
957 // and do not convey that P2P is to be used.
958 MockP2PManager mock_p2p_manager;
959 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
960 mock_p2p_manager.fake().SetP2PEnabled(false);
961 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
962 attempter_.Update({});
963 EXPECT_FALSE(actual_using_p2p_for_downloading_);
964 EXPECT_FALSE(actual_using_p2p_for_sharing());
965 ScheduleQuitMainLoop();
966 }
967
TEST_F(UpdateAttempterTest,P2PEnabledStartingFails)968 TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
969 loop_.PostTask(FROM_HERE,
970 base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
971 base::Unretained(this)));
972 loop_.Run();
973 }
974
P2PEnabledStartingFailsStart()975 void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
976 // If P2P is enabled, but starting it fails ensure we don't do
977 // any housekeeping and do not convey that P2P should be used.
978 MockP2PManager mock_p2p_manager;
979 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
980 mock_p2p_manager.fake().SetP2PEnabled(true);
981 mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
982 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
983 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
984 attempter_.Update({});
985 EXPECT_FALSE(actual_using_p2p_for_downloading());
986 EXPECT_FALSE(actual_using_p2p_for_sharing());
987 ScheduleQuitMainLoop();
988 }
989
TEST_F(UpdateAttempterTest,P2PEnabledHousekeepingFails)990 TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
991 loop_.PostTask(
992 FROM_HERE,
993 base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
994 base::Unretained(this)));
995 loop_.Run();
996 }
997
P2PEnabledHousekeepingFailsStart()998 void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
999 // If P2P is enabled, starting it works but housekeeping fails, ensure
1000 // we do not convey P2P is to be used.
1001 MockP2PManager mock_p2p_manager;
1002 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
1003 mock_p2p_manager.fake().SetP2PEnabled(true);
1004 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1005 mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
1006 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
1007 attempter_.Update({});
1008 EXPECT_FALSE(actual_using_p2p_for_downloading());
1009 EXPECT_FALSE(actual_using_p2p_for_sharing());
1010 ScheduleQuitMainLoop();
1011 }
1012
TEST_F(UpdateAttempterTest,P2PEnabled)1013 TEST_F(UpdateAttempterTest, P2PEnabled) {
1014 loop_.PostTask(FROM_HERE,
1015 base::Bind(&UpdateAttempterTest::P2PEnabledStart,
1016 base::Unretained(this)));
1017 loop_.Run();
1018 }
1019
P2PEnabledStart()1020 void UpdateAttempterTest::P2PEnabledStart() {
1021 MockP2PManager mock_p2p_manager;
1022 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
1023 // If P2P is enabled and starting it works, check that we performed
1024 // housekeeping and that we convey P2P should be used.
1025 mock_p2p_manager.fake().SetP2PEnabled(true);
1026 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1027 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
1028 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
1029 attempter_.Update({});
1030 EXPECT_TRUE(actual_using_p2p_for_downloading());
1031 EXPECT_TRUE(actual_using_p2p_for_sharing());
1032 ScheduleQuitMainLoop();
1033 }
1034
TEST_F(UpdateAttempterTest,P2PEnabledInteractive)1035 TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
1036 loop_.PostTask(FROM_HERE,
1037 base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
1038 base::Unretained(this)));
1039 loop_.Run();
1040 }
1041
P2PEnabledInteractiveStart()1042 void UpdateAttempterTest::P2PEnabledInteractiveStart() {
1043 MockP2PManager mock_p2p_manager;
1044 FakeSystemState::Get()->set_p2p_manager(&mock_p2p_manager);
1045 // For an interactive check, if P2P is enabled and starting it
1046 // works, check that we performed housekeeping and that we convey
1047 // P2P should be used for sharing but NOT for downloading.
1048 mock_p2p_manager.fake().SetP2PEnabled(true);
1049 mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
1050 mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
1051 EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
1052 attempter_.Update({.interactive = true});
1053 EXPECT_FALSE(actual_using_p2p_for_downloading());
1054 EXPECT_TRUE(actual_using_p2p_for_sharing());
1055 ScheduleQuitMainLoop();
1056 }
1057
TEST_F(UpdateAttempterTest,ReadScatterFactorFromPolicy)1058 TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
1059 loop_.PostTask(
1060 FROM_HERE,
1061 base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
1062 base::Unretained(this)));
1063 loop_.Run();
1064 }
1065
1066 // Tests that the scatter_factor_in_seconds value is properly fetched
1067 // from the device policy.
ReadScatterFactorFromPolicyTestStart()1068 void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
1069 int64_t scatter_factor_in_seconds = 36000;
1070
1071 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1072 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1073 FakeSystemState::Get()->set_device_policy(device_policy.get());
1074
1075 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
1076 .WillRepeatedly(
1077 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
1078
1079 attempter_.policy_provider_.reset(
1080 new policy::PolicyProvider(std::move(device_policy)));
1081
1082 attempter_.Update({});
1083 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1084
1085 ScheduleQuitMainLoop();
1086 }
1087
TEST_F(UpdateAttempterTest,DecrementUpdateCheckCountTest)1088 TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
1089 loop_.PostTask(
1090 FROM_HERE,
1091 base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
1092 base::Unretained(this)));
1093 loop_.Run();
1094 }
1095
DecrementUpdateCheckCountTestStart()1096 void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
1097 // Tests that the scatter_factor_in_seconds value is properly fetched
1098 // from the device policy and is decremented if value > 0.
1099 int64_t initial_value = 5;
1100 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
1101 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1102
1103 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1104
1105 int64_t scatter_factor_in_seconds = 10;
1106
1107 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1108 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1109 FakeSystemState::Get()->set_device_policy(device_policy.get());
1110
1111 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
1112 .WillRepeatedly(
1113 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
1114
1115 attempter_.policy_provider_.reset(
1116 new policy::PolicyProvider(std::move(device_policy)));
1117
1118 attempter_.Update({});
1119 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1120
1121 // Make sure the file still exists.
1122 EXPECT_TRUE(fake_prefs->Exists(kPrefsUpdateCheckCount));
1123
1124 int64_t new_value;
1125 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &new_value));
1126 EXPECT_EQ(initial_value - 1, new_value);
1127
1128 EXPECT_TRUE(
1129 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1130
1131 // However, if the count is already 0, it's not decremented. Test that.
1132 initial_value = 0;
1133 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1134 attempter_.Update({});
1135 EXPECT_TRUE(fake_prefs->Exists(kPrefsUpdateCheckCount));
1136 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &new_value));
1137 EXPECT_EQ(initial_value, new_value);
1138
1139 ScheduleQuitMainLoop();
1140 }
1141
TEST_F(UpdateAttempterTest,NoScatteringDoneDuringManualUpdateTestStart)1142 TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
1143 loop_.PostTask(
1144 FROM_HERE,
1145 base::Bind(
1146 &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
1147 base::Unretained(this)));
1148 loop_.Run();
1149 }
1150
NoScatteringDoneDuringManualUpdateTestStart()1151 void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
1152 // Tests that no scattering logic is enabled if the update check
1153 // is manually done (as opposed to a scheduled update check)
1154 int64_t initial_value = 8;
1155 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
1156 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1157
1158 EXPECT_TRUE(
1159 fake_prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1160 EXPECT_TRUE(fake_prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
1161
1162 // make sure scatter_factor is non-zero as scattering is disabled
1163 // otherwise.
1164 int64_t scatter_factor_in_seconds = 50;
1165
1166 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1167 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1168 FakeSystemState::Get()->set_device_policy(device_policy.get());
1169
1170 EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
1171 .WillRepeatedly(
1172 DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
1173
1174 attempter_.policy_provider_.reset(
1175 new policy::PolicyProvider(std::move(device_policy)));
1176
1177 // Trigger an interactive check so we can test that scattering is disabled.
1178 attempter_.Update({.interactive = true});
1179 EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
1180
1181 // Make sure scattering is disabled for manual (i.e. user initiated) update
1182 // checks and all artifacts are removed.
1183 EXPECT_FALSE(
1184 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1185 EXPECT_FALSE(fake_prefs->Exists(kPrefsWallClockScatteringWaitPeriod));
1186 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
1187 EXPECT_FALSE(
1188 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1189 EXPECT_FALSE(fake_prefs->Exists(kPrefsUpdateCheckCount));
1190
1191 ScheduleQuitMainLoop();
1192 }
1193
SetUpStagingTest(const StagingSchedule & schedule)1194 void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule) {
1195 int64_t initial_value = 8;
1196 EXPECT_TRUE(
1197 prefs_->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
1198 EXPECT_TRUE(prefs_->SetInt64(kPrefsUpdateCheckCount, initial_value));
1199 attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
1200
1201 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1202 EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
1203 FakeSystemState::Get()->set_device_policy(device_policy.get());
1204 EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
1205 .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
1206
1207 attempter_.policy_provider_.reset(
1208 new policy::PolicyProvider(std::move(device_policy)));
1209 }
1210
TEST_F(UpdateAttempterTest,StagingSetsPrefsAndTurnsOffScattering)1211 TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
1212 loop_.PostTask(
1213 FROM_HERE,
1214 base::Bind(
1215 &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
1216 base::Unretained(this)));
1217 loop_.Run();
1218 }
1219
StagingSetsPrefsAndTurnsOffScatteringStart()1220 void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
1221 // Tests that staging sets its prefs properly and turns off scattering.
1222 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1223 SetUpStagingTest(kValidStagingSchedule);
1224
1225 attempter_.Update({});
1226 auto* fake_prefs = FakeSystemState::Get()->fake_prefs();
1227 // Check that prefs have the correct values.
1228 int64_t update_count;
1229 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsUpdateCheckCount, &update_count));
1230 int64_t waiting_time_days;
1231 EXPECT_TRUE(fake_prefs->GetInt64(kPrefsWallClockStagingWaitPeriod,
1232 &waiting_time_days));
1233 EXPECT_GT(waiting_time_days, 0);
1234 // Update count should have been decremented.
1235 EXPECT_EQ(7, update_count);
1236 // Check that Omaha parameters were updated correctly.
1237 EXPECT_TRUE(
1238 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1239 EXPECT_TRUE(
1240 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1241 EXPECT_EQ(waiting_time_days,
1242 attempter_.omaha_request_params_->waiting_period().InDays());
1243 // Check class variables.
1244 EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
1245 EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
1246 // Check that scattering is turned off
1247 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1248 EXPECT_FALSE(fake_prefs->Exists(kPrefsWallClockScatteringWaitPeriod));
1249
1250 ScheduleQuitMainLoop();
1251 }
1252
CheckStagingOff()1253 void UpdateAttempterTest::CheckStagingOff() {
1254 // Check that all prefs were removed.
1255 EXPECT_FALSE(prefs_->Exists(kPrefsUpdateCheckCount));
1256 EXPECT_FALSE(prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
1257 EXPECT_FALSE(prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
1258 // Check that the Omaha parameters have the correct value.
1259 EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
1260 EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
1261 attempter_.staging_wait_time_);
1262 EXPECT_FALSE(
1263 attempter_.omaha_request_params_->update_check_count_wait_enabled());
1264 EXPECT_FALSE(
1265 attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
1266 // Check that scattering is turned off too.
1267 EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
1268 }
1269
TEST_F(UpdateAttempterTest,StagingOffIfInteractive)1270 TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
1271 loop_.PostTask(FROM_HERE,
1272 base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
1273 base::Unretained(this)));
1274 loop_.Run();
1275 }
1276
StagingOffIfInteractiveStart()1277 void UpdateAttempterTest::StagingOffIfInteractiveStart() {
1278 // Tests that staging is turned off when an interactive update is requested.
1279 FakeSystemState::Get()->fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
1280 SetUpStagingTest(kValidStagingSchedule);
1281
1282 attempter_.Update({.interactive = true});
1283 CheckStagingOff();
1284
1285 ScheduleQuitMainLoop();
1286 }
1287
TEST_F(UpdateAttempterTest,StagingOffIfOobe)1288 TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
1289 loop_.PostTask(FROM_HERE,
1290 base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
1291 base::Unretained(this)));
1292 loop_.Run();
1293 }
1294
StagingOffIfOobeStart()1295 void UpdateAttempterTest::StagingOffIfOobeStart() {
1296 // Tests that staging is turned off if OOBE hasn't been completed.
1297 FakeSystemState::Get()->fake_hardware()->SetIsOOBEEnabled(true);
1298 FakeSystemState::Get()->fake_hardware()->UnsetIsOOBEComplete();
1299 SetUpStagingTest(kValidStagingSchedule);
1300
1301 attempter_.Update({.interactive = true});
1302 CheckStagingOff();
1303
1304 ScheduleQuitMainLoop();
1305 }
1306
1307 // Checks that we only report daily metrics at most every 24 hours.
TEST_F(UpdateAttempterTest,ReportDailyMetrics)1308 TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
1309 auto* fake_clock = FakeSystemState::Get()->fake_clock();
1310 Time epoch = Time::FromInternalValue(0);
1311 fake_clock->SetWallclockTime(epoch);
1312
1313 // If there is no kPrefsDailyMetricsLastReportedAt state variable,
1314 // we should report.
1315 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1316 // We should not report again if no time has passed.
1317 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1318
1319 // We should not report if only 10 hours has passed.
1320 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(10));
1321 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1322
1323 // We should not report if only 24 hours - 1 sec has passed.
1324 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24) -
1325 TimeDelta::FromSeconds(1));
1326 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1327
1328 // We should report if 24 hours has passed.
1329 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(24));
1330 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1331
1332 // But then we should not report again..
1333 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1334
1335 // .. until another 24 hours has passed
1336 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(47));
1337 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1338 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(48));
1339 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1340 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1341
1342 // .. and another 24 hours
1343 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
1344 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1345 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(72));
1346 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1347 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1348
1349 // If the span between time of reporting and present time is
1350 // negative, we report. This is in order to reset the timestamp and
1351 // avoid an edge condition whereby a distant point in the future is
1352 // in the state variable resulting in us never ever reporting again.
1353 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(71));
1354 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1355 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1356
1357 // In this case we should not update until the clock reads 71 + 24 = 95.
1358 // Check that.
1359 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(94));
1360 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1361 fake_clock->SetWallclockTime(epoch + TimeDelta::FromHours(95));
1362 EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
1363 EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
1364 }
1365
TEST_F(UpdateAttempterTest,BootTimeInUpdateMarkerFile)1366 TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
1367 FakeSystemState::Get()->fake_clock()->SetBootTime(Time::FromTimeT(42));
1368 attempter_.Init();
1369
1370 Time boot_time;
1371 EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
1372
1373 attempter_.WriteUpdateCompletedMarker();
1374
1375 EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
1376 EXPECT_EQ(boot_time.ToTimeT(), 42);
1377 }
1378
TEST_F(UpdateAttempterTest,AnyUpdateSourceAllowedUnofficial)1379 TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
1380 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(false);
1381 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1382 }
1383
TEST_F(UpdateAttempterTest,AnyUpdateSourceAllowedOfficialDevmode)1384 TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
1385 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1386 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(true);
1387 EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
1388 }
1389
TEST_F(UpdateAttempterTest,AnyUpdateSourceDisallowedOfficialNormal)1390 TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
1391 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1392 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
1393 EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
1394 }
1395
1396 // TODO(kimjae): Follow testing pattern with params for |CheckForInstall()|.
1397 // When adding, remove older tests related to |CheckForInstall()|.
TEST_F(UpdateAttempterTest,CheckForInstallNotIdleFails)1398 TEST_F(UpdateAttempterTest, CheckForInstallNotIdleFails) {
1399 for (const auto status : kNonIdleUpdateStatuses) {
1400 // GIVEN a non-idle status.
1401 attempter_.status_ = status;
1402
1403 EXPECT_FALSE(attempter_.CheckForInstall({}, ""));
1404 }
1405 }
1406
TEST_F(UpdateAttempterTest,CheckForUpdateNotIdleFails)1407 TEST_F(UpdateAttempterTest, CheckForUpdateNotIdleFails) {
1408 for (const auto status : kNonIdleUpdateStatuses) {
1409 // GIVEN a non-idle status.
1410 cfu_params_.status = status;
1411
1412 // THEN |ScheduleUpdates()| should not be called.
1413 cfu_params_.should_schedule_updates_be_called = false;
1414 // THEN result should indicate failure.
1415 cfu_params_.expected_result = false;
1416
1417 TestCheckForUpdate();
1418 }
1419 }
1420
TEST_F(UpdateAttempterTest,CheckForUpdateOfficalBuildClearsSource)1421 TEST_F(UpdateAttempterTest, CheckForUpdateOfficalBuildClearsSource) {
1422 // GIVEN a official build.
1423
1424 // THEN we except forced app version + forced omaha url to be cleared.
1425
1426 TestCheckForUpdate();
1427 }
1428
TEST_F(UpdateAttempterTest,CheckForUpdateUnofficialBuildChangesSource)1429 TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildChangesSource) {
1430 // GIVEN a nonofficial build with dev features enabled.
1431 cfu_params_.is_official_build = false;
1432 cfu_params_.are_dev_features_enabled = true;
1433
1434 // THEN the forced app version + forced omaha url changes based on input.
1435 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1436 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1437
1438 TestCheckForUpdate();
1439 }
1440
TEST_F(UpdateAttempterTest,CheckForUpdateOfficialBuildScheduledAUTest)1441 TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildScheduledAUTest) {
1442 // GIVEN a scheduled autest omaha url.
1443 cfu_params_.omaha_url = "autest-scheduled";
1444
1445 // THEN forced app version is cleared.
1446 // THEN forced omaha url changes to default constant.
1447 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1448
1449 TestCheckForUpdate();
1450 }
1451
TEST_F(UpdateAttempterTest,CheckForUpdateUnofficialBuildScheduledAUTest)1452 TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildScheduledAUTest) {
1453 // GIVEN a scheduled autest omaha url.
1454 cfu_params_.omaha_url = "autest-scheduled";
1455 // GIVEN a nonofficial build with dev features enabled.
1456 cfu_params_.is_official_build = false;
1457 cfu_params_.are_dev_features_enabled = true;
1458
1459 // THEN forced app version changes based on input.
1460 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1461 // THEN forced omaha url changes to default constant.
1462 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1463
1464 TestCheckForUpdate();
1465 }
1466
TEST_F(UpdateAttempterTest,CheckForUpdateOfficialBuildAUTest)1467 TEST_F(UpdateAttempterTest, CheckForUpdateOfficialBuildAUTest) {
1468 // GIVEN a autest omaha url.
1469 cfu_params_.omaha_url = "autest";
1470
1471 // THEN forced app version is cleared.
1472 // THEN forced omaha url changes to default constant.
1473 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1474
1475 TestCheckForUpdate();
1476 }
1477
TEST_F(UpdateAttempterTest,CheckForUpdateUnofficialBuildAUTest)1478 TEST_F(UpdateAttempterTest, CheckForUpdateUnofficialBuildAUTest) {
1479 // GIVEN a autest omha url.
1480 cfu_params_.omaha_url = "autest";
1481 // GIVEN a nonofficial build with dev features enabled.
1482 cfu_params_.is_official_build = false;
1483 cfu_params_.are_dev_features_enabled = true;
1484
1485 // THEN forced app version changes based on input.
1486 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1487 // THEN forced omaha url changes to default constant.
1488 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1489
1490 TestCheckForUpdate();
1491 }
1492
TEST_F(UpdateAttempterTest,CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest)1493 TEST_F(UpdateAttempterTest,
1494 CheckForUpdateNonInteractiveOfficialBuildScheduledAUTest) {
1495 // GIVEN a scheduled autest omaha url.
1496 cfu_params_.omaha_url = "autest-scheduled";
1497 // GIVEN a noninteractive update.
1498 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1499
1500 // THEN forced app version is cleared.
1501 // THEN forced omaha url changes to default constant.
1502 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1503
1504 TestCheckForUpdate();
1505 }
1506
TEST_F(UpdateAttempterTest,CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest)1507 TEST_F(UpdateAttempterTest,
1508 CheckForUpdateNonInteractiveUnofficialBuildScheduledAUTest) {
1509 // GIVEN a scheduled autest omaha url.
1510 cfu_params_.omaha_url = "autest-scheduled";
1511 // GIVEN a noninteractive update.
1512 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1513 // GIVEN a nonofficial build with dev features enabled.
1514 cfu_params_.is_official_build = false;
1515 cfu_params_.are_dev_features_enabled = true;
1516
1517 // THEN forced app version changes based on input.
1518 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1519 // THEN forced omaha url changes to default constant.
1520 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1521
1522 TestCheckForUpdate();
1523 }
1524
TEST_F(UpdateAttempterTest,CheckForUpdateNonInteractiveOfficialBuildAUTest)1525 TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveOfficialBuildAUTest) {
1526 // GIVEN a autest omaha url.
1527 cfu_params_.omaha_url = "autest";
1528 // GIVEN a noninteractive update.
1529 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1530
1531 // THEN forced app version is cleared.
1532 // THEN forced omaha url changes to default constant.
1533 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1534
1535 TestCheckForUpdate();
1536 }
1537
TEST_F(UpdateAttempterTest,CheckForUpdateNonInteractiveUnofficialBuildAUTest)1538 TEST_F(UpdateAttempterTest, CheckForUpdateNonInteractiveUnofficialBuildAUTest) {
1539 // GIVEN a autest omaha url.
1540 cfu_params_.omaha_url = "autest";
1541 // GIVEN a noninteractive update.
1542 cfu_params_.flags = UpdateAttemptFlags::kFlagNonInteractive;
1543 // GIVEN a nonofficial build with dev features enabled.
1544 cfu_params_.is_official_build = false;
1545 cfu_params_.are_dev_features_enabled = true;
1546
1547 // THEN forced app version changes based on input.
1548 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1549 // THEN forced omaha url changes to default constant.
1550 cfu_params_.expected_forced_omaha_url = constants::kOmahaDefaultAUTestURL;
1551
1552 TestCheckForUpdate();
1553 }
1554
TEST_F(UpdateAttempterTest,CheckForUpdateMissingForcedCallback1)1555 TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback1) {
1556 // GIVEN a official build.
1557 // GIVEN forced callback is not set.
1558 attempter_.set_forced_update_pending_callback(nullptr);
1559
1560 // THEN we except forced app version + forced omaha url to be cleared.
1561 // THEN |ScheduleUpdates()| should not be called.
1562 cfu_params_.should_schedule_updates_be_called = false;
1563
1564 TestCheckForUpdate();
1565 }
1566
TEST_F(UpdateAttempterTest,CheckForUpdateMissingForcedCallback2)1567 TEST_F(UpdateAttempterTest, CheckForUpdateMissingForcedCallback2) {
1568 // GIVEN a nonofficial build with dev features enabled.
1569 cfu_params_.is_official_build = false;
1570 cfu_params_.are_dev_features_enabled = true;
1571 // GIVEN forced callback is not set.
1572 attempter_.set_forced_update_pending_callback(nullptr);
1573
1574 // THEN the forced app version + forced omaha url changes based on input.
1575 cfu_params_.expected_forced_app_version = cfu_params_.app_version;
1576 cfu_params_.expected_forced_omaha_url = cfu_params_.omaha_url;
1577 // THEN |ScheduleUpdates()| should not be called.
1578 cfu_params_.should_schedule_updates_be_called = false;
1579
1580 TestCheckForUpdate();
1581 }
1582
TEST_F(UpdateAttempterTest,CheckForInstallTest)1583 TEST_F(UpdateAttempterTest, CheckForInstallTest) {
1584 FakeSystemState::Get()->fake_hardware()->SetIsOfficialBuild(true);
1585 FakeSystemState::Get()->fake_hardware()->SetAreDevFeaturesEnabled(false);
1586 attempter_.CheckForInstall({}, "autest");
1587 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1588
1589 attempter_.CheckForInstall({}, "autest-scheduled");
1590 EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
1591
1592 attempter_.CheckForInstall({}, "http://omaha.phishing");
1593 EXPECT_EQ("", attempter_.forced_omaha_url());
1594 }
1595
TEST_F(UpdateAttempterTest,InstallSetsStatusIdle)1596 TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
1597 attempter_.CheckForInstall({}, "http://foo.bar");
1598 attempter_.status_ = UpdateStatus::DOWNLOADING;
1599 EXPECT_TRUE(attempter_.is_install_);
1600 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1601 UpdateEngineStatus status;
1602 attempter_.GetStatus(&status);
1603 // Should set status to idle after an install operation.
1604 EXPECT_EQ(UpdateStatus::IDLE, status.status);
1605 }
1606
TEST_F(UpdateAttempterTest,RollbackAfterInstall)1607 TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
1608 attempter_.is_install_ = true;
1609 attempter_.Rollback(false);
1610 EXPECT_FALSE(attempter_.is_install_);
1611 }
1612
TEST_F(UpdateAttempterTest,UpdateAfterInstall)1613 TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
1614 attempter_.is_install_ = true;
1615 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1616 EXPECT_FALSE(attempter_.is_install_);
1617 }
1618
TEST_F(UpdateAttempterTest,TargetVersionPrefixSetAndReset)1619 TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
1620 UpdateCheckParams params;
1621 attempter_.CalculateUpdateParams({.target_version_prefix = "1234"});
1622 EXPECT_EQ("1234",
1623 FakeSystemState::Get()->request_params()->target_version_prefix());
1624
1625 attempter_.CalculateUpdateParams({});
1626 EXPECT_TRUE(FakeSystemState::Get()
1627 ->request_params()
1628 ->target_version_prefix()
1629 .empty());
1630 }
1631
TEST_F(UpdateAttempterTest,TargetChannelHintSetAndReset)1632 TEST_F(UpdateAttempterTest, TargetChannelHintSetAndReset) {
1633 attempter_.CalculateUpdateParams({.lts_tag = "hint"});
1634 EXPECT_EQ("hint", FakeSystemState::Get()->request_params()->lts_tag());
1635
1636 attempter_.CalculateUpdateParams({});
1637 EXPECT_TRUE(FakeSystemState::Get()->request_params()->lts_tag().empty());
1638 }
1639
TEST_F(UpdateAttempterTest,RollbackAllowedSetAndReset)1640 TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
1641 attempter_.CalculateUpdateParams({
1642 .target_version_prefix = "1234",
1643 .rollback_allowed = true,
1644 .rollback_allowed_milestones = 4,
1645 });
1646 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1647 EXPECT_EQ(
1648 4,
1649 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
1650
1651 attempter_.CalculateUpdateParams({
1652 .target_version_prefix = "1234",
1653 .rollback_allowed_milestones = 4,
1654 });
1655 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1656 EXPECT_EQ(
1657 4,
1658 FakeSystemState::Get()->request_params()->rollback_allowed_milestones());
1659 }
1660
TEST_F(UpdateAttempterTest,ChannelDowngradeNoRollback)1661 TEST_F(UpdateAttempterTest, ChannelDowngradeNoRollback) {
1662 base::ScopedTempDir tempdir;
1663 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
1664 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
1665 attempter_.CalculateUpdateParams({
1666 .target_channel = "stable-channel",
1667 });
1668 EXPECT_FALSE(
1669 FakeSystemState::Get()->request_params()->is_powerwash_allowed());
1670 }
1671
TEST_F(UpdateAttempterTest,ChannelDowngradeRollback)1672 TEST_F(UpdateAttempterTest, ChannelDowngradeRollback) {
1673 base::ScopedTempDir tempdir;
1674 ASSERT_TRUE(tempdir.CreateUniqueTempDir());
1675 FakeSystemState::Get()->request_params()->set_root(tempdir.GetPath().value());
1676 attempter_.CalculateUpdateParams({
1677 .rollback_on_channel_downgrade = true,
1678 .target_channel = "stable-channel",
1679 });
1680 EXPECT_TRUE(FakeSystemState::Get()->request_params()->is_powerwash_allowed());
1681 }
1682
TEST_F(UpdateAttempterTest,UpdateDeferredByPolicyTest)1683 TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
1684 // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
1685 // but the update is being deferred by the Policy.
1686 OmahaResponseHandlerAction response_action;
1687 response_action.install_plan_.version = "a.b.c.d";
1688 response_action.install_plan_.payloads.push_back(
1689 {.size = 1234ULL, .type = InstallPayloadType::kFull});
1690 // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
1691 // completed, with the deferred-update error code.
1692 attempter_.ActionCompleted(
1693 nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1694 {
1695 UpdateEngineStatus status;
1696 attempter_.GetStatus(&status);
1697 EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
1698 EXPECT_TRUE(attempter_.install_plan_);
1699 EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
1700 EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
1701 status.new_size_bytes);
1702 }
1703 // An "error" event should have been created to tell Omaha that the update is
1704 // being deferred.
1705 EXPECT_TRUE(nullptr != attempter_.error_event_);
1706 EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
1707 EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
1708 ErrorCode expected_code = static_cast<ErrorCode>(
1709 static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
1710 static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
1711 EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
1712 // End the processing
1713 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1714 // Validate the state of the attempter.
1715 {
1716 UpdateEngineStatus status;
1717 attempter_.GetStatus(&status);
1718 EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
1719 EXPECT_EQ(response_action.install_plan_.version, status.new_version);
1720 EXPECT_EQ(response_action.install_plan_.payloads[0].size,
1721 status.new_size_bytes);
1722 }
1723 }
1724
TEST_F(UpdateAttempterTest,UpdateIsNotRunningWhenUpdateAvailable)1725 TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
1726 // Default construction for |waiting_for_scheduled_check_| is false.
1727 EXPECT_FALSE(attempter_.IsBusyOrUpdateScheduled());
1728 // Verify in-progress update with UPDATE_AVAILABLE is running
1729 attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
1730 EXPECT_TRUE(attempter_.IsBusyOrUpdateScheduled());
1731 }
1732
TEST_F(UpdateAttempterTest,UpdateAttemptFlagsCachedAtUpdateStart)1733 TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
1734 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1735
1736 UpdateCheckParams params = {.updates_enabled = true};
1737 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1738
1739 EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
1740 attempter_.GetCurrentUpdateAttemptFlags());
1741 }
1742
TEST_F(UpdateAttempterTest,RollbackNotAllowed)1743 TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
1744 UpdateCheckParams params = {.updates_enabled = true,
1745 .rollback_allowed = false};
1746 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1747 EXPECT_FALSE(FakeSystemState::Get()->request_params()->rollback_allowed());
1748 }
1749
TEST_F(UpdateAttempterTest,RollbackAllowed)1750 TEST_F(UpdateAttempterTest, RollbackAllowed) {
1751 UpdateCheckParams params = {.updates_enabled = true,
1752 .rollback_allowed = true};
1753 attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
1754 EXPECT_TRUE(FakeSystemState::Get()->request_params()->rollback_allowed());
1755 }
1756
TEST_F(UpdateAttempterTest,InteractiveUpdateUsesPassedRestrictions)1757 TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
1758 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
1759
1760 attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
1761 EXPECT_EQ(UpdateAttemptFlags::kNone,
1762 attempter_.GetCurrentUpdateAttemptFlags());
1763 }
1764
TEST_F(UpdateAttempterTest,NonInteractiveUpdateUsesSetRestrictions)1765 TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
1766 attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
1767
1768 // This tests that when CheckForUpdate() is called with the non-interactive
1769 // flag set, that it doesn't change the current UpdateAttemptFlags.
1770 attempter_.CheckForUpdate("",
1771 "",
1772 UpdateAttemptFlags::kFlagNonInteractive |
1773 UpdateAttemptFlags::kFlagRestrictDownload);
1774 EXPECT_EQ(UpdateAttemptFlags::kNone,
1775 attempter_.GetCurrentUpdateAttemptFlags());
1776 }
1777
ResetRollbackHappenedStart(bool is_consumer,bool is_policy_loaded,bool expected_reset)1778 void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
1779 bool is_policy_loaded,
1780 bool expected_reset) {
1781 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1782 GetRollbackHappened())
1783 .WillRepeatedly(Return(true));
1784 auto mock_policy_provider =
1785 std::make_unique<NiceMock<policy::MockPolicyProvider>>();
1786 EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
1787 .WillRepeatedly(Return(is_consumer));
1788 EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
1789 .WillRepeatedly(Return(is_policy_loaded));
1790 const policy::MockDevicePolicy device_policy;
1791 EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
1792 .WillRepeatedly(ReturnRef(device_policy));
1793 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1794 SetRollbackHappened(false))
1795 .Times(expected_reset ? 1 : 0);
1796 attempter_.policy_provider_ = std::move(mock_policy_provider);
1797 attempter_.Update({});
1798 ScheduleQuitMainLoop();
1799 }
1800
TEST_F(UpdateAttempterTest,ResetRollbackHappenedOobe)1801 TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
1802 loop_.PostTask(FROM_HERE,
1803 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1804 base::Unretained(this),
1805 /*is_consumer=*/false,
1806 /*is_policy_loaded=*/false,
1807 /*expected_reset=*/false));
1808 loop_.Run();
1809 }
1810
TEST_F(UpdateAttempterTest,ResetRollbackHappenedConsumer)1811 TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
1812 loop_.PostTask(FROM_HERE,
1813 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1814 base::Unretained(this),
1815 /*is_consumer=*/true,
1816 /*is_policy_loaded=*/false,
1817 /*expected_reset=*/true));
1818 loop_.Run();
1819 }
1820
TEST_F(UpdateAttempterTest,ResetRollbackHappenedEnterprise)1821 TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
1822 loop_.PostTask(FROM_HERE,
1823 base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
1824 base::Unretained(this),
1825 /*is_consumer=*/false,
1826 /*is_policy_loaded=*/true,
1827 /*expected_reset=*/true));
1828 loop_.Run();
1829 }
1830
TEST_F(UpdateAttempterTest,SetRollbackHappenedRollback)1831 TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
1832 attempter_.install_plan_.reset(new InstallPlan);
1833 attempter_.install_plan_->is_rollback = true;
1834
1835 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1836 SetRollbackHappened(true))
1837 .Times(1);
1838 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1839 }
1840
TEST_F(UpdateAttempterTest,SetRollbackHappenedNotRollback)1841 TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
1842 attempter_.install_plan_.reset(new InstallPlan);
1843 attempter_.install_plan_->is_rollback = false;
1844
1845 EXPECT_CALL(*FakeSystemState::Get()->mock_payload_state(),
1846 SetRollbackHappened(true))
1847 .Times(0);
1848 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1849 }
1850
TEST_F(UpdateAttempterTest,RollbackMetricsRollbackSuccess)1851 TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
1852 attempter_.install_plan_.reset(new InstallPlan);
1853 attempter_.install_plan_->is_rollback = true;
1854 attempter_.install_plan_->version = kRollbackVersion;
1855
1856 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1857 ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
1858 .Times(1);
1859 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1860 }
1861
TEST_F(UpdateAttempterTest,RollbackMetricsNotRollbackSuccess)1862 TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
1863 attempter_.install_plan_.reset(new InstallPlan);
1864 attempter_.install_plan_->is_rollback = false;
1865 attempter_.install_plan_->version = kRollbackVersion;
1866
1867 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1868 ReportEnterpriseRollbackMetrics(_, _))
1869 .Times(0);
1870 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1871 }
1872
TEST_F(UpdateAttempterTest,RollbackMetricsRollbackFailure)1873 TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
1874 attempter_.install_plan_.reset(new InstallPlan);
1875 attempter_.install_plan_->is_rollback = true;
1876 attempter_.install_plan_->version = kRollbackVersion;
1877
1878 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1879 ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
1880 .Times(1);
1881 MockAction action;
1882 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1883 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1884 }
1885
TEST_F(UpdateAttempterTest,RollbackMetricsNotRollbackFailure)1886 TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
1887 attempter_.install_plan_.reset(new InstallPlan);
1888 attempter_.install_plan_->is_rollback = false;
1889 attempter_.install_plan_->version = kRollbackVersion;
1890
1891 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1892 ReportEnterpriseRollbackMetrics(_, _))
1893 .Times(0);
1894 MockAction action;
1895 attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
1896 attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
1897 }
1898
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedMetricFailure)1899 TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
1900 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1901 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1902 .Times(0);
1903 attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
1904 }
1905
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedOnNonEnterprise)1906 TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
1907 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1908 FakeSystemState::Get()->set_device_policy(device_policy.get());
1909 // Make device policy return that this is not enterprise enrolled
1910 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
1911
1912 // Ensure that the metric is not recorded.
1913 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1914 ReportEnterpriseUpdateSeenToDownloadDays(_, _))
1915 .Times(0);
1916 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1917 }
1918
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedWithTimeRestrictionMetricSuccess)1919 TEST_F(UpdateAttempterTest,
1920 TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
1921 constexpr int kDaysToUpdate = 15;
1922 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1923 FakeSystemState::Get()->set_device_policy(device_policy.get());
1924 // Make device policy return that this is enterprise enrolled
1925 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1926 // Pretend that there's a time restriction policy in place
1927 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1928 .WillOnce(Return(true));
1929
1930 Time update_first_seen_at = Time::Now();
1931 FakeSystemState::Get()->fake_prefs()->SetInt64(
1932 kPrefsUpdateFirstSeenAt, update_first_seen_at.ToInternalValue());
1933
1934 Time update_finished_at =
1935 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1936 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
1937
1938 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1939 ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
1940 .Times(1);
1941 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1942 }
1943
TEST_F(UpdateAttempterTest,TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess)1944 TEST_F(UpdateAttempterTest,
1945 TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
1946 constexpr int kDaysToUpdate = 15;
1947 auto device_policy = std::make_unique<policy::MockDevicePolicy>();
1948 FakeSystemState::Get()->set_device_policy(device_policy.get());
1949 // Make device policy return that this is enterprise enrolled
1950 EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
1951 // Pretend that there's no time restriction policy in place
1952 EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
1953 .WillOnce(Return(false));
1954
1955 Time update_first_seen_at = Time::Now();
1956 FakeSystemState::Get()->fake_prefs()->SetInt64(
1957 kPrefsUpdateFirstSeenAt, update_first_seen_at.ToInternalValue());
1958
1959 Time update_finished_at =
1960 update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
1961 FakeSystemState::Get()->fake_clock()->SetWallclockTime(update_finished_at);
1962
1963 EXPECT_CALL(*FakeSystemState::Get()->mock_metrics_reporter(),
1964 ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
1965 .Times(1);
1966 attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
1967 }
1968
TEST_F(UpdateAttempterTest,ProcessingDoneUpdated)1969 TEST_F(UpdateAttempterTest, ProcessingDoneUpdated) {
1970 // GIVEN an update finished.
1971
1972 // THEN update_engine should call update completion.
1973 pd_params_.should_update_completed_be_called = true;
1974 // THEN need reboot since update applied.
1975 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
1976 // THEN install indication should be false.
1977
1978 TestProcessingDone();
1979 }
1980
TEST_F(UpdateAttempterTest,ProcessingDoneUpdatedDlcFilter)1981 TEST_F(UpdateAttempterTest, ProcessingDoneUpdatedDlcFilter) {
1982 // GIVEN an update finished.
1983 // GIVEN DLC |AppParams| list.
1984 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
1985 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
1986 {dlc_2, {.name = dlc_2}}};
1987
1988 // THEN update_engine should call update completion.
1989 pd_params_.should_update_completed_be_called = true;
1990 pd_params_.args_to_update_completed = {dlc_2};
1991 // THEN need reboot since update applied.
1992 pd_params_.expected_exit_status = UpdateStatus::UPDATED_NEED_REBOOT;
1993 // THEN install indication should be false.
1994
1995 TestProcessingDone();
1996 }
1997
TEST_F(UpdateAttempterTest,ProcessingDoneInstalled)1998 TEST_F(UpdateAttempterTest, ProcessingDoneInstalled) {
1999 // GIVEN an install finished.
2000 pd_params_.is_install = true;
2001
2002 // THEN update_engine should call install completion.
2003 pd_params_.should_install_completed_be_called = true;
2004 // THEN go idle.
2005 // THEN install indication should be false.
2006
2007 TestProcessingDone();
2008 }
2009
TEST_F(UpdateAttempterTest,ProcessingDoneInstalledDlcFilter)2010 TEST_F(UpdateAttempterTest, ProcessingDoneInstalledDlcFilter) {
2011 // GIVEN an install finished.
2012 pd_params_.is_install = true;
2013 // GIVEN DLC |AppParams| list.
2014 auto dlc_1 = "dlc_1", dlc_2 = "dlc_2";
2015 pd_params_.dlc_apps_params = {{dlc_1, {.name = dlc_1, .updated = false}},
2016 {dlc_2, {.name = dlc_2}}};
2017
2018 // THEN update_engine should call install completion.
2019 pd_params_.should_install_completed_be_called = true;
2020 pd_params_.args_to_install_completed = {dlc_2};
2021 // THEN go idle.
2022 // THEN install indication should be false.
2023
2024 TestProcessingDone();
2025 }
2026
TEST_F(UpdateAttempterTest,ProcessingDoneInstallReportingError)2027 TEST_F(UpdateAttempterTest, ProcessingDoneInstallReportingError) {
2028 // GIVEN an install finished.
2029 pd_params_.is_install = true;
2030 // GIVEN a reporting error occurred.
2031 pd_params_.status = UpdateStatus::REPORTING_ERROR_EVENT;
2032
2033 // THEN update_engine should not call install completion.
2034 // THEN go idle.
2035 // THEN install indication should be false.
2036
2037 TestProcessingDone();
2038 }
2039
TEST_F(UpdateAttempterTest,ProcessingDoneNoUpdate)2040 TEST_F(UpdateAttempterTest, ProcessingDoneNoUpdate) {
2041 // GIVEN an update finished.
2042 // GIVEN an action error occured.
2043 pd_params_.code = ErrorCode::kNoUpdate;
2044
2045 // THEN update_engine should not call update completion.
2046 // THEN go idle.
2047 // THEN install indication should be false.
2048
2049 TestProcessingDone();
2050 }
2051
TEST_F(UpdateAttempterTest,ProcessingDoneNoInstall)2052 TEST_F(UpdateAttempterTest, ProcessingDoneNoInstall) {
2053 // GIVEN an install finished.
2054 pd_params_.is_install = true;
2055 // GIVEN an action error occured.
2056 pd_params_.code = ErrorCode::kNoUpdate;
2057
2058 // THEN update_engine should not call install completion.
2059 // THEN go idle.
2060 // THEN install indication should be false.
2061
2062 TestProcessingDone();
2063 }
2064
TEST_F(UpdateAttempterTest,ProcessingDoneUpdateError)2065 TEST_F(UpdateAttempterTest, ProcessingDoneUpdateError) {
2066 // GIVEN an update finished.
2067 // GIVEN an action error occured.
2068 pd_params_.code = ErrorCode::kError;
2069 // GIVEN an event error is set.
2070 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2071 OmahaEvent::kResultError,
2072 ErrorCode::kError));
2073
2074 // THEN indicate a error event.
2075 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2076 // THEN install indication should be false.
2077
2078 // THEN update_engine should not call update completion.
2079 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2080 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2081 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2082 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2083 pd_params_.should_schedule_updates_be_called = false;
2084
2085 TestProcessingDone();
2086 }
2087
TEST_F(UpdateAttempterTest,ProcessingDoneInstallError)2088 TEST_F(UpdateAttempterTest, ProcessingDoneInstallError) {
2089 // GIVEN an install finished.
2090 pd_params_.is_install = true;
2091 // GIVEN an action error occured.
2092 pd_params_.code = ErrorCode::kError;
2093 // GIVEN an event error is set.
2094 attempter_.error_event_.reset(new OmahaEvent(OmahaEvent::kTypeUpdateComplete,
2095 OmahaEvent::kResultError,
2096 ErrorCode::kError));
2097
2098 // THEN indicate a error event.
2099 pd_params_.expected_exit_status = UpdateStatus::REPORTING_ERROR_EVENT;
2100 // THEN install indication should be false.
2101
2102 // THEN update_engine should not call install completion.
2103 // THEN expect critical actions of |ScheduleErrorEventAction()|.
2104 EXPECT_CALL(*processor_, EnqueueAction(Pointee(_))).Times(1);
2105 EXPECT_CALL(*processor_, StartProcessing()).Times(1);
2106 // THEN |ScheduleUpdates()| will be called next |ProcessingDone()| so skip.
2107 pd_params_.should_schedule_updates_be_called = false;
2108
2109 TestProcessingDone();
2110 }
2111
TEST_F(UpdateAttempterTest,QuickFixTokenWhenDeviceIsEnterpriseEnrolled)2112 TEST_F(UpdateAttempterTest, QuickFixTokenWhenDeviceIsEnterpriseEnrolled) {
2113 attempter_.CalculateUpdateParams({.quick_fix_build_token = "token"});
2114 EXPECT_EQ("token",
2115 FakeSystemState::Get()->request_params()->autoupdate_token());
2116
2117 attempter_.CalculateUpdateParams({});
2118 EXPECT_TRUE(
2119 FakeSystemState::Get()->request_params()->autoupdate_token().empty());
2120 }
2121
TEST_F(UpdateAttempterTest,ScheduleUpdateSpamHandlerTest)2122 TEST_F(UpdateAttempterTest, ScheduleUpdateSpamHandlerTest) {
2123 EXPECT_CALL(mock_update_manager_, AsyncPolicyRequestUpdateCheckAllowed(_, _))
2124 .Times(1);
2125 EXPECT_TRUE(attempter_.ScheduleUpdates());
2126 // Now there is an update scheduled which means that all subsequent
2127 // |ScheduleUpdates()| should fail.
2128 EXPECT_FALSE(attempter_.ScheduleUpdates());
2129 EXPECT_FALSE(attempter_.ScheduleUpdates());
2130 EXPECT_FALSE(attempter_.ScheduleUpdates());
2131 }
2132
2133 // Critical tests to always make sure that an update is scheduled. The following
2134 // unittest(s) try and cover the correctness in synergy between
2135 // |UpdateAttempter| and |UpdateManager|. Also it is good to remember the
2136 // actions that happen in the flow when |UpdateAttempter| get callbacked on
2137 // |OnUpdateScheduled()| -> (various cases which leads to) -> |ProcessingDone()|
TestOnUpdateScheduled()2138 void UpdateAttempterTest::TestOnUpdateScheduled() {
2139 // Setup
2140 attempter_.SetWaitingForScheduledCheck(true);
2141 attempter_.DisableUpdate();
2142 attempter_.DisableScheduleUpdates();
2143
2144 // Invocation
2145 attempter_.OnUpdateScheduled(ous_params_.status, ous_params_.params);
2146
2147 // Verify
2148 EXPECT_EQ(ous_params_.exit_status, attempter_.status());
2149 EXPECT_EQ(ous_params_.should_schedule_updates_be_called,
2150 attempter_.WasScheduleUpdatesCalled());
2151 EXPECT_EQ(ous_params_.should_update_be_called, attempter_.WasUpdateCalled());
2152 }
2153
TEST_F(UpdateAttempterTest,OnUpdatesScheduledFailed)2154 TEST_F(UpdateAttempterTest, OnUpdatesScheduledFailed) {
2155 // GIVEN failed status.
2156
2157 // THEN update should be scheduled.
2158 ous_params_.should_schedule_updates_be_called = true;
2159
2160 TestOnUpdateScheduled();
2161 }
2162
TEST_F(UpdateAttempterTest,OnUpdatesScheduledAskMeAgainLater)2163 TEST_F(UpdateAttempterTest, OnUpdatesScheduledAskMeAgainLater) {
2164 // GIVEN ask me again later status.
2165 ous_params_.status = EvalStatus::kAskMeAgainLater;
2166
2167 // THEN update should be scheduled.
2168 ous_params_.should_schedule_updates_be_called = true;
2169
2170 TestOnUpdateScheduled();
2171 }
2172
TEST_F(UpdateAttempterTest,OnUpdatesScheduledContinue)2173 TEST_F(UpdateAttempterTest, OnUpdatesScheduledContinue) {
2174 // GIVEN continue status.
2175 ous_params_.status = EvalStatus::kContinue;
2176
2177 // THEN update should be scheduled.
2178 ous_params_.should_schedule_updates_be_called = true;
2179
2180 TestOnUpdateScheduled();
2181 }
2182
TEST_F(UpdateAttempterTest,OnUpdatesScheduledSucceededButUpdateDisabledFails)2183 TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceededButUpdateDisabledFails) {
2184 // GIVEN updates disabled.
2185 ous_params_.params = {.updates_enabled = false};
2186 // GIVEN succeeded status.
2187 ous_params_.status = EvalStatus::kSucceeded;
2188
2189 // THEN update should not be scheduled.
2190
2191 TestOnUpdateScheduled();
2192 }
2193
TEST_F(UpdateAttempterTest,OnUpdatesScheduledSucceeded)2194 TEST_F(UpdateAttempterTest, OnUpdatesScheduledSucceeded) {
2195 // GIVEN updates enabled.
2196 ous_params_.params = {.updates_enabled = true};
2197 // GIVEN succeeded status.
2198 ous_params_.status = EvalStatus::kSucceeded;
2199
2200 // THEN update should be called indicating status change.
2201 ous_params_.exit_status = UpdateStatus::CHECKING_FOR_UPDATE;
2202 ous_params_.should_update_be_called = true;
2203
2204 TestOnUpdateScheduled();
2205 }
2206
TEST_F(UpdateAttempterTest,IsEnterpriseRollbackInGetStatusDefault)2207 TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusDefault) {
2208 UpdateEngineStatus status;
2209 attempter_.GetStatus(&status);
2210 EXPECT_FALSE(status.is_enterprise_rollback);
2211 }
2212
TEST_F(UpdateAttempterTest,IsEnterpriseRollbackInGetStatusFalse)2213 TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusFalse) {
2214 attempter_.install_plan_.reset(new InstallPlan);
2215 attempter_.install_plan_->is_rollback = false;
2216
2217 UpdateEngineStatus status;
2218 attempter_.GetStatus(&status);
2219 EXPECT_FALSE(status.is_enterprise_rollback);
2220 }
2221
TEST_F(UpdateAttempterTest,IsEnterpriseRollbackInGetStatusTrue)2222 TEST_F(UpdateAttempterTest, IsEnterpriseRollbackInGetStatusTrue) {
2223 attempter_.install_plan_.reset(new InstallPlan);
2224 attempter_.install_plan_->is_rollback = true;
2225
2226 UpdateEngineStatus status;
2227 attempter_.GetStatus(&status);
2228 EXPECT_TRUE(status.is_enterprise_rollback);
2229 }
2230
TEST_F(UpdateAttempterTest,PowerwashInGetStatusDefault)2231 TEST_F(UpdateAttempterTest, PowerwashInGetStatusDefault) {
2232 UpdateEngineStatus status;
2233 attempter_.GetStatus(&status);
2234 EXPECT_FALSE(status.will_powerwash_after_reboot);
2235 }
2236
TEST_F(UpdateAttempterTest,PowerwashInGetStatusTrueBecausePowerwashRequired)2237 TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecausePowerwashRequired) {
2238 attempter_.install_plan_.reset(new InstallPlan);
2239 attempter_.install_plan_->powerwash_required = true;
2240
2241 UpdateEngineStatus status;
2242 attempter_.GetStatus(&status);
2243 EXPECT_TRUE(status.will_powerwash_after_reboot);
2244 }
2245
TEST_F(UpdateAttempterTest,PowerwashInGetStatusTrueBecauseRollback)2246 TEST_F(UpdateAttempterTest, PowerwashInGetStatusTrueBecauseRollback) {
2247 attempter_.install_plan_.reset(new InstallPlan);
2248 attempter_.install_plan_->is_rollback = true;
2249
2250 UpdateEngineStatus status;
2251 attempter_.GetStatus(&status);
2252 EXPECT_TRUE(status.will_powerwash_after_reboot);
2253 }
2254
TEST_F(UpdateAttempterTest,FutureEolTest)2255 TEST_F(UpdateAttempterTest, FutureEolTest) {
2256 EolDate eol_date = std::numeric_limits<int64_t>::max();
2257 EXPECT_TRUE(prefs_->SetString(kPrefsOmahaEolDate, EolDateToString(eol_date)));
2258 UpdateEngineStatus status;
2259 attempter_.GetStatus(&status);
2260 EXPECT_EQ(eol_date, status.eol_date);
2261 }
2262
TEST_F(UpdateAttempterTest,PastEolTest)2263 TEST_F(UpdateAttempterTest, PastEolTest) {
2264 EolDate eol_date = 1;
2265 EXPECT_TRUE(prefs_->SetString(kPrefsOmahaEolDate, EolDateToString(eol_date)));
2266 UpdateEngineStatus status;
2267 attempter_.GetStatus(&status);
2268 EXPECT_EQ(eol_date, status.eol_date);
2269 }
2270
TEST_F(UpdateAttempterTest,MissingEolTest)2271 TEST_F(UpdateAttempterTest, MissingEolTest) {
2272 UpdateEngineStatus status;
2273 attempter_.GetStatus(&status);
2274 EXPECT_EQ(kEolDateInvalid, status.eol_date);
2275 }
2276
TEST_F(UpdateAttempterTest,CalculateDlcParamsInstallTest)2277 TEST_F(UpdateAttempterTest, CalculateDlcParamsInstallTest) {
2278 string dlc_id = "dlc0";
2279 attempter_.is_install_ = true;
2280 attempter_.dlc_ids_ = {dlc_id};
2281 attempter_.CalculateDlcParams();
2282
2283 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
2284 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2285 OmahaRequestParams::AppParams dlc_app_params =
2286 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2287 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2288 EXPECT_EQ(false, dlc_app_params.send_ping);
2289 // When the DLC gets installed, a ping is not sent, therefore we don't store
2290 // the values sent by Omaha.
2291 auto last_active_key = PrefsInterface::CreateSubKey(
2292 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
2293 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2294 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2295 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
2296 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
2297 }
2298
TEST_F(UpdateAttempterTest,CalculateDlcParamsNoPrefFilesTest)2299 TEST_F(UpdateAttempterTest, CalculateDlcParamsNoPrefFilesTest) {
2300 string dlc_id = "dlc0";
2301 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
2302 .WillOnce(
2303 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2304
2305 attempter_.is_install_ = false;
2306 attempter_.CalculateDlcParams();
2307
2308 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
2309 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2310 OmahaRequestParams::AppParams dlc_app_params =
2311 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2312 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2313
2314 EXPECT_EQ(true, dlc_app_params.send_ping);
2315 EXPECT_EQ(0, dlc_app_params.ping_active);
2316 EXPECT_EQ(-1, dlc_app_params.ping_date_last_active);
2317 EXPECT_EQ(-1, dlc_app_params.ping_date_last_rollcall);
2318 }
2319
TEST_F(UpdateAttempterTest,CalculateDlcParamsNonParseableValuesTest)2320 TEST_F(UpdateAttempterTest, CalculateDlcParamsNonParseableValuesTest) {
2321 string dlc_id = "dlc0";
2322 MemoryPrefs prefs;
2323 FakeSystemState::Get()->set_prefs(&prefs);
2324 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
2325 .WillOnce(
2326 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2327
2328 // Write non numeric values in the metadata files.
2329 auto active_key =
2330 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
2331 auto last_active_key = PrefsInterface::CreateSubKey(
2332 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
2333 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2334 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
2335 FakeSystemState::Get()->prefs()->SetString(active_key, "z2yz");
2336 FakeSystemState::Get()->prefs()->SetString(last_active_key, "z2yz");
2337 FakeSystemState::Get()->prefs()->SetString(last_rollcall_key, "z2yz");
2338 attempter_.is_install_ = false;
2339 attempter_.CalculateDlcParams();
2340
2341 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
2342 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2343 OmahaRequestParams::AppParams dlc_app_params =
2344 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2345 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2346
2347 EXPECT_EQ(true, dlc_app_params.send_ping);
2348 EXPECT_EQ(0, dlc_app_params.ping_active);
2349 EXPECT_EQ(-2, dlc_app_params.ping_date_last_active);
2350 EXPECT_EQ(-2, dlc_app_params.ping_date_last_rollcall);
2351 }
2352
TEST_F(UpdateAttempterTest,CalculateDlcParamsValidValuesTest)2353 TEST_F(UpdateAttempterTest, CalculateDlcParamsValidValuesTest) {
2354 string dlc_id = "dlc0";
2355 EXPECT_CALL(mock_dlcservice_, GetDlcsToUpdate(_))
2356 .WillOnce(
2357 DoAll(SetArgPointee<0>(std::vector<string>({dlc_id})), Return(true)));
2358
2359 // Write numeric values in the metadata files.
2360 auto active_key =
2361 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
2362 auto last_active_key = PrefsInterface::CreateSubKey(
2363 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
2364 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2365 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
2366
2367 FakeSystemState::Get()->prefs()->SetInt64(active_key, 1);
2368 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 78);
2369 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 99);
2370 attempter_.is_install_ = false;
2371 attempter_.CalculateDlcParams();
2372
2373 OmahaRequestParams* params = FakeSystemState::Get()->request_params();
2374 EXPECT_EQ(1, params->dlc_apps_params().count(params->GetDlcAppId(dlc_id)));
2375 OmahaRequestParams::AppParams dlc_app_params =
2376 params->dlc_apps_params().at(params->GetDlcAppId(dlc_id));
2377 EXPECT_STREQ(dlc_id.c_str(), dlc_app_params.name.c_str());
2378
2379 EXPECT_EQ(true, dlc_app_params.send_ping);
2380 EXPECT_EQ(1, dlc_app_params.ping_active);
2381 EXPECT_EQ(78, dlc_app_params.ping_date_last_active);
2382 EXPECT_EQ(99, dlc_app_params.ping_date_last_rollcall);
2383 }
2384
TEST_F(UpdateAttempterTest,CalculateDlcParamsRemoveStaleMetadata)2385 TEST_F(UpdateAttempterTest, CalculateDlcParamsRemoveStaleMetadata) {
2386 string dlc_id = "dlc0";
2387 auto active_key =
2388 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
2389 auto last_active_key = PrefsInterface::CreateSubKey(
2390 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastActive});
2391 auto last_rollcall_key = PrefsInterface::CreateSubKey(
2392 {kDlcPrefsSubDir, dlc_id, kPrefsPingLastRollcall});
2393 FakeSystemState::Get()->prefs()->SetInt64(active_key, kPingInactiveValue);
2394 FakeSystemState::Get()->prefs()->SetInt64(last_active_key, 0);
2395 FakeSystemState::Get()->prefs()->SetInt64(last_rollcall_key, 0);
2396 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2397 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2398 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
2399
2400 attempter_.dlc_ids_ = {dlc_id};
2401 attempter_.is_install_ = true;
2402 attempter_.CalculateDlcParams();
2403
2404 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_active_key));
2405 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(last_rollcall_key));
2406 // Active key is set on install.
2407 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2408 int64_t temp_int;
2409 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
2410 EXPECT_EQ(temp_int, kPingActiveValue);
2411 }
2412
TEST_F(UpdateAttempterTest,SetDlcActiveValue)2413 TEST_F(UpdateAttempterTest, SetDlcActiveValue) {
2414 string dlc_id = "dlc0";
2415 attempter_.SetDlcActiveValue(true, dlc_id);
2416 int64_t temp_int;
2417 auto active_key =
2418 PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, kPrefsPingActive});
2419 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(active_key));
2420 EXPECT_TRUE(FakeSystemState::Get()->prefs()->GetInt64(active_key, &temp_int));
2421 EXPECT_EQ(temp_int, kPingActiveValue);
2422 }
2423
TEST_F(UpdateAttempterTest,SetDlcInactive)2424 TEST_F(UpdateAttempterTest, SetDlcInactive) {
2425 string dlc_id = "dlc0";
2426 auto sub_keys = {
2427 kPrefsPingActive, kPrefsPingLastActive, kPrefsPingLastRollcall};
2428 for (auto& sub_key : sub_keys) {
2429 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
2430 FakeSystemState::Get()->prefs()->SetInt64(key, 1);
2431 EXPECT_TRUE(FakeSystemState::Get()->prefs()->Exists(key));
2432 }
2433 attempter_.SetDlcActiveValue(false, dlc_id);
2434 for (auto& sub_key : sub_keys) {
2435 auto key = PrefsInterface::CreateSubKey({kDlcPrefsSubDir, dlc_id, sub_key});
2436 EXPECT_FALSE(FakeSystemState::Get()->prefs()->Exists(key));
2437 }
2438 }
2439
TEST_F(UpdateAttempterTest,GetSuccessfulDlcIds)2440 TEST_F(UpdateAttempterTest, GetSuccessfulDlcIds) {
2441 auto dlc_1 = "1", dlc_2 = "2", dlc_3 = "3";
2442 attempter_.omaha_request_params_->set_dlc_apps_params(
2443 {{dlc_1, {.name = dlc_1, .updated = false}},
2444 {dlc_2, {.name = dlc_2}},
2445 {dlc_3, {.name = dlc_3, .updated = false}}});
2446 EXPECT_THAT(attempter_.GetSuccessfulDlcIds(), ElementsAre(dlc_2));
2447 }
2448
TEST_F(UpdateAttempterTest,MoveToPrefs)2449 TEST_F(UpdateAttempterTest, MoveToPrefs) {
2450 string key1 = kPrefsLastActivePingDay;
2451 string key2 = kPrefsPingLastRollcall;
2452
2453 FakePrefs fake_prefs;
2454 EXPECT_TRUE(fake_prefs.SetString(key2, "current-rollcall"));
2455 FakeSystemState::Get()->set_prefs(&fake_prefs);
2456
2457 FakePrefs powerwash_safe_prefs;
2458 EXPECT_TRUE(powerwash_safe_prefs.SetString(key1, "powerwash-last-active"));
2459 EXPECT_TRUE(powerwash_safe_prefs.SetString(key2, "powerwash-last-rollcall"));
2460 FakeSystemState::Get()->set_powerwash_safe_prefs(&powerwash_safe_prefs);
2461
2462 attempter_.Init();
2463 attempter_.MoveToPrefs({key1, key2});
2464
2465 string pref_value_1;
2466 fake_prefs.GetString(key1, &pref_value_1);
2467 EXPECT_EQ(pref_value_1, "powerwash-last-active");
2468 // Do not overwrite if value already exists.
2469 string pref_value_2;
2470 fake_prefs.GetString(key2, &pref_value_2);
2471 EXPECT_EQ(pref_value_2, "current-rollcall");
2472
2473 // Make sure keys are deleted from powerwash safe prefs regardless of whether
2474 // they are written to prefs.
2475 EXPECT_FALSE(FakeSystemState::Get()->powerwash_safe_prefs()->Exists(key1));
2476 EXPECT_FALSE(FakeSystemState::Get()->powerwash_safe_prefs()->Exists(key2));
2477 }
2478
2479 } // namespace chromeos_update_engine
2480