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