update_attempter_unittest.cc 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  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. #include "update_engine/update_attempter.h"
  17. #include <stdint.h>
  18. #include <memory>
  19. #include <base/files/file_util.h>
  20. #include <base/message_loop/message_loop.h>
  21. #include <brillo/message_loops/base_message_loop.h>
  22. #include <brillo/message_loops/message_loop.h>
  23. #include <brillo/message_loops/message_loop_utils.h>
  24. #include <gtest/gtest.h>
  25. #include <policy/libpolicy.h>
  26. #include <policy/mock_device_policy.h>
  27. #include <policy/mock_libpolicy.h>
  28. #include "update_engine/common/dlcservice_interface.h"
  29. #include "update_engine/common/fake_clock.h"
  30. #include "update_engine/common/fake_prefs.h"
  31. #include "update_engine/common/mock_action.h"
  32. #include "update_engine/common/mock_action_processor.h"
  33. #include "update_engine/common/mock_http_fetcher.h"
  34. #include "update_engine/common/mock_prefs.h"
  35. #include "update_engine/common/platform_constants.h"
  36. #include "update_engine/common/prefs.h"
  37. #include "update_engine/common/test_utils.h"
  38. #include "update_engine/common/utils.h"
  39. #include "update_engine/fake_system_state.h"
  40. #include "update_engine/mock_p2p_manager.h"
  41. #include "update_engine/mock_payload_state.h"
  42. #include "update_engine/mock_service_observer.h"
  43. #include "update_engine/payload_consumer/filesystem_verifier_action.h"
  44. #include "update_engine/payload_consumer/install_plan.h"
  45. #include "update_engine/payload_consumer/payload_constants.h"
  46. #include "update_engine/payload_consumer/postinstall_runner_action.h"
  47. #include "update_engine/update_boot_flags_action.h"
  48. using base::Time;
  49. using base::TimeDelta;
  50. using chromeos_update_manager::EvalStatus;
  51. using chromeos_update_manager::StagingSchedule;
  52. using chromeos_update_manager::UpdateCheckParams;
  53. using policy::DevicePolicy;
  54. using std::string;
  55. using std::unique_ptr;
  56. using std::vector;
  57. using testing::_;
  58. using testing::DoAll;
  59. using testing::Field;
  60. using testing::InSequence;
  61. using testing::Ne;
  62. using testing::NiceMock;
  63. using testing::Pointee;
  64. using testing::Property;
  65. using testing::Return;
  66. using testing::ReturnPointee;
  67. using testing::ReturnRef;
  68. using testing::SaveArg;
  69. using testing::SetArgPointee;
  70. using update_engine::UpdateAttemptFlags;
  71. using update_engine::UpdateEngineStatus;
  72. using update_engine::UpdateStatus;
  73. namespace chromeos_update_engine {
  74. namespace {
  75. class MockDlcService : public DlcServiceInterface {
  76. public:
  77. MOCK_METHOD1(GetInstalled, bool(vector<string>*));
  78. };
  79. } // namespace
  80. const char kRollbackVersion[] = "10575.39.2";
  81. // Test a subclass rather than the main class directly so that we can mock out
  82. // methods within the class. There're explicit unit tests for the mocked out
  83. // methods.
  84. class UpdateAttempterUnderTest : public UpdateAttempter {
  85. public:
  86. explicit UpdateAttempterUnderTest(SystemState* system_state)
  87. : UpdateAttempter(system_state, nullptr) {}
  88. // Wrap the update scheduling method, allowing us to opt out of scheduled
  89. // updates for testing purposes.
  90. bool ScheduleUpdates() override {
  91. schedule_updates_called_ = true;
  92. if (do_schedule_updates_) {
  93. UpdateAttempter::ScheduleUpdates();
  94. } else {
  95. LOG(INFO) << "[TEST] Update scheduling disabled.";
  96. }
  97. return true;
  98. }
  99. void EnableScheduleUpdates() { do_schedule_updates_ = true; }
  100. void DisableScheduleUpdates() { do_schedule_updates_ = false; }
  101. // Indicates whether ScheduleUpdates() was called.
  102. bool schedule_updates_called() const { return schedule_updates_called_; }
  103. // Need to expose forced_omaha_url_ so we can test it.
  104. const string& forced_omaha_url() const { return forced_omaha_url_; }
  105. private:
  106. bool schedule_updates_called_ = false;
  107. bool do_schedule_updates_ = true;
  108. };
  109. class UpdateAttempterTest : public ::testing::Test {
  110. protected:
  111. UpdateAttempterTest()
  112. : certificate_checker_(fake_system_state_.mock_prefs(),
  113. &openssl_wrapper_) {
  114. // Override system state members.
  115. fake_system_state_.set_connection_manager(&mock_connection_manager);
  116. fake_system_state_.set_update_attempter(&attempter_);
  117. fake_system_state_.set_dlcservice(&mock_dlcservice_);
  118. loop_.SetAsCurrent();
  119. certificate_checker_.Init();
  120. attempter_.set_forced_update_pending_callback(
  121. new base::Callback<void(bool, bool)>(base::Bind([](bool, bool) {})));
  122. // Finish initializing the attempter.
  123. attempter_.Init();
  124. }
  125. void SetUp() override {
  126. EXPECT_NE(nullptr, attempter_.system_state_);
  127. EXPECT_EQ(0, attempter_.http_response_code_);
  128. EXPECT_EQ(UpdateStatus::IDLE, attempter_.status_);
  129. EXPECT_EQ(0.0, attempter_.download_progress_);
  130. EXPECT_EQ(0, attempter_.last_checked_time_);
  131. EXPECT_EQ("0.0.0.0", attempter_.new_version_);
  132. EXPECT_EQ(0ULL, attempter_.new_payload_size_);
  133. processor_ = new NiceMock<MockActionProcessor>();
  134. attempter_.processor_.reset(processor_); // Transfers ownership.
  135. prefs_ = fake_system_state_.mock_prefs();
  136. // Set up store/load semantics of P2P properties via the mock PayloadState.
  137. actual_using_p2p_for_downloading_ = false;
  138. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  139. SetUsingP2PForDownloading(_))
  140. .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_downloading_));
  141. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  142. GetUsingP2PForDownloading())
  143. .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_downloading_));
  144. actual_using_p2p_for_sharing_ = false;
  145. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  146. SetUsingP2PForSharing(_))
  147. .WillRepeatedly(SaveArg<0>(&actual_using_p2p_for_sharing_));
  148. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  149. GetUsingP2PForDownloading())
  150. .WillRepeatedly(ReturnPointee(&actual_using_p2p_for_sharing_));
  151. }
  152. public:
  153. void ScheduleQuitMainLoop();
  154. // Callbacks to run the different tests from the main loop.
  155. void UpdateTestStart();
  156. void UpdateTestVerify();
  157. void RollbackTestStart(bool enterprise_rollback, bool valid_slot);
  158. void RollbackTestVerify();
  159. void PingOmahaTestStart();
  160. void ReadScatterFactorFromPolicyTestStart();
  161. void DecrementUpdateCheckCountTestStart();
  162. void NoScatteringDoneDuringManualUpdateTestStart();
  163. void P2PNotEnabledStart();
  164. void P2PEnabledStart();
  165. void P2PEnabledInteractiveStart();
  166. void P2PEnabledStartingFailsStart();
  167. void P2PEnabledHousekeepingFailsStart();
  168. void ResetRollbackHappenedStart(bool is_consumer,
  169. bool is_policy_available,
  170. bool expected_reset);
  171. // Staging related callbacks.
  172. void SetUpStagingTest(const StagingSchedule& schedule, FakePrefs* prefs);
  173. void CheckStagingOff();
  174. void StagingSetsPrefsAndTurnsOffScatteringStart();
  175. void StagingOffIfInteractiveStart();
  176. void StagingOffIfOobeStart();
  177. bool actual_using_p2p_for_downloading() {
  178. return actual_using_p2p_for_downloading_;
  179. }
  180. bool actual_using_p2p_for_sharing() { return actual_using_p2p_for_sharing_; }
  181. base::MessageLoopForIO base_loop_;
  182. brillo::BaseMessageLoop loop_{&base_loop_};
  183. FakeSystemState fake_system_state_;
  184. UpdateAttempterUnderTest attempter_{&fake_system_state_};
  185. OpenSSLWrapper openssl_wrapper_;
  186. CertificateChecker certificate_checker_;
  187. MockDlcService mock_dlcservice_;
  188. NiceMock<MockActionProcessor>* processor_;
  189. NiceMock<MockPrefs>* prefs_; // Shortcut to fake_system_state_->mock_prefs().
  190. NiceMock<MockConnectionManager> mock_connection_manager;
  191. bool actual_using_p2p_for_downloading_;
  192. bool actual_using_p2p_for_sharing_;
  193. };
  194. void UpdateAttempterTest::ScheduleQuitMainLoop() {
  195. loop_.PostTask(
  196. FROM_HERE,
  197. base::Bind([](brillo::BaseMessageLoop* loop) { loop->BreakLoop(); },
  198. base::Unretained(&loop_)));
  199. }
  200. TEST_F(UpdateAttempterTest, ActionCompletedDownloadTest) {
  201. unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
  202. fetcher->FailTransfer(503); // Sets the HTTP response code.
  203. DownloadAction action(prefs_,
  204. nullptr,
  205. nullptr,
  206. nullptr,
  207. fetcher.release(),
  208. false /* interactive */);
  209. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
  210. attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
  211. EXPECT_EQ(UpdateStatus::FINALIZING, attempter_.status());
  212. EXPECT_EQ(0.0, attempter_.download_progress_);
  213. ASSERT_EQ(nullptr, attempter_.error_event_.get());
  214. }
  215. TEST_F(UpdateAttempterTest, ActionCompletedErrorTest) {
  216. MockAction action;
  217. EXPECT_CALL(action, Type()).WillRepeatedly(Return("MockAction"));
  218. attempter_.status_ = UpdateStatus::DOWNLOADING;
  219. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
  220. .WillOnce(Return(false));
  221. attempter_.ActionCompleted(nullptr, &action, ErrorCode::kError);
  222. ASSERT_NE(nullptr, attempter_.error_event_.get());
  223. }
  224. TEST_F(UpdateAttempterTest, DownloadProgressAccumulationTest) {
  225. // Simple test case, where all the values match (nothing was skipped)
  226. uint64_t bytes_progressed_1 = 1024 * 1024; // 1MB
  227. uint64_t bytes_progressed_2 = 1024 * 1024; // 1MB
  228. uint64_t bytes_received_1 = bytes_progressed_1;
  229. uint64_t bytes_received_2 = bytes_received_1 + bytes_progressed_2;
  230. uint64_t bytes_total = 20 * 1024 * 1024; // 20MB
  231. double progress_1 =
  232. static_cast<double>(bytes_received_1) / static_cast<double>(bytes_total);
  233. double progress_2 =
  234. static_cast<double>(bytes_received_2) / static_cast<double>(bytes_total);
  235. EXPECT_EQ(0.0, attempter_.download_progress_);
  236. // This is set via inspecting the InstallPlan payloads when the
  237. // OmahaResponseAction is completed
  238. attempter_.new_payload_size_ = bytes_total;
  239. NiceMock<MockServiceObserver> observer;
  240. EXPECT_CALL(observer,
  241. SendStatusUpdate(AllOf(
  242. Field(&UpdateEngineStatus::progress, progress_1),
  243. Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
  244. Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
  245. EXPECT_CALL(observer,
  246. SendStatusUpdate(AllOf(
  247. Field(&UpdateEngineStatus::progress, progress_2),
  248. Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
  249. Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
  250. attempter_.AddObserver(&observer);
  251. attempter_.BytesReceived(bytes_progressed_1, bytes_received_1, bytes_total);
  252. EXPECT_EQ(progress_1, attempter_.download_progress_);
  253. // This iteration validates that a later set of updates to the variables are
  254. // properly handled (so that |getStatus()| will return the same progress info
  255. // as the callback is receiving.
  256. attempter_.BytesReceived(bytes_progressed_2, bytes_received_2, bytes_total);
  257. EXPECT_EQ(progress_2, attempter_.download_progress_);
  258. }
  259. TEST_F(UpdateAttempterTest, ChangeToDownloadingOnReceivedBytesTest) {
  260. // The transition into UpdateStatus::DOWNLOADING happens when the
  261. // first bytes are received.
  262. uint64_t bytes_progressed = 1024 * 1024; // 1MB
  263. uint64_t bytes_received = 2 * 1024 * 1024; // 2MB
  264. uint64_t bytes_total = 20 * 1024 * 1024; // 300MB
  265. attempter_.status_ = UpdateStatus::CHECKING_FOR_UPDATE;
  266. // This is set via inspecting the InstallPlan payloads when the
  267. // OmahaResponseAction is completed
  268. attempter_.new_payload_size_ = bytes_total;
  269. EXPECT_EQ(0.0, attempter_.download_progress_);
  270. NiceMock<MockServiceObserver> observer;
  271. EXPECT_CALL(observer,
  272. SendStatusUpdate(AllOf(
  273. Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
  274. Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
  275. attempter_.AddObserver(&observer);
  276. attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
  277. EXPECT_EQ(UpdateStatus::DOWNLOADING, attempter_.status_);
  278. }
  279. TEST_F(UpdateAttempterTest, BroadcastCompleteDownloadTest) {
  280. // There is a special case to ensure that at 100% downloaded,
  281. // download_progress_ is updated and that value broadcast. This test confirms
  282. // that.
  283. uint64_t bytes_progressed = 0; // ignored
  284. uint64_t bytes_received = 5 * 1024 * 1024; // ignored
  285. uint64_t bytes_total = 5 * 1024 * 1024; // 300MB
  286. attempter_.status_ = UpdateStatus::DOWNLOADING;
  287. attempter_.new_payload_size_ = bytes_total;
  288. EXPECT_EQ(0.0, attempter_.download_progress_);
  289. NiceMock<MockServiceObserver> observer;
  290. EXPECT_CALL(observer,
  291. SendStatusUpdate(AllOf(
  292. Field(&UpdateEngineStatus::progress, 1.0),
  293. Field(&UpdateEngineStatus::status, UpdateStatus::DOWNLOADING),
  294. Field(&UpdateEngineStatus::new_size_bytes, bytes_total))));
  295. attempter_.AddObserver(&observer);
  296. attempter_.BytesReceived(bytes_progressed, bytes_received, bytes_total);
  297. EXPECT_EQ(1.0, attempter_.download_progress_);
  298. }
  299. TEST_F(UpdateAttempterTest, ActionCompletedOmahaRequestTest) {
  300. unique_ptr<MockHttpFetcher> fetcher(new MockHttpFetcher("", 0, nullptr));
  301. fetcher->FailTransfer(500); // Sets the HTTP response code.
  302. OmahaRequestAction action(
  303. &fake_system_state_, nullptr, std::move(fetcher), false);
  304. ObjectCollectorAction<OmahaResponse> collector_action;
  305. BondActions(&action, &collector_action);
  306. OmahaResponse response;
  307. response.poll_interval = 234;
  308. action.SetOutputObject(response);
  309. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _)).Times(0);
  310. attempter_.ActionCompleted(nullptr, &action, ErrorCode::kSuccess);
  311. EXPECT_EQ(500, attempter_.http_response_code());
  312. EXPECT_EQ(UpdateStatus::IDLE, attempter_.status());
  313. EXPECT_EQ(234U, attempter_.server_dictated_poll_interval_);
  314. ASSERT_TRUE(attempter_.error_event_.get() == nullptr);
  315. }
  316. TEST_F(UpdateAttempterTest, ConstructWithUpdatedMarkerTest) {
  317. FakePrefs fake_prefs;
  318. string boot_id;
  319. EXPECT_TRUE(utils::GetBootId(&boot_id));
  320. fake_prefs.SetString(kPrefsUpdateCompletedOnBootId, boot_id);
  321. fake_system_state_.set_prefs(&fake_prefs);
  322. attempter_.Init();
  323. EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
  324. }
  325. TEST_F(UpdateAttempterTest, GetErrorCodeForActionTest) {
  326. EXPECT_EQ(ErrorCode::kSuccess,
  327. GetErrorCodeForAction(nullptr, ErrorCode::kSuccess));
  328. FakeSystemState fake_system_state;
  329. OmahaRequestAction omaha_request_action(
  330. &fake_system_state, nullptr, nullptr, false);
  331. EXPECT_EQ(ErrorCode::kOmahaRequestError,
  332. GetErrorCodeForAction(&omaha_request_action, ErrorCode::kError));
  333. OmahaResponseHandlerAction omaha_response_handler_action(&fake_system_state_);
  334. EXPECT_EQ(
  335. ErrorCode::kOmahaResponseHandlerError,
  336. GetErrorCodeForAction(&omaha_response_handler_action, ErrorCode::kError));
  337. FilesystemVerifierAction filesystem_verifier_action;
  338. EXPECT_EQ(
  339. ErrorCode::kFilesystemVerifierError,
  340. GetErrorCodeForAction(&filesystem_verifier_action, ErrorCode::kError));
  341. PostinstallRunnerAction postinstall_runner_action(
  342. fake_system_state.fake_boot_control(), fake_system_state.fake_hardware());
  343. EXPECT_EQ(
  344. ErrorCode::kPostinstallRunnerError,
  345. GetErrorCodeForAction(&postinstall_runner_action, ErrorCode::kError));
  346. MockAction action_mock;
  347. EXPECT_CALL(action_mock, Type()).WillOnce(Return("MockAction"));
  348. EXPECT_EQ(ErrorCode::kError,
  349. GetErrorCodeForAction(&action_mock, ErrorCode::kError));
  350. }
  351. TEST_F(UpdateAttempterTest, DisableDeltaUpdateIfNeededTest) {
  352. attempter_.omaha_request_params_->set_delta_okay(true);
  353. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
  354. .WillOnce(Return(false));
  355. attempter_.DisableDeltaUpdateIfNeeded();
  356. EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
  357. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
  358. .WillOnce(
  359. DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures - 1),
  360. Return(true)));
  361. attempter_.DisableDeltaUpdateIfNeeded();
  362. EXPECT_TRUE(attempter_.omaha_request_params_->delta_okay());
  363. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
  364. .WillOnce(
  365. DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
  366. Return(true)));
  367. attempter_.DisableDeltaUpdateIfNeeded();
  368. EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
  369. EXPECT_CALL(*prefs_, GetInt64(_, _)).Times(0);
  370. attempter_.DisableDeltaUpdateIfNeeded();
  371. EXPECT_FALSE(attempter_.omaha_request_params_->delta_okay());
  372. }
  373. TEST_F(UpdateAttempterTest, MarkDeltaUpdateFailureTest) {
  374. EXPECT_CALL(*prefs_, GetInt64(kPrefsDeltaUpdateFailures, _))
  375. .WillOnce(Return(false))
  376. .WillOnce(DoAll(SetArgPointee<1>(-1), Return(true)))
  377. .WillOnce(DoAll(SetArgPointee<1>(1), Return(true)))
  378. .WillOnce(
  379. DoAll(SetArgPointee<1>(UpdateAttempter::kMaxDeltaUpdateFailures),
  380. Return(true)));
  381. EXPECT_CALL(*prefs_, SetInt64(Ne(kPrefsDeltaUpdateFailures), _))
  382. .WillRepeatedly(Return(true));
  383. EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 1)).Times(2);
  384. EXPECT_CALL(*prefs_, SetInt64(kPrefsDeltaUpdateFailures, 2));
  385. EXPECT_CALL(*prefs_,
  386. SetInt64(kPrefsDeltaUpdateFailures,
  387. UpdateAttempter::kMaxDeltaUpdateFailures + 1));
  388. for (int i = 0; i < 4; i++)
  389. attempter_.MarkDeltaUpdateFailure();
  390. }
  391. TEST_F(UpdateAttempterTest, ScheduleErrorEventActionNoEventTest) {
  392. EXPECT_CALL(*processor_, EnqueueAction(_)).Times(0);
  393. EXPECT_CALL(*processor_, StartProcessing()).Times(0);
  394. EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(_))
  395. .Times(0);
  396. OmahaResponse response;
  397. string url1 = "http://url1";
  398. response.packages.push_back({.payload_urls = {url1, "https://url"}});
  399. EXPECT_CALL(*(fake_system_state_.mock_payload_state()), GetCurrentUrl())
  400. .WillRepeatedly(Return(url1));
  401. fake_system_state_.mock_payload_state()->SetResponse(response);
  402. attempter_.ScheduleErrorEventAction();
  403. EXPECT_EQ(url1, fake_system_state_.mock_payload_state()->GetCurrentUrl());
  404. }
  405. TEST_F(UpdateAttempterTest, ScheduleErrorEventActionTest) {
  406. EXPECT_CALL(*processor_,
  407. EnqueueAction(Pointee(Property(
  408. &AbstractAction::Type, OmahaRequestAction::StaticType()))));
  409. EXPECT_CALL(*processor_, StartProcessing());
  410. ErrorCode err = ErrorCode::kError;
  411. EXPECT_CALL(*fake_system_state_.mock_payload_state(), UpdateFailed(err));
  412. attempter_.error_event_.reset(new OmahaEvent(
  413. OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, err));
  414. attempter_.ScheduleErrorEventAction();
  415. EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, attempter_.status());
  416. }
  417. namespace {
  418. // Actions that will be built as part of an update check.
  419. const string kUpdateActionTypes[] = { // NOLINT(runtime/string)
  420. OmahaRequestAction::StaticType(),
  421. OmahaResponseHandlerAction::StaticType(),
  422. UpdateBootFlagsAction::StaticType(),
  423. OmahaRequestAction::StaticType(),
  424. DownloadAction::StaticType(),
  425. OmahaRequestAction::StaticType(),
  426. FilesystemVerifierAction::StaticType(),
  427. PostinstallRunnerAction::StaticType(),
  428. OmahaRequestAction::StaticType()};
  429. // Actions that will be built as part of a user-initiated rollback.
  430. const string kRollbackActionTypes[] = {
  431. // NOLINT(runtime/string)
  432. InstallPlanAction::StaticType(),
  433. PostinstallRunnerAction::StaticType(),
  434. };
  435. const StagingSchedule kValidStagingSchedule = {
  436. {4, 10}, {10, 40}, {19, 70}, {26, 100}};
  437. } // namespace
  438. void UpdateAttempterTest::UpdateTestStart() {
  439. attempter_.set_http_response_code(200);
  440. // Expect that the device policy is loaded by the UpdateAttempter at some
  441. // point by calling RefreshDevicePolicy.
  442. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  443. EXPECT_CALL(*device_policy, LoadPolicy())
  444. .Times(testing::AtLeast(1))
  445. .WillRepeatedly(Return(true));
  446. attempter_.policy_provider_.reset(
  447. new policy::PolicyProvider(std::move(device_policy)));
  448. {
  449. InSequence s;
  450. for (size_t i = 0; i < arraysize(kUpdateActionTypes); ++i) {
  451. EXPECT_CALL(*processor_,
  452. EnqueueAction(Pointee(
  453. Property(&AbstractAction::Type, kUpdateActionTypes[i]))));
  454. }
  455. EXPECT_CALL(*processor_, StartProcessing());
  456. }
  457. attempter_.Update("", "", "", "", false, false, false);
  458. loop_.PostTask(FROM_HERE,
  459. base::Bind(&UpdateAttempterTest::UpdateTestVerify,
  460. base::Unretained(this)));
  461. }
  462. void UpdateAttempterTest::UpdateTestVerify() {
  463. EXPECT_EQ(0, attempter_.http_response_code());
  464. EXPECT_EQ(&attempter_, processor_->delegate());
  465. EXPECT_EQ(UpdateStatus::CHECKING_FOR_UPDATE, attempter_.status());
  466. loop_.BreakLoop();
  467. }
  468. void UpdateAttempterTest::RollbackTestStart(bool enterprise_rollback,
  469. bool valid_slot) {
  470. // Create a device policy so that we can change settings.
  471. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  472. EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
  473. fake_system_state_.set_device_policy(device_policy.get());
  474. if (enterprise_rollback) {
  475. // We return an empty owner as this is an enterprise.
  476. EXPECT_CALL(*device_policy, GetOwner(_))
  477. .WillRepeatedly(DoAll(SetArgPointee<0>(string("")), Return(true)));
  478. } else {
  479. // We return a fake owner as this is an owned consumer device.
  480. EXPECT_CALL(*device_policy, GetOwner(_))
  481. .WillRepeatedly(DoAll(SetArgPointee<0>(string("[email protected]")),
  482. Return(true)));
  483. }
  484. attempter_.policy_provider_.reset(
  485. new policy::PolicyProvider(std::move(device_policy)));
  486. if (valid_slot) {
  487. BootControlInterface::Slot rollback_slot = 1;
  488. LOG(INFO) << "Test Mark Bootable: "
  489. << BootControlInterface::SlotName(rollback_slot);
  490. fake_system_state_.fake_boot_control()->SetSlotBootable(rollback_slot,
  491. true);
  492. }
  493. bool is_rollback_allowed = false;
  494. // We only allow rollback on devices that are not enterprise enrolled and
  495. // which have a valid slot to rollback to.
  496. if (!enterprise_rollback && valid_slot) {
  497. is_rollback_allowed = true;
  498. }
  499. if (is_rollback_allowed) {
  500. InSequence s;
  501. for (size_t i = 0; i < arraysize(kRollbackActionTypes); ++i) {
  502. EXPECT_CALL(*processor_,
  503. EnqueueAction(Pointee(Property(&AbstractAction::Type,
  504. kRollbackActionTypes[i]))));
  505. }
  506. EXPECT_CALL(*processor_, StartProcessing());
  507. EXPECT_TRUE(attempter_.Rollback(true));
  508. loop_.PostTask(FROM_HERE,
  509. base::Bind(&UpdateAttempterTest::RollbackTestVerify,
  510. base::Unretained(this)));
  511. } else {
  512. EXPECT_FALSE(attempter_.Rollback(true));
  513. loop_.BreakLoop();
  514. }
  515. }
  516. void UpdateAttempterTest::RollbackTestVerify() {
  517. // Verifies the actions that were enqueued.
  518. EXPECT_EQ(&attempter_, processor_->delegate());
  519. EXPECT_EQ(UpdateStatus::ATTEMPTING_ROLLBACK, attempter_.status());
  520. EXPECT_EQ(0U, attempter_.install_plan_->partitions.size());
  521. EXPECT_EQ(attempter_.install_plan_->powerwash_required, true);
  522. loop_.BreakLoop();
  523. }
  524. TEST_F(UpdateAttempterTest, UpdateTest) {
  525. UpdateTestStart();
  526. loop_.Run();
  527. }
  528. TEST_F(UpdateAttempterTest, RollbackTest) {
  529. loop_.PostTask(FROM_HERE,
  530. base::Bind(&UpdateAttempterTest::RollbackTestStart,
  531. base::Unretained(this),
  532. false,
  533. true));
  534. loop_.Run();
  535. }
  536. TEST_F(UpdateAttempterTest, InvalidSlotRollbackTest) {
  537. loop_.PostTask(FROM_HERE,
  538. base::Bind(&UpdateAttempterTest::RollbackTestStart,
  539. base::Unretained(this),
  540. false,
  541. false));
  542. loop_.Run();
  543. }
  544. TEST_F(UpdateAttempterTest, EnterpriseRollbackTest) {
  545. loop_.PostTask(FROM_HERE,
  546. base::Bind(&UpdateAttempterTest::RollbackTestStart,
  547. base::Unretained(this),
  548. true,
  549. true));
  550. loop_.Run();
  551. }
  552. void UpdateAttempterTest::PingOmahaTestStart() {
  553. EXPECT_CALL(*processor_,
  554. EnqueueAction(Pointee(Property(
  555. &AbstractAction::Type, OmahaRequestAction::StaticType()))));
  556. EXPECT_CALL(*processor_, StartProcessing());
  557. attempter_.PingOmaha();
  558. ScheduleQuitMainLoop();
  559. }
  560. TEST_F(UpdateAttempterTest, PingOmahaTest) {
  561. EXPECT_FALSE(attempter_.waiting_for_scheduled_check_);
  562. EXPECT_FALSE(attempter_.schedule_updates_called());
  563. // Disable scheduling of subsequnet checks; we're using the DefaultPolicy in
  564. // testing, which is more permissive than we want to handle here.
  565. attempter_.DisableScheduleUpdates();
  566. loop_.PostTask(FROM_HERE,
  567. base::Bind(&UpdateAttempterTest::PingOmahaTestStart,
  568. base::Unretained(this)));
  569. brillo::MessageLoopRunMaxIterations(&loop_, 100);
  570. EXPECT_EQ(UpdateStatus::UPDATED_NEED_REBOOT, attempter_.status());
  571. EXPECT_TRUE(attempter_.schedule_updates_called());
  572. }
  573. TEST_F(UpdateAttempterTest, CreatePendingErrorEventTest) {
  574. MockAction action;
  575. const ErrorCode kCode = ErrorCode::kDownloadTransferError;
  576. attempter_.CreatePendingErrorEvent(&action, kCode);
  577. ASSERT_NE(nullptr, attempter_.error_event_.get());
  578. EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
  579. EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
  580. EXPECT_EQ(
  581. static_cast<ErrorCode>(static_cast<int>(kCode) |
  582. static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
  583. attempter_.error_event_->error_code);
  584. }
  585. TEST_F(UpdateAttempterTest, CreatePendingErrorEventResumedTest) {
  586. attempter_.install_plan_.reset(new InstallPlan);
  587. attempter_.install_plan_->is_resume = true;
  588. MockAction action;
  589. const ErrorCode kCode = ErrorCode::kInstallDeviceOpenError;
  590. attempter_.CreatePendingErrorEvent(&action, kCode);
  591. ASSERT_NE(nullptr, attempter_.error_event_.get());
  592. EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
  593. EXPECT_EQ(OmahaEvent::kResultError, attempter_.error_event_->result);
  594. EXPECT_EQ(
  595. static_cast<ErrorCode>(static_cast<int>(kCode) |
  596. static_cast<int>(ErrorCode::kResumedFlag) |
  597. static_cast<int>(ErrorCode::kTestOmahaUrlFlag)),
  598. attempter_.error_event_->error_code);
  599. }
  600. TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenNotEnabled) {
  601. MockP2PManager mock_p2p_manager;
  602. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  603. mock_p2p_manager.fake().SetP2PEnabled(false);
  604. EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
  605. attempter_.UpdateEngineStarted();
  606. }
  607. TEST_F(UpdateAttempterTest, P2PNotStartedAtStartupWhenEnabledButNotSharing) {
  608. MockP2PManager mock_p2p_manager;
  609. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  610. mock_p2p_manager.fake().SetP2PEnabled(true);
  611. EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning()).Times(0);
  612. attempter_.UpdateEngineStarted();
  613. }
  614. TEST_F(UpdateAttempterTest, P2PStartedAtStartupWhenEnabledAndSharing) {
  615. MockP2PManager mock_p2p_manager;
  616. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  617. mock_p2p_manager.fake().SetP2PEnabled(true);
  618. mock_p2p_manager.fake().SetCountSharedFilesResult(1);
  619. EXPECT_CALL(mock_p2p_manager, EnsureP2PRunning());
  620. attempter_.UpdateEngineStarted();
  621. }
  622. TEST_F(UpdateAttempterTest, P2PNotEnabled) {
  623. loop_.PostTask(FROM_HERE,
  624. base::Bind(&UpdateAttempterTest::P2PNotEnabledStart,
  625. base::Unretained(this)));
  626. loop_.Run();
  627. }
  628. void UpdateAttempterTest::P2PNotEnabledStart() {
  629. // If P2P is not enabled, check that we do not attempt housekeeping
  630. // and do not convey that p2p is to be used.
  631. MockP2PManager mock_p2p_manager;
  632. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  633. mock_p2p_manager.fake().SetP2PEnabled(false);
  634. EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
  635. attempter_.Update("", "", "", "", false, false, false);
  636. EXPECT_FALSE(actual_using_p2p_for_downloading_);
  637. EXPECT_FALSE(actual_using_p2p_for_sharing());
  638. ScheduleQuitMainLoop();
  639. }
  640. TEST_F(UpdateAttempterTest, P2PEnabledStartingFails) {
  641. loop_.PostTask(FROM_HERE,
  642. base::Bind(&UpdateAttempterTest::P2PEnabledStartingFailsStart,
  643. base::Unretained(this)));
  644. loop_.Run();
  645. }
  646. void UpdateAttempterTest::P2PEnabledStartingFailsStart() {
  647. // If p2p is enabled, but starting it fails ensure we don't do
  648. // any housekeeping and do not convey that p2p should be used.
  649. MockP2PManager mock_p2p_manager;
  650. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  651. mock_p2p_manager.fake().SetP2PEnabled(true);
  652. mock_p2p_manager.fake().SetEnsureP2PRunningResult(false);
  653. mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
  654. EXPECT_CALL(mock_p2p_manager, PerformHousekeeping()).Times(0);
  655. attempter_.Update("", "", "", "", false, false, false);
  656. EXPECT_FALSE(actual_using_p2p_for_downloading());
  657. EXPECT_FALSE(actual_using_p2p_for_sharing());
  658. ScheduleQuitMainLoop();
  659. }
  660. TEST_F(UpdateAttempterTest, P2PEnabledHousekeepingFails) {
  661. loop_.PostTask(
  662. FROM_HERE,
  663. base::Bind(&UpdateAttempterTest::P2PEnabledHousekeepingFailsStart,
  664. base::Unretained(this)));
  665. loop_.Run();
  666. }
  667. void UpdateAttempterTest::P2PEnabledHousekeepingFailsStart() {
  668. // If p2p is enabled, starting it works but housekeeping fails, ensure
  669. // we do not convey p2p is to be used.
  670. MockP2PManager mock_p2p_manager;
  671. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  672. mock_p2p_manager.fake().SetP2PEnabled(true);
  673. mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
  674. mock_p2p_manager.fake().SetPerformHousekeepingResult(false);
  675. EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
  676. attempter_.Update("", "", "", "", false, false, false);
  677. EXPECT_FALSE(actual_using_p2p_for_downloading());
  678. EXPECT_FALSE(actual_using_p2p_for_sharing());
  679. ScheduleQuitMainLoop();
  680. }
  681. TEST_F(UpdateAttempterTest, P2PEnabled) {
  682. loop_.PostTask(FROM_HERE,
  683. base::Bind(&UpdateAttempterTest::P2PEnabledStart,
  684. base::Unretained(this)));
  685. loop_.Run();
  686. }
  687. void UpdateAttempterTest::P2PEnabledStart() {
  688. MockP2PManager mock_p2p_manager;
  689. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  690. // If P2P is enabled and starting it works, check that we performed
  691. // housekeeping and that we convey p2p should be used.
  692. mock_p2p_manager.fake().SetP2PEnabled(true);
  693. mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
  694. mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
  695. EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
  696. attempter_.Update("", "", "", "", false, false, false);
  697. EXPECT_TRUE(actual_using_p2p_for_downloading());
  698. EXPECT_TRUE(actual_using_p2p_for_sharing());
  699. ScheduleQuitMainLoop();
  700. }
  701. TEST_F(UpdateAttempterTest, P2PEnabledInteractive) {
  702. loop_.PostTask(FROM_HERE,
  703. base::Bind(&UpdateAttempterTest::P2PEnabledInteractiveStart,
  704. base::Unretained(this)));
  705. loop_.Run();
  706. }
  707. void UpdateAttempterTest::P2PEnabledInteractiveStart() {
  708. MockP2PManager mock_p2p_manager;
  709. fake_system_state_.set_p2p_manager(&mock_p2p_manager);
  710. // For an interactive check, if P2P is enabled and starting it
  711. // works, check that we performed housekeeping and that we convey
  712. // p2p should be used for sharing but NOT for downloading.
  713. mock_p2p_manager.fake().SetP2PEnabled(true);
  714. mock_p2p_manager.fake().SetEnsureP2PRunningResult(true);
  715. mock_p2p_manager.fake().SetPerformHousekeepingResult(true);
  716. EXPECT_CALL(mock_p2p_manager, PerformHousekeeping());
  717. attempter_.Update("",
  718. "",
  719. "",
  720. "",
  721. false,
  722. false,
  723. /*interactive=*/true);
  724. EXPECT_FALSE(actual_using_p2p_for_downloading());
  725. EXPECT_TRUE(actual_using_p2p_for_sharing());
  726. ScheduleQuitMainLoop();
  727. }
  728. TEST_F(UpdateAttempterTest, ReadScatterFactorFromPolicy) {
  729. loop_.PostTask(
  730. FROM_HERE,
  731. base::Bind(&UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart,
  732. base::Unretained(this)));
  733. loop_.Run();
  734. }
  735. // Tests that the scatter_factor_in_seconds value is properly fetched
  736. // from the device policy.
  737. void UpdateAttempterTest::ReadScatterFactorFromPolicyTestStart() {
  738. int64_t scatter_factor_in_seconds = 36000;
  739. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  740. EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
  741. fake_system_state_.set_device_policy(device_policy.get());
  742. EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
  743. .WillRepeatedly(
  744. DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
  745. attempter_.policy_provider_.reset(
  746. new policy::PolicyProvider(std::move(device_policy)));
  747. attempter_.Update("", "", "", "", false, false, false);
  748. EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
  749. ScheduleQuitMainLoop();
  750. }
  751. TEST_F(UpdateAttempterTest, DecrementUpdateCheckCountTest) {
  752. loop_.PostTask(
  753. FROM_HERE,
  754. base::Bind(&UpdateAttempterTest::DecrementUpdateCheckCountTestStart,
  755. base::Unretained(this)));
  756. loop_.Run();
  757. }
  758. void UpdateAttempterTest::DecrementUpdateCheckCountTestStart() {
  759. // Tests that the scatter_factor_in_seconds value is properly fetched
  760. // from the device policy and is decremented if value > 0.
  761. int64_t initial_value = 5;
  762. FakePrefs fake_prefs;
  763. attempter_.prefs_ = &fake_prefs;
  764. fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
  765. EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
  766. int64_t scatter_factor_in_seconds = 10;
  767. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  768. EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
  769. fake_system_state_.set_device_policy(device_policy.get());
  770. EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
  771. .WillRepeatedly(
  772. DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
  773. attempter_.policy_provider_.reset(
  774. new policy::PolicyProvider(std::move(device_policy)));
  775. attempter_.Update("", "", "", "", false, false, false);
  776. EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
  777. // Make sure the file still exists.
  778. EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
  779. int64_t new_value;
  780. EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
  781. EXPECT_EQ(initial_value - 1, new_value);
  782. EXPECT_TRUE(
  783. attempter_.omaha_request_params_->update_check_count_wait_enabled());
  784. // However, if the count is already 0, it's not decremented. Test that.
  785. initial_value = 0;
  786. EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
  787. attempter_.Update("", "", "", "", false, false, false);
  788. EXPECT_TRUE(fake_prefs.Exists(kPrefsUpdateCheckCount));
  789. EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &new_value));
  790. EXPECT_EQ(initial_value, new_value);
  791. ScheduleQuitMainLoop();
  792. }
  793. TEST_F(UpdateAttempterTest, NoScatteringDoneDuringManualUpdateTestStart) {
  794. loop_.PostTask(
  795. FROM_HERE,
  796. base::Bind(
  797. &UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart,
  798. base::Unretained(this)));
  799. loop_.Run();
  800. }
  801. void UpdateAttempterTest::NoScatteringDoneDuringManualUpdateTestStart() {
  802. // Tests that no scattering logic is enabled if the update check
  803. // is manually done (as opposed to a scheduled update check)
  804. int64_t initial_value = 8;
  805. FakePrefs fake_prefs;
  806. attempter_.prefs_ = &fake_prefs;
  807. fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
  808. fake_system_state_.set_prefs(&fake_prefs);
  809. EXPECT_TRUE(
  810. fake_prefs.SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
  811. EXPECT_TRUE(fake_prefs.SetInt64(kPrefsUpdateCheckCount, initial_value));
  812. // make sure scatter_factor is non-zero as scattering is disabled
  813. // otherwise.
  814. int64_t scatter_factor_in_seconds = 50;
  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. EXPECT_CALL(*device_policy, GetScatterFactorInSeconds(_))
  819. .WillRepeatedly(
  820. DoAll(SetArgPointee<0>(scatter_factor_in_seconds), Return(true)));
  821. attempter_.policy_provider_.reset(
  822. new policy::PolicyProvider(std::move(device_policy)));
  823. // Trigger an interactive check so we can test that scattering is disabled.
  824. attempter_.Update("",
  825. "",
  826. "",
  827. "",
  828. false,
  829. false,
  830. /*interactive=*/true);
  831. EXPECT_EQ(scatter_factor_in_seconds, attempter_.scatter_factor_.InSeconds());
  832. // Make sure scattering is disabled for manual (i.e. user initiated) update
  833. // checks and all artifacts are removed.
  834. EXPECT_FALSE(
  835. attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
  836. EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
  837. EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InSeconds());
  838. EXPECT_FALSE(
  839. attempter_.omaha_request_params_->update_check_count_wait_enabled());
  840. EXPECT_FALSE(fake_prefs.Exists(kPrefsUpdateCheckCount));
  841. ScheduleQuitMainLoop();
  842. }
  843. void UpdateAttempterTest::SetUpStagingTest(const StagingSchedule& schedule,
  844. FakePrefs* prefs) {
  845. attempter_.prefs_ = prefs;
  846. fake_system_state_.set_prefs(prefs);
  847. int64_t initial_value = 8;
  848. EXPECT_TRUE(
  849. prefs->SetInt64(kPrefsWallClockScatteringWaitPeriod, initial_value));
  850. EXPECT_TRUE(prefs->SetInt64(kPrefsUpdateCheckCount, initial_value));
  851. attempter_.scatter_factor_ = TimeDelta::FromSeconds(20);
  852. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  853. EXPECT_CALL(*device_policy, LoadPolicy()).WillRepeatedly(Return(true));
  854. fake_system_state_.set_device_policy(device_policy.get());
  855. EXPECT_CALL(*device_policy, GetDeviceUpdateStagingSchedule(_))
  856. .WillRepeatedly(DoAll(SetArgPointee<0>(schedule), Return(true)));
  857. attempter_.policy_provider_.reset(
  858. new policy::PolicyProvider(std::move(device_policy)));
  859. }
  860. TEST_F(UpdateAttempterTest, StagingSetsPrefsAndTurnsOffScattering) {
  861. loop_.PostTask(
  862. FROM_HERE,
  863. base::Bind(
  864. &UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart,
  865. base::Unretained(this)));
  866. loop_.Run();
  867. }
  868. void UpdateAttempterTest::StagingSetsPrefsAndTurnsOffScatteringStart() {
  869. // Tests that staging sets its prefs properly and turns off scattering.
  870. fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
  871. FakePrefs fake_prefs;
  872. SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
  873. attempter_.Update("", "", "", "", false, false, false);
  874. // Check that prefs have the correct values.
  875. int64_t update_count;
  876. EXPECT_TRUE(fake_prefs.GetInt64(kPrefsUpdateCheckCount, &update_count));
  877. int64_t waiting_time_days;
  878. EXPECT_TRUE(fake_prefs.GetInt64(kPrefsWallClockStagingWaitPeriod,
  879. &waiting_time_days));
  880. EXPECT_GT(waiting_time_days, 0);
  881. // Update count should have been decremented.
  882. EXPECT_EQ(7, update_count);
  883. // Check that Omaha parameters were updated correctly.
  884. EXPECT_TRUE(
  885. attempter_.omaha_request_params_->update_check_count_wait_enabled());
  886. EXPECT_TRUE(
  887. attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
  888. EXPECT_EQ(waiting_time_days,
  889. attempter_.omaha_request_params_->waiting_period().InDays());
  890. // Check class variables.
  891. EXPECT_EQ(waiting_time_days, attempter_.staging_wait_time_.InDays());
  892. EXPECT_EQ(kValidStagingSchedule, attempter_.staging_schedule_);
  893. // Check that scattering is turned off
  894. EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
  895. EXPECT_FALSE(fake_prefs.Exists(kPrefsWallClockScatteringWaitPeriod));
  896. ScheduleQuitMainLoop();
  897. }
  898. void UpdateAttempterTest::CheckStagingOff() {
  899. // Check that all prefs were removed.
  900. EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsUpdateCheckCount));
  901. EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockScatteringWaitPeriod));
  902. EXPECT_FALSE(attempter_.prefs_->Exists(kPrefsWallClockStagingWaitPeriod));
  903. // Check that the Omaha parameters have the correct value.
  904. EXPECT_EQ(0, attempter_.omaha_request_params_->waiting_period().InDays());
  905. EXPECT_EQ(attempter_.omaha_request_params_->waiting_period(),
  906. attempter_.staging_wait_time_);
  907. EXPECT_FALSE(
  908. attempter_.omaha_request_params_->update_check_count_wait_enabled());
  909. EXPECT_FALSE(
  910. attempter_.omaha_request_params_->wall_clock_based_wait_enabled());
  911. // Check that scattering is turned off too.
  912. EXPECT_EQ(0, attempter_.scatter_factor_.InSeconds());
  913. }
  914. TEST_F(UpdateAttempterTest, StagingOffIfInteractive) {
  915. loop_.PostTask(FROM_HERE,
  916. base::Bind(&UpdateAttempterTest::StagingOffIfInteractiveStart,
  917. base::Unretained(this)));
  918. loop_.Run();
  919. }
  920. void UpdateAttempterTest::StagingOffIfInteractiveStart() {
  921. // Tests that staging is turned off when an interactive update is requested.
  922. fake_system_state_.fake_hardware()->SetIsOOBEComplete(Time::UnixEpoch());
  923. FakePrefs fake_prefs;
  924. SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
  925. attempter_.Update("", "", "", "", false, false, /* interactive = */ true);
  926. CheckStagingOff();
  927. ScheduleQuitMainLoop();
  928. }
  929. TEST_F(UpdateAttempterTest, StagingOffIfOobe) {
  930. loop_.PostTask(FROM_HERE,
  931. base::Bind(&UpdateAttempterTest::StagingOffIfOobeStart,
  932. base::Unretained(this)));
  933. loop_.Run();
  934. }
  935. void UpdateAttempterTest::StagingOffIfOobeStart() {
  936. // Tests that staging is turned off if OOBE hasn't been completed.
  937. fake_system_state_.fake_hardware()->SetIsOOBEEnabled(true);
  938. fake_system_state_.fake_hardware()->UnsetIsOOBEComplete();
  939. FakePrefs fake_prefs;
  940. SetUpStagingTest(kValidStagingSchedule, &fake_prefs);
  941. attempter_.Update("", "", "", "", false, false, /* interactive = */ true);
  942. CheckStagingOff();
  943. ScheduleQuitMainLoop();
  944. }
  945. // Checks that we only report daily metrics at most every 24 hours.
  946. TEST_F(UpdateAttempterTest, ReportDailyMetrics) {
  947. FakeClock fake_clock;
  948. FakePrefs fake_prefs;
  949. fake_system_state_.set_clock(&fake_clock);
  950. fake_system_state_.set_prefs(&fake_prefs);
  951. Time epoch = Time::FromInternalValue(0);
  952. fake_clock.SetWallclockTime(epoch);
  953. // If there is no kPrefsDailyMetricsLastReportedAt state variable,
  954. // we should report.
  955. EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
  956. // We should not report again if no time has passed.
  957. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  958. // We should not report if only 10 hours has passed.
  959. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(10));
  960. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  961. // We should not report if only 24 hours - 1 sec has passed.
  962. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24) -
  963. TimeDelta::FromSeconds(1));
  964. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  965. // We should report if 24 hours has passed.
  966. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(24));
  967. EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
  968. // But then we should not report again..
  969. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  970. // .. until another 24 hours has passed
  971. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(47));
  972. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  973. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(48));
  974. EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
  975. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  976. // .. and another 24 hours
  977. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
  978. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  979. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(72));
  980. EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
  981. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  982. // If the span between time of reporting and present time is
  983. // negative, we report. This is in order to reset the timestamp and
  984. // avoid an edge condition whereby a distant point in the future is
  985. // in the state variable resulting in us never ever reporting again.
  986. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(71));
  987. EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
  988. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  989. // In this case we should not update until the clock reads 71 + 24 = 95.
  990. // Check that.
  991. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(94));
  992. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  993. fake_clock.SetWallclockTime(epoch + TimeDelta::FromHours(95));
  994. EXPECT_TRUE(attempter_.CheckAndReportDailyMetrics());
  995. EXPECT_FALSE(attempter_.CheckAndReportDailyMetrics());
  996. }
  997. TEST_F(UpdateAttempterTest, BootTimeInUpdateMarkerFile) {
  998. FakeClock fake_clock;
  999. fake_clock.SetBootTime(Time::FromTimeT(42));
  1000. fake_system_state_.set_clock(&fake_clock);
  1001. FakePrefs fake_prefs;
  1002. fake_system_state_.set_prefs(&fake_prefs);
  1003. attempter_.Init();
  1004. Time boot_time;
  1005. EXPECT_FALSE(attempter_.GetBootTimeAtUpdate(&boot_time));
  1006. attempter_.WriteUpdateCompletedMarker();
  1007. EXPECT_TRUE(attempter_.GetBootTimeAtUpdate(&boot_time));
  1008. EXPECT_EQ(boot_time.ToTimeT(), 42);
  1009. }
  1010. TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedUnofficial) {
  1011. fake_system_state_.fake_hardware()->SetIsOfficialBuild(false);
  1012. EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
  1013. }
  1014. TEST_F(UpdateAttempterTest, AnyUpdateSourceAllowedOfficialDevmode) {
  1015. fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
  1016. fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(true);
  1017. EXPECT_TRUE(attempter_.IsAnyUpdateSourceAllowed());
  1018. }
  1019. TEST_F(UpdateAttempterTest, AnyUpdateSourceDisallowedOfficialNormal) {
  1020. fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
  1021. fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
  1022. EXPECT_FALSE(attempter_.IsAnyUpdateSourceAllowed());
  1023. }
  1024. TEST_F(UpdateAttempterTest, CheckForUpdateAUDlcTest) {
  1025. fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
  1026. fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
  1027. const string dlc_module_id = "a_dlc_module_id";
  1028. vector<string> dlc_module_ids = {dlc_module_id};
  1029. ON_CALL(mock_dlcservice_, GetInstalled(testing::_))
  1030. .WillByDefault(DoAll(testing::SetArgPointee<0>(dlc_module_ids),
  1031. testing::Return(true)));
  1032. attempter_.CheckForUpdate("", "autest", UpdateAttemptFlags::kNone);
  1033. EXPECT_EQ(attempter_.dlc_module_ids_.size(), 1);
  1034. EXPECT_EQ(attempter_.dlc_module_ids_[0], dlc_module_id);
  1035. }
  1036. TEST_F(UpdateAttempterTest, CheckForUpdateAUTest) {
  1037. fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
  1038. fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
  1039. attempter_.CheckForUpdate("", "autest", UpdateAttemptFlags::kNone);
  1040. EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
  1041. }
  1042. TEST_F(UpdateAttempterTest, CheckForUpdateScheduledAUTest) {
  1043. fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
  1044. fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
  1045. attempter_.CheckForUpdate("", "autest-scheduled", UpdateAttemptFlags::kNone);
  1046. EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
  1047. }
  1048. TEST_F(UpdateAttempterTest, CheckForInstallTest) {
  1049. fake_system_state_.fake_hardware()->SetIsOfficialBuild(true);
  1050. fake_system_state_.fake_hardware()->SetAreDevFeaturesEnabled(false);
  1051. attempter_.CheckForInstall({}, "autest");
  1052. EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
  1053. attempter_.CheckForInstall({}, "autest-scheduled");
  1054. EXPECT_EQ(constants::kOmahaDefaultAUTestURL, attempter_.forced_omaha_url());
  1055. attempter_.CheckForInstall({}, "http://omaha.phishing");
  1056. EXPECT_EQ("", attempter_.forced_omaha_url());
  1057. }
  1058. TEST_F(UpdateAttempterTest, InstallSetsStatusIdle) {
  1059. attempter_.CheckForInstall({}, "http://foo.bar");
  1060. attempter_.status_ = UpdateStatus::DOWNLOADING;
  1061. EXPECT_TRUE(attempter_.is_install_);
  1062. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1063. UpdateEngineStatus status;
  1064. attempter_.GetStatus(&status);
  1065. // Should set status to idle after an install operation.
  1066. EXPECT_EQ(UpdateStatus::IDLE, status.status);
  1067. }
  1068. TEST_F(UpdateAttempterTest, RollbackAfterInstall) {
  1069. attempter_.is_install_ = true;
  1070. attempter_.Rollback(false);
  1071. EXPECT_FALSE(attempter_.is_install_);
  1072. }
  1073. TEST_F(UpdateAttempterTest, UpdateAfterInstall) {
  1074. attempter_.is_install_ = true;
  1075. attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
  1076. EXPECT_FALSE(attempter_.is_install_);
  1077. }
  1078. TEST_F(UpdateAttempterTest, TargetVersionPrefixSetAndReset) {
  1079. attempter_.CalculateUpdateParams("", "", "", "1234", false, false, false);
  1080. EXPECT_EQ("1234",
  1081. fake_system_state_.request_params()->target_version_prefix());
  1082. attempter_.CalculateUpdateParams("", "", "", "", false, false, false);
  1083. EXPECT_TRUE(
  1084. fake_system_state_.request_params()->target_version_prefix().empty());
  1085. }
  1086. TEST_F(UpdateAttempterTest, RollbackAllowedSetAndReset) {
  1087. attempter_.CalculateUpdateParams("",
  1088. "",
  1089. "",
  1090. "1234",
  1091. /*rollback_allowed=*/true,
  1092. false,
  1093. false);
  1094. EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
  1095. attempter_.CalculateUpdateParams("",
  1096. "",
  1097. "",
  1098. "1234",
  1099. /*rollback_allowed=*/false,
  1100. false,
  1101. false);
  1102. EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
  1103. }
  1104. TEST_F(UpdateAttempterTest, UpdateDeferredByPolicyTest) {
  1105. // Construct an OmahaResponseHandlerAction that has processed an InstallPlan,
  1106. // but the update is being deferred by the Policy.
  1107. OmahaResponseHandlerAction response_action(&fake_system_state_);
  1108. response_action.install_plan_.version = "a.b.c.d";
  1109. response_action.install_plan_.system_version = "b.c.d.e";
  1110. response_action.install_plan_.payloads.push_back(
  1111. {.size = 1234ULL, .type = InstallPayloadType::kFull});
  1112. // Inform the UpdateAttempter that the OmahaResponseHandlerAction has
  1113. // completed, with the deferred-update error code.
  1114. attempter_.ActionCompleted(
  1115. nullptr, &response_action, ErrorCode::kOmahaUpdateDeferredPerPolicy);
  1116. {
  1117. UpdateEngineStatus status;
  1118. attempter_.GetStatus(&status);
  1119. EXPECT_EQ(UpdateStatus::UPDATE_AVAILABLE, status.status);
  1120. EXPECT_TRUE(attempter_.install_plan_);
  1121. EXPECT_EQ(attempter_.install_plan_->version, status.new_version);
  1122. EXPECT_EQ(attempter_.install_plan_->system_version,
  1123. status.new_system_version);
  1124. EXPECT_EQ(attempter_.install_plan_->payloads[0].size,
  1125. status.new_size_bytes);
  1126. }
  1127. // An "error" event should have been created to tell Omaha that the update is
  1128. // being deferred.
  1129. EXPECT_TRUE(nullptr != attempter_.error_event_);
  1130. EXPECT_EQ(OmahaEvent::kTypeUpdateComplete, attempter_.error_event_->type);
  1131. EXPECT_EQ(OmahaEvent::kResultUpdateDeferred, attempter_.error_event_->result);
  1132. ErrorCode expected_code = static_cast<ErrorCode>(
  1133. static_cast<int>(ErrorCode::kOmahaUpdateDeferredPerPolicy) |
  1134. static_cast<int>(ErrorCode::kTestOmahaUrlFlag));
  1135. EXPECT_EQ(expected_code, attempter_.error_event_->error_code);
  1136. // End the processing
  1137. attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
  1138. // Validate the state of the attempter.
  1139. {
  1140. UpdateEngineStatus status;
  1141. attempter_.GetStatus(&status);
  1142. EXPECT_EQ(UpdateStatus::REPORTING_ERROR_EVENT, status.status);
  1143. EXPECT_EQ(response_action.install_plan_.version, status.new_version);
  1144. EXPECT_EQ(response_action.install_plan_.system_version,
  1145. status.new_system_version);
  1146. EXPECT_EQ(response_action.install_plan_.payloads[0].size,
  1147. status.new_size_bytes);
  1148. }
  1149. }
  1150. TEST_F(UpdateAttempterTest, UpdateIsNotRunningWhenUpdateAvailable) {
  1151. EXPECT_FALSE(attempter_.IsUpdateRunningOrScheduled());
  1152. // Verify in-progress update with UPDATE_AVAILABLE is running
  1153. attempter_.status_ = UpdateStatus::UPDATE_AVAILABLE;
  1154. EXPECT_TRUE(attempter_.IsUpdateRunningOrScheduled());
  1155. }
  1156. TEST_F(UpdateAttempterTest, UpdateAttemptFlagsCachedAtUpdateStart) {
  1157. attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
  1158. UpdateCheckParams params = {.updates_enabled = true};
  1159. attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
  1160. EXPECT_EQ(UpdateAttemptFlags::kFlagRestrictDownload,
  1161. attempter_.GetCurrentUpdateAttemptFlags());
  1162. }
  1163. TEST_F(UpdateAttempterTest, RollbackNotAllowed) {
  1164. UpdateCheckParams params = {.updates_enabled = true,
  1165. .rollback_allowed = false};
  1166. attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
  1167. EXPECT_FALSE(fake_system_state_.request_params()->rollback_allowed());
  1168. }
  1169. TEST_F(UpdateAttempterTest, RollbackAllowed) {
  1170. UpdateCheckParams params = {.updates_enabled = true,
  1171. .rollback_allowed = true};
  1172. attempter_.OnUpdateScheduled(EvalStatus::kSucceeded, params);
  1173. EXPECT_TRUE(fake_system_state_.request_params()->rollback_allowed());
  1174. }
  1175. TEST_F(UpdateAttempterTest, InteractiveUpdateUsesPassedRestrictions) {
  1176. attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kFlagRestrictDownload);
  1177. attempter_.CheckForUpdate("", "", UpdateAttemptFlags::kNone);
  1178. EXPECT_EQ(UpdateAttemptFlags::kNone,
  1179. attempter_.GetCurrentUpdateAttemptFlags());
  1180. }
  1181. TEST_F(UpdateAttempterTest, NonInteractiveUpdateUsesSetRestrictions) {
  1182. attempter_.SetUpdateAttemptFlags(UpdateAttemptFlags::kNone);
  1183. // This tests that when CheckForUpdate() is called with the non-interactive
  1184. // flag set, that it doesn't change the current UpdateAttemptFlags.
  1185. attempter_.CheckForUpdate("",
  1186. "",
  1187. UpdateAttemptFlags::kFlagNonInteractive |
  1188. UpdateAttemptFlags::kFlagRestrictDownload);
  1189. EXPECT_EQ(UpdateAttemptFlags::kNone,
  1190. attempter_.GetCurrentUpdateAttemptFlags());
  1191. }
  1192. void UpdateAttempterTest::ResetRollbackHappenedStart(bool is_consumer,
  1193. bool is_policy_loaded,
  1194. bool expected_reset) {
  1195. EXPECT_CALL(*fake_system_state_.mock_payload_state(), GetRollbackHappened())
  1196. .WillRepeatedly(Return(true));
  1197. auto mock_policy_provider =
  1198. std::make_unique<NiceMock<policy::MockPolicyProvider>>();
  1199. EXPECT_CALL(*mock_policy_provider, IsConsumerDevice())
  1200. .WillRepeatedly(Return(is_consumer));
  1201. EXPECT_CALL(*mock_policy_provider, device_policy_is_loaded())
  1202. .WillRepeatedly(Return(is_policy_loaded));
  1203. const policy::MockDevicePolicy device_policy;
  1204. EXPECT_CALL(*mock_policy_provider, GetDevicePolicy())
  1205. .WillRepeatedly(ReturnRef(device_policy));
  1206. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  1207. SetRollbackHappened(false))
  1208. .Times(expected_reset ? 1 : 0);
  1209. attempter_.policy_provider_ = std::move(mock_policy_provider);
  1210. attempter_.Update("", "", "", "", false, false, false);
  1211. ScheduleQuitMainLoop();
  1212. }
  1213. TEST_F(UpdateAttempterTest, ResetRollbackHappenedOobe) {
  1214. loop_.PostTask(FROM_HERE,
  1215. base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
  1216. base::Unretained(this),
  1217. /*is_consumer=*/false,
  1218. /*is_policy_loaded=*/false,
  1219. /*expected_reset=*/false));
  1220. loop_.Run();
  1221. }
  1222. TEST_F(UpdateAttempterTest, ResetRollbackHappenedConsumer) {
  1223. loop_.PostTask(FROM_HERE,
  1224. base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
  1225. base::Unretained(this),
  1226. /*is_consumer=*/true,
  1227. /*is_policy_loaded=*/false,
  1228. /*expected_reset=*/true));
  1229. loop_.Run();
  1230. }
  1231. TEST_F(UpdateAttempterTest, ResetRollbackHappenedEnterprise) {
  1232. loop_.PostTask(FROM_HERE,
  1233. base::Bind(&UpdateAttempterTest::ResetRollbackHappenedStart,
  1234. base::Unretained(this),
  1235. /*is_consumer=*/false,
  1236. /*is_policy_loaded=*/true,
  1237. /*expected_reset=*/true));
  1238. loop_.Run();
  1239. }
  1240. TEST_F(UpdateAttempterTest, SetRollbackHappenedRollback) {
  1241. attempter_.install_plan_.reset(new InstallPlan);
  1242. attempter_.install_plan_->is_rollback = true;
  1243. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  1244. SetRollbackHappened(true))
  1245. .Times(1);
  1246. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1247. }
  1248. TEST_F(UpdateAttempterTest, SetRollbackHappenedNotRollback) {
  1249. attempter_.install_plan_.reset(new InstallPlan);
  1250. attempter_.install_plan_->is_rollback = false;
  1251. EXPECT_CALL(*fake_system_state_.mock_payload_state(),
  1252. SetRollbackHappened(true))
  1253. .Times(0);
  1254. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1255. }
  1256. TEST_F(UpdateAttempterTest, RollbackMetricsRollbackSuccess) {
  1257. attempter_.install_plan_.reset(new InstallPlan);
  1258. attempter_.install_plan_->is_rollback = true;
  1259. attempter_.install_plan_->version = kRollbackVersion;
  1260. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1261. ReportEnterpriseRollbackMetrics(true, kRollbackVersion))
  1262. .Times(1);
  1263. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1264. }
  1265. TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackSuccess) {
  1266. attempter_.install_plan_.reset(new InstallPlan);
  1267. attempter_.install_plan_->is_rollback = false;
  1268. attempter_.install_plan_->version = kRollbackVersion;
  1269. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1270. ReportEnterpriseRollbackMetrics(_, _))
  1271. .Times(0);
  1272. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1273. }
  1274. TEST_F(UpdateAttempterTest, RollbackMetricsRollbackFailure) {
  1275. attempter_.install_plan_.reset(new InstallPlan);
  1276. attempter_.install_plan_->is_rollback = true;
  1277. attempter_.install_plan_->version = kRollbackVersion;
  1278. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1279. ReportEnterpriseRollbackMetrics(false, kRollbackVersion))
  1280. .Times(1);
  1281. MockAction action;
  1282. attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
  1283. attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
  1284. }
  1285. TEST_F(UpdateAttempterTest, RollbackMetricsNotRollbackFailure) {
  1286. attempter_.install_plan_.reset(new InstallPlan);
  1287. attempter_.install_plan_->is_rollback = false;
  1288. attempter_.install_plan_->version = kRollbackVersion;
  1289. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1290. ReportEnterpriseRollbackMetrics(_, _))
  1291. .Times(0);
  1292. MockAction action;
  1293. attempter_.CreatePendingErrorEvent(&action, ErrorCode::kRollbackNotPossible);
  1294. attempter_.ProcessingDone(nullptr, ErrorCode::kRollbackNotPossible);
  1295. }
  1296. TEST_F(UpdateAttempterTest, TimeToUpdateAppliedMetricFailure) {
  1297. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1298. ReportEnterpriseUpdateSeenToDownloadDays(_, _))
  1299. .Times(0);
  1300. attempter_.ProcessingDone(nullptr, ErrorCode::kOmahaUpdateDeferredPerPolicy);
  1301. }
  1302. TEST_F(UpdateAttempterTest, TimeToUpdateAppliedOnNonEnterprise) {
  1303. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  1304. fake_system_state_.set_device_policy(device_policy.get());
  1305. // Make device policy return that this is not enterprise enrolled
  1306. EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(false));
  1307. // Ensure that the metric is not recorded.
  1308. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1309. ReportEnterpriseUpdateSeenToDownloadDays(_, _))
  1310. .Times(0);
  1311. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1312. }
  1313. TEST_F(UpdateAttempterTest,
  1314. TimeToUpdateAppliedWithTimeRestrictionMetricSuccess) {
  1315. constexpr int kDaysToUpdate = 15;
  1316. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  1317. fake_system_state_.set_device_policy(device_policy.get());
  1318. // Make device policy return that this is enterprise enrolled
  1319. EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
  1320. // Pretend that there's a time restriction policy in place
  1321. EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
  1322. .WillOnce(Return(true));
  1323. FakePrefs fake_prefs;
  1324. Time update_first_seen_at = Time::Now();
  1325. fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
  1326. update_first_seen_at.ToInternalValue());
  1327. FakeClock fake_clock;
  1328. Time update_finished_at =
  1329. update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
  1330. fake_clock.SetWallclockTime(update_finished_at);
  1331. fake_system_state_.set_clock(&fake_clock);
  1332. fake_system_state_.set_prefs(&fake_prefs);
  1333. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1334. ReportEnterpriseUpdateSeenToDownloadDays(true, kDaysToUpdate))
  1335. .Times(1);
  1336. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1337. }
  1338. TEST_F(UpdateAttempterTest,
  1339. TimeToUpdateAppliedWithoutTimeRestrictionMetricSuccess) {
  1340. constexpr int kDaysToUpdate = 15;
  1341. auto device_policy = std::make_unique<policy::MockDevicePolicy>();
  1342. fake_system_state_.set_device_policy(device_policy.get());
  1343. // Make device policy return that this is enterprise enrolled
  1344. EXPECT_CALL(*device_policy, IsEnterpriseEnrolled()).WillOnce(Return(true));
  1345. // Pretend that there's no time restriction policy in place
  1346. EXPECT_CALL(*device_policy, GetDisallowedTimeIntervals(_))
  1347. .WillOnce(Return(false));
  1348. FakePrefs fake_prefs;
  1349. Time update_first_seen_at = Time::Now();
  1350. fake_prefs.SetInt64(kPrefsUpdateFirstSeenAt,
  1351. update_first_seen_at.ToInternalValue());
  1352. FakeClock fake_clock;
  1353. Time update_finished_at =
  1354. update_first_seen_at + TimeDelta::FromDays(kDaysToUpdate);
  1355. fake_clock.SetWallclockTime(update_finished_at);
  1356. fake_system_state_.set_clock(&fake_clock);
  1357. fake_system_state_.set_prefs(&fake_prefs);
  1358. EXPECT_CALL(*fake_system_state_.mock_metrics_reporter(),
  1359. ReportEnterpriseUpdateSeenToDownloadDays(false, kDaysToUpdate))
  1360. .Times(1);
  1361. attempter_.ProcessingDone(nullptr, ErrorCode::kSuccess);
  1362. }
  1363. } // namespace chromeos_update_engine