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/omaha_request_action.h"
18
19#include <stdint.h>
20
21#include <string>
22#include <vector>
23
24#include <base/bind.h>
25#include <base/files/file_util.h>
26#include <base/strings/string_number_conversions.h>
27#include <base/strings/string_util.h>
28#include <base/strings/stringprintf.h>
29#include <base/time/time.h>
30#include <brillo/bind_lambda.h>
31#include <brillo/make_unique_ptr.h>
32#include <brillo/message_loops/fake_message_loop.h>
33#include <brillo/message_loops/message_loop.h>
34#include <brillo/message_loops/message_loop_utils.h>
35#include <gtest/gtest.h>
36
37#include "update_engine/common/action_pipe.h"
38#include "update_engine/common/constants.h"
39#include "update_engine/common/fake_prefs.h"
40#include "update_engine/common/hash_calculator.h"
41#include "update_engine/common/mock_http_fetcher.h"
42#include "update_engine/common/platform_constants.h"
43#include "update_engine/common/prefs.h"
44#include "update_engine/common/test_utils.h"
45#include "update_engine/common/utils.h"
46#include "update_engine/fake_system_state.h"
47#include "update_engine/metrics.h"
48#include "update_engine/mock_connection_manager.h"
49#include "update_engine/mock_payload_state.h"
50#include "update_engine/omaha_request_params.h"
51
52using base::Time;
53using base::TimeDelta;
54using chromeos_update_engine::test_utils::System;
55using chromeos_update_engine::test_utils::WriteFileString;
56using std::string;
57using std::vector;
58using testing::AllOf;
59using testing::AnyNumber;
60using testing::DoAll;
61using testing::Ge;
62using testing::Le;
63using testing::NiceMock;
64using testing::Return;
65using testing::ReturnPointee;
66using testing::SaveArg;
67using testing::SetArgumentPointee;
68using testing::_;
69
70namespace {
71
72const char kTestAppId[] = "test-app-id";
73
74// This is a helper struct to allow unit tests build an update response with the
75// values they care about.
76struct FakeUpdateResponse {
77  string GetNoUpdateResponse() const {
78    string entity_str;
79    if (include_entity)
80      entity_str = "<!DOCTYPE response [<!ENTITY CrOS \"ChromeOS\">]>";
81    return
82        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
83        entity_str + "<response protocol=\"3.0\">"
84        "<daystart elapsed_seconds=\"100\"/>"
85        "<app appid=\"" + app_id + "\" " +
86        (include_cohorts ? "cohort=\"" + cohort + "\" cohorthint=\"" +
87         cohorthint + "\" cohortname=\"" + cohortname + "\" " : "") +
88        " status=\"ok\">"
89        "<ping status=\"ok\"/>"
90        "<updatecheck status=\"noupdate\"/></app></response>";
91  }
92
93  string GetUpdateResponse() const {
94    return
95        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
96        "protocol=\"3.0\">"
97        "<daystart elapsed_seconds=\"100\"" +
98        (elapsed_days.empty() ? "" : (" elapsed_days=\"" + elapsed_days + "\""))
99        + "/>"
100        "<app appid=\"" + app_id + "\" " +
101        (include_cohorts ? "cohort=\"" + cohort + "\" cohorthint=\"" +
102         cohorthint + "\" cohortname=\"" + cohortname + "\" " : "") +
103        " status=\"ok\">"
104        "<ping status=\"ok\"/><updatecheck status=\"ok\">"
105        "<urls><url codebase=\"" + codebase + "\"/></urls>"
106        "<manifest version=\"" + version + "\">"
107        "<packages><package hash=\"not-used\" name=\"" + filename +  "\" "
108        "size=\"" + base::Int64ToString(size) + "\"/></packages>"
109        "<actions><action event=\"postinstall\" "
110        "ChromeOSVersion=\"" + version + "\" "
111        "MoreInfo=\"" + more_info_url + "\" Prompt=\"" + prompt + "\" "
112        "IsDelta=\"true\" "
113        "IsDeltaPayload=\"true\" "
114        "MaxDaysToScatter=\"" + max_days_to_scatter + "\" "
115        "sha256=\"" + hash + "\" "
116        "needsadmin=\"" + needsadmin + "\" " +
117        (deadline.empty() ? "" : ("deadline=\"" + deadline + "\" ")) +
118        (disable_p2p_for_downloading ?
119            "DisableP2PForDownloading=\"true\" " : "") +
120        (disable_p2p_for_sharing ? "DisableP2PForSharing=\"true\" " : "") +
121        "/></actions></manifest></updatecheck></app></response>";
122  }
123
124  // Return the payload URL, which is split in two fields in the XML response.
125  string GetPayloadUrl() {
126    return codebase + filename;
127  }
128
129  string app_id = kTestAppId;
130  string version = "1.2.3.4";
131  string more_info_url = "http://more/info";
132  string prompt = "true";
133  string codebase = "http://code/base/";
134  string filename = "file.signed";
135  string hash = "HASH1234=";
136  string needsadmin = "false";
137  int64_t size = 123;
138  string deadline = "";
139  string max_days_to_scatter = "7";
140  string elapsed_days = "42";
141
142  // P2P setting defaults to allowed.
143  bool disable_p2p_for_downloading = false;
144  bool disable_p2p_for_sharing = false;
145
146  // Omaha cohorts settings.
147  bool include_cohorts = false;
148  string cohort = "";
149  string cohorthint = "";
150  string cohortname = "";
151
152  // Whether to include the CrOS <!ENTITY> in the XML response.
153  bool include_entity = false;
154};
155
156}  // namespace
157
158namespace chromeos_update_engine {
159
160class OmahaRequestActionTest : public ::testing::Test {
161 protected:
162  void SetUp() override {
163    fake_system_state_.set_request_params(&request_params_);
164    fake_system_state_.set_prefs(&fake_prefs_);
165  }
166
167  // Returns true iff an output response was obtained from the
168  // OmahaRequestAction. |prefs| may be null, in which case a local MockPrefs
169  // is used. |payload_state| may be null, in which case a local mock is used.
170  // |p2p_manager| may be null, in which case a local mock is used.
171  // |connection_manager| may be null, in which case a local mock is used.
172  // out_response may be null. If |fail_http_response_code| is non-negative,
173  // the transfer will fail with that code. |ping_only| is passed through to the
174  // OmahaRequestAction constructor. out_post_data may be null; if non-null, the
175  // post-data received by the mock HttpFetcher is returned.
176  //
177  // The |expected_check_result|, |expected_check_reaction| and
178  // |expected_error_code| parameters are for checking expectations
179  // about reporting UpdateEngine.Check.{Result,Reaction,DownloadError}
180  // UMA statistics. Use the appropriate ::kUnset value to specify that
181  // the given metric should not be reported.
182  bool TestUpdateCheck(OmahaRequestParams* request_params,
183                       const string& http_response,
184                       int fail_http_response_code,
185                       bool ping_only,
186                       ErrorCode expected_code,
187                       metrics::CheckResult expected_check_result,
188                       metrics::CheckReaction expected_check_reaction,
189                       metrics::DownloadErrorCode expected_download_error_code,
190                       OmahaResponse* out_response,
191                       brillo::Blob* out_post_data);
192
193  // Runs and checks a ping test. |ping_only| indicates whether it should send
194  // only a ping or also an updatecheck.
195  void PingTest(bool ping_only);
196
197  // InstallDate test helper function.
198  bool InstallDateParseHelper(const string &elapsed_days,
199                              OmahaResponse *response);
200
201  // P2P test helper function.
202  void P2PTest(
203      bool initial_allow_p2p_for_downloading,
204      bool initial_allow_p2p_for_sharing,
205      bool omaha_disable_p2p_for_downloading,
206      bool omaha_disable_p2p_for_sharing,
207      bool payload_state_allow_p2p_attempt,
208      bool expect_p2p_client_lookup,
209      const string& p2p_client_result_url,
210      bool expected_allow_p2p_for_downloading,
211      bool expected_allow_p2p_for_sharing,
212      const string& expected_p2p_url);
213
214  FakeSystemState fake_system_state_;
215  FakeUpdateResponse fake_update_response_;
216
217  // By default, all tests use these objects unless they replace them in the
218  // fake_system_state_.
219  OmahaRequestParams request_params_ = OmahaRequestParams{
220      &fake_system_state_,
221      constants::kOmahaPlatformName,
222      OmahaRequestParams::kOsVersion,
223      "service_pack",
224      "x86-generic",
225      kTestAppId,
226      "0.1.0.0",
227      "en-US",
228      "unittest",
229      "OEM MODEL 09235 7471",
230      "ChromeOSFirmware.1.0",
231      "0X0A1",
232      false,   // delta okay
233      false,   // interactive
234      "http://url",
235      ""};     // target_version_prefix
236
237  FakePrefs fake_prefs_;
238};
239
240namespace {
241class OmahaRequestActionTestProcessorDelegate : public ActionProcessorDelegate {
242 public:
243  OmahaRequestActionTestProcessorDelegate()
244      : expected_code_(ErrorCode::kSuccess) {}
245  ~OmahaRequestActionTestProcessorDelegate() override {
246  }
247  void ProcessingDone(const ActionProcessor* processor,
248                      ErrorCode code) override {
249    brillo::MessageLoop::current()->BreakLoop();
250  }
251
252  void ActionCompleted(ActionProcessor* processor,
253                       AbstractAction* action,
254                       ErrorCode code) override {
255    // make sure actions always succeed
256    if (action->Type() == OmahaRequestAction::StaticType())
257      EXPECT_EQ(expected_code_, code);
258    else
259      EXPECT_EQ(ErrorCode::kSuccess, code);
260  }
261  ErrorCode expected_code_;
262};
263}  // namespace
264
265class OutputObjectCollectorAction;
266
267template<>
268class ActionTraits<OutputObjectCollectorAction> {
269 public:
270  // Does not take an object for input
271  typedef OmahaResponse InputObjectType;
272  // On success, puts the output path on output
273  typedef NoneType OutputObjectType;
274};
275
276class OutputObjectCollectorAction : public Action<OutputObjectCollectorAction> {
277 public:
278  OutputObjectCollectorAction() : has_input_object_(false) {}
279  void PerformAction() {
280    // copy input object
281    has_input_object_ = HasInputObject();
282    if (has_input_object_)
283      omaha_response_ = GetInputObject();
284    processor_->ActionComplete(this, ErrorCode::kSuccess);
285  }
286  // Should never be called
287  void TerminateProcessing() {
288    CHECK(false);
289  }
290  // Debugging/logging
291  static string StaticType() {
292    return "OutputObjectCollectorAction";
293  }
294  string Type() const { return StaticType(); }
295  using InputObjectType =
296      ActionTraits<OutputObjectCollectorAction>::InputObjectType;
297  using OutputObjectType =
298      ActionTraits<OutputObjectCollectorAction>::OutputObjectType;
299  bool has_input_object_;
300  OmahaResponse omaha_response_;
301};
302
303bool OmahaRequestActionTest::TestUpdateCheck(
304    OmahaRequestParams* request_params,
305    const string& http_response,
306    int fail_http_response_code,
307    bool ping_only,
308    ErrorCode expected_code,
309    metrics::CheckResult expected_check_result,
310    metrics::CheckReaction expected_check_reaction,
311    metrics::DownloadErrorCode expected_download_error_code,
312    OmahaResponse* out_response,
313    brillo::Blob* out_post_data) {
314  brillo::FakeMessageLoop loop(nullptr);
315  loop.SetAsCurrent();
316  MockHttpFetcher* fetcher = new MockHttpFetcher(http_response.data(),
317                                                 http_response.size(),
318                                                 nullptr);
319  if (fail_http_response_code >= 0) {
320    fetcher->FailTransfer(fail_http_response_code);
321  }
322  if (request_params)
323    fake_system_state_.set_request_params(request_params);
324  OmahaRequestAction action(&fake_system_state_,
325                            nullptr,
326                            brillo::make_unique_ptr(fetcher),
327                            ping_only);
328  OmahaRequestActionTestProcessorDelegate delegate;
329  delegate.expected_code_ = expected_code;
330
331  ActionProcessor processor;
332  processor.set_delegate(&delegate);
333  processor.EnqueueAction(&action);
334
335  OutputObjectCollectorAction collector_action;
336  BondActions(&action, &collector_action);
337  processor.EnqueueAction(&collector_action);
338
339  EXPECT_CALL(*fake_system_state_.mock_metrics_lib(), SendEnumToUMA(_, _, _))
340      .Times(AnyNumber());
341  EXPECT_CALL(*fake_system_state_.mock_metrics_lib(),
342      SendEnumToUMA(metrics::kMetricCheckResult,
343          static_cast<int>(expected_check_result),
344          static_cast<int>(metrics::CheckResult::kNumConstants) - 1))
345      .Times(expected_check_result == metrics::CheckResult::kUnset ? 0 : 1);
346  EXPECT_CALL(*fake_system_state_.mock_metrics_lib(),
347      SendEnumToUMA(metrics::kMetricCheckReaction,
348          static_cast<int>(expected_check_reaction),
349          static_cast<int>(metrics::CheckReaction::kNumConstants) - 1))
350      .Times(expected_check_reaction == metrics::CheckReaction::kUnset ? 0 : 1);
351  EXPECT_CALL(*fake_system_state_.mock_metrics_lib(),
352      SendSparseToUMA(metrics::kMetricCheckDownloadErrorCode,
353          static_cast<int>(expected_download_error_code)))
354      .Times(expected_download_error_code == metrics::DownloadErrorCode::kUnset
355             ? 0 : 1);
356
357  loop.PostTask(base::Bind([&processor] { processor.StartProcessing(); }));
358  LOG(INFO) << "loop.PendingTasks() = " << loop.PendingTasks();
359  loop.Run();
360  LOG(INFO) << "loop.PendingTasks() = " << loop.PendingTasks();
361  EXPECT_FALSE(loop.PendingTasks());
362  if (collector_action.has_input_object_ && out_response)
363    *out_response = collector_action.omaha_response_;
364  if (out_post_data)
365    *out_post_data = fetcher->post_data();
366  return collector_action.has_input_object_;
367}
368
369// Tests Event requests -- they should always succeed. |out_post_data|
370// may be null; if non-null, the post-data received by the mock
371// HttpFetcher is returned.
372void TestEvent(OmahaRequestParams params,
373               OmahaEvent* event,
374               const string& http_response,
375               brillo::Blob* out_post_data) {
376  brillo::FakeMessageLoop loop(nullptr);
377  loop.SetAsCurrent();
378  MockHttpFetcher* fetcher = new MockHttpFetcher(http_response.data(),
379                                                 http_response.size(),
380                                                 nullptr);
381  FakeSystemState fake_system_state;
382  fake_system_state.set_request_params(&params);
383  OmahaRequestAction action(&fake_system_state,
384                            event,
385                            brillo::make_unique_ptr(fetcher),
386                            false);
387  OmahaRequestActionTestProcessorDelegate delegate;
388  ActionProcessor processor;
389  processor.set_delegate(&delegate);
390  processor.EnqueueAction(&action);
391
392  loop.PostTask(base::Bind([&processor] { processor.StartProcessing(); }));
393  loop.Run();
394
395  // This test should schedule a callback to notify the crash reporter if
396  // the passed event is an error.
397  EXPECT_EQ(event->result == OmahaEvent::kResultError, loop.PendingTasks());
398
399  if (out_post_data)
400    *out_post_data = fetcher->post_data();
401}
402
403TEST_F(OmahaRequestActionTest, RejectEntities) {
404  OmahaResponse response;
405  fake_update_response_.include_entity = true;
406  ASSERT_FALSE(
407      TestUpdateCheck(nullptr,  // request_params
408                      fake_update_response_.GetNoUpdateResponse(),
409                      -1,
410                      false,  // ping_only
411                      ErrorCode::kOmahaRequestXMLHasEntityDecl,
412                      metrics::CheckResult::kParsingError,
413                      metrics::CheckReaction::kUnset,
414                      metrics::DownloadErrorCode::kUnset,
415                      &response,
416                      nullptr));
417  EXPECT_FALSE(response.update_exists);
418}
419
420TEST_F(OmahaRequestActionTest, NoUpdateTest) {
421  OmahaResponse response;
422  ASSERT_TRUE(
423      TestUpdateCheck(nullptr,  // request_params
424                      fake_update_response_.GetNoUpdateResponse(),
425                      -1,
426                      false,  // ping_only
427                      ErrorCode::kSuccess,
428                      metrics::CheckResult::kNoUpdateAvailable,
429                      metrics::CheckReaction::kUnset,
430                      metrics::DownloadErrorCode::kUnset,
431                      &response,
432                      nullptr));
433  EXPECT_FALSE(response.update_exists);
434}
435
436// Test that all the values in the response are parsed in a normal update
437// response.
438TEST_F(OmahaRequestActionTest, ValidUpdateTest) {
439  OmahaResponse response;
440  fake_update_response_.deadline = "20101020";
441  ASSERT_TRUE(
442      TestUpdateCheck(nullptr,  // request_params
443                      fake_update_response_.GetUpdateResponse(),
444                      -1,
445                      false,  // ping_only
446                      ErrorCode::kSuccess,
447                      metrics::CheckResult::kUpdateAvailable,
448                      metrics::CheckReaction::kUpdating,
449                      metrics::DownloadErrorCode::kUnset,
450                      &response,
451                      nullptr));
452  EXPECT_TRUE(response.update_exists);
453  EXPECT_TRUE(response.update_exists);
454  EXPECT_EQ(fake_update_response_.version, response.version);
455  EXPECT_EQ(fake_update_response_.GetPayloadUrl(), response.payload_urls[0]);
456  EXPECT_EQ(fake_update_response_.more_info_url, response.more_info_url);
457  EXPECT_EQ(fake_update_response_.hash, response.hash);
458  EXPECT_EQ(fake_update_response_.size, response.size);
459  EXPECT_EQ(fake_update_response_.prompt == "true", response.prompt);
460  EXPECT_EQ(fake_update_response_.deadline, response.deadline);
461  // Omaha cohort attribets are not set in the response, so they should not be
462  // persisted.
463  EXPECT_FALSE(fake_prefs_.Exists(kPrefsOmahaCohort));
464  EXPECT_FALSE(fake_prefs_.Exists(kPrefsOmahaCohortHint));
465  EXPECT_FALSE(fake_prefs_.Exists(kPrefsOmahaCohortName));
466}
467
468TEST_F(OmahaRequestActionTest, ValidUpdateBlockedByConnection) {
469  OmahaResponse response;
470  // Set up a connection manager that doesn't allow a valid update over
471  // the current ethernet connection.
472  MockConnectionManager mock_cm;
473  fake_system_state_.set_connection_manager(&mock_cm);
474
475  EXPECT_CALL(mock_cm, GetConnectionProperties(_, _))
476      .WillRepeatedly(
477          DoAll(SetArgumentPointee<0>(NetworkConnectionType::kEthernet),
478                SetArgumentPointee<1>(NetworkTethering::kUnknown),
479                Return(true)));
480  EXPECT_CALL(mock_cm, IsUpdateAllowedOver(NetworkConnectionType::kEthernet, _))
481    .WillRepeatedly(Return(false));
482
483  ASSERT_FALSE(
484      TestUpdateCheck(nullptr,  // request_params
485                      fake_update_response_.GetUpdateResponse(),
486                      -1,
487                      false,  // ping_only
488                      ErrorCode::kOmahaUpdateIgnoredPerPolicy,
489                      metrics::CheckResult::kUpdateAvailable,
490                      metrics::CheckReaction::kIgnored,
491                      metrics::DownloadErrorCode::kUnset,
492                      &response,
493                      nullptr));
494  EXPECT_FALSE(response.update_exists);
495}
496
497TEST_F(OmahaRequestActionTest, ValidUpdateBlockedByRollback) {
498  string rollback_version = "1234.0.0";
499  OmahaResponse response;
500
501  MockPayloadState mock_payload_state;
502  fake_system_state_.set_payload_state(&mock_payload_state);
503
504  EXPECT_CALL(mock_payload_state, GetRollbackVersion())
505    .WillRepeatedly(Return(rollback_version));
506
507  fake_update_response_.version = rollback_version;
508  ASSERT_FALSE(
509      TestUpdateCheck(nullptr,  // request_params
510                      fake_update_response_.GetUpdateResponse(),
511                      -1,
512                      false,  // ping_only
513                      ErrorCode::kOmahaUpdateIgnoredPerPolicy,
514                      metrics::CheckResult::kUpdateAvailable,
515                      metrics::CheckReaction::kIgnored,
516                      metrics::DownloadErrorCode::kUnset,
517                      &response,
518                      nullptr));
519  EXPECT_FALSE(response.update_exists);
520}
521
522TEST_F(OmahaRequestActionTest, WallClockBasedWaitAloneCausesScattering) {
523  OmahaResponse response;
524  OmahaRequestParams params = request_params_;
525  params.set_wall_clock_based_wait_enabled(true);
526  params.set_update_check_count_wait_enabled(false);
527  params.set_waiting_period(TimeDelta::FromDays(2));
528
529  ASSERT_FALSE(
530      TestUpdateCheck(&params,
531                      fake_update_response_.GetUpdateResponse(),
532                      -1,
533                      false,  // ping_only
534                      ErrorCode::kOmahaUpdateDeferredPerPolicy,
535                      metrics::CheckResult::kUpdateAvailable,
536                      metrics::CheckReaction::kDeferring,
537                      metrics::DownloadErrorCode::kUnset,
538                      &response,
539                      nullptr));
540  EXPECT_FALSE(response.update_exists);
541
542  // Verify if we are interactive check we don't defer.
543  params.set_interactive(true);
544  ASSERT_TRUE(
545      TestUpdateCheck(&params,
546                      fake_update_response_.GetUpdateResponse(),
547                      -1,
548                      false,  // ping_only
549                      ErrorCode::kSuccess,
550                      metrics::CheckResult::kUpdateAvailable,
551                      metrics::CheckReaction::kUpdating,
552                      metrics::DownloadErrorCode::kUnset,
553                      &response,
554                      nullptr));
555  EXPECT_TRUE(response.update_exists);
556}
557
558TEST_F(OmahaRequestActionTest, NoWallClockBasedWaitCausesNoScattering) {
559  OmahaResponse response;
560  OmahaRequestParams params = request_params_;
561  params.set_wall_clock_based_wait_enabled(false);
562  params.set_waiting_period(TimeDelta::FromDays(2));
563
564  params.set_update_check_count_wait_enabled(true);
565  params.set_min_update_checks_needed(1);
566  params.set_max_update_checks_allowed(8);
567
568  ASSERT_TRUE(
569      TestUpdateCheck(&params,
570                      fake_update_response_.GetUpdateResponse(),
571                      -1,
572                      false,  // ping_only
573                      ErrorCode::kSuccess,
574                      metrics::CheckResult::kUpdateAvailable,
575                      metrics::CheckReaction::kUpdating,
576                      metrics::DownloadErrorCode::kUnset,
577                      &response,
578                      nullptr));
579  EXPECT_TRUE(response.update_exists);
580}
581
582TEST_F(OmahaRequestActionTest, ZeroMaxDaysToScatterCausesNoScattering) {
583  OmahaResponse response;
584  OmahaRequestParams params = request_params_;
585  params.set_wall_clock_based_wait_enabled(true);
586  params.set_waiting_period(TimeDelta::FromDays(2));
587
588  params.set_update_check_count_wait_enabled(true);
589  params.set_min_update_checks_needed(1);
590  params.set_max_update_checks_allowed(8);
591
592  fake_update_response_.max_days_to_scatter = "0";
593  ASSERT_TRUE(
594      TestUpdateCheck(&params,
595                      fake_update_response_.GetUpdateResponse(),
596                      -1,
597                      false,  // ping_only
598                      ErrorCode::kSuccess,
599                      metrics::CheckResult::kUpdateAvailable,
600                      metrics::CheckReaction::kUpdating,
601                      metrics::DownloadErrorCode::kUnset,
602                      &response,
603                      nullptr));
604  EXPECT_TRUE(response.update_exists);
605}
606
607
608TEST_F(OmahaRequestActionTest, ZeroUpdateCheckCountCausesNoScattering) {
609  OmahaResponse response;
610  OmahaRequestParams params = request_params_;
611  params.set_wall_clock_based_wait_enabled(true);
612  params.set_waiting_period(TimeDelta());
613
614  params.set_update_check_count_wait_enabled(true);
615  params.set_min_update_checks_needed(0);
616  params.set_max_update_checks_allowed(0);
617
618  ASSERT_TRUE(TestUpdateCheck(
619                      &params,
620                      fake_update_response_.GetUpdateResponse(),
621                      -1,
622                      false,  // ping_only
623                      ErrorCode::kSuccess,
624                      metrics::CheckResult::kUpdateAvailable,
625                      metrics::CheckReaction::kUpdating,
626                      metrics::DownloadErrorCode::kUnset,
627                      &response,
628                      nullptr));
629
630  int64_t count;
631  ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateCheckCount, &count));
632  ASSERT_EQ(count, 0);
633  EXPECT_TRUE(response.update_exists);
634}
635
636TEST_F(OmahaRequestActionTest, NonZeroUpdateCheckCountCausesScattering) {
637  OmahaResponse response;
638  OmahaRequestParams params = request_params_;
639  params.set_wall_clock_based_wait_enabled(true);
640  params.set_waiting_period(TimeDelta());
641
642  params.set_update_check_count_wait_enabled(true);
643  params.set_min_update_checks_needed(1);
644  params.set_max_update_checks_allowed(8);
645
646  ASSERT_FALSE(TestUpdateCheck(
647                      &params,
648                      fake_update_response_.GetUpdateResponse(),
649                      -1,
650                      false,  // ping_only
651                      ErrorCode::kOmahaUpdateDeferredPerPolicy,
652                      metrics::CheckResult::kUpdateAvailable,
653                      metrics::CheckReaction::kDeferring,
654                      metrics::DownloadErrorCode::kUnset,
655                      &response,
656                      nullptr));
657
658  int64_t count;
659  ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateCheckCount, &count));
660  ASSERT_GT(count, 0);
661  EXPECT_FALSE(response.update_exists);
662
663  // Verify if we are interactive check we don't defer.
664  params.set_interactive(true);
665  ASSERT_TRUE(
666      TestUpdateCheck(&params,
667                      fake_update_response_.GetUpdateResponse(),
668                      -1,
669                      false,  // ping_only
670                      ErrorCode::kSuccess,
671                      metrics::CheckResult::kUpdateAvailable,
672                      metrics::CheckReaction::kUpdating,
673                      metrics::DownloadErrorCode::kUnset,
674                      &response,
675                      nullptr));
676  EXPECT_TRUE(response.update_exists);
677}
678
679TEST_F(OmahaRequestActionTest, ExistingUpdateCheckCountCausesScattering) {
680  OmahaResponse response;
681  OmahaRequestParams params = request_params_;
682  params.set_wall_clock_based_wait_enabled(true);
683  params.set_waiting_period(TimeDelta());
684
685  params.set_update_check_count_wait_enabled(true);
686  params.set_min_update_checks_needed(1);
687  params.set_max_update_checks_allowed(8);
688
689  ASSERT_TRUE(fake_prefs_.SetInt64(kPrefsUpdateCheckCount, 5));
690
691  ASSERT_FALSE(TestUpdateCheck(
692                      &params,
693                      fake_update_response_.GetUpdateResponse(),
694                      -1,
695                      false,  // ping_only
696                      ErrorCode::kOmahaUpdateDeferredPerPolicy,
697                      metrics::CheckResult::kUpdateAvailable,
698                      metrics::CheckReaction::kDeferring,
699                      metrics::DownloadErrorCode::kUnset,
700                      &response,
701                      nullptr));
702
703  int64_t count;
704  ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateCheckCount, &count));
705  // count remains the same, as the decrementing happens in update_attempter
706  // which this test doesn't exercise.
707  ASSERT_EQ(count, 5);
708  EXPECT_FALSE(response.update_exists);
709
710  // Verify if we are interactive check we don't defer.
711  params.set_interactive(true);
712  ASSERT_TRUE(
713      TestUpdateCheck(&params,
714                      fake_update_response_.GetUpdateResponse(),
715                      -1,
716                      false,  // ping_only
717                      ErrorCode::kSuccess,
718                      metrics::CheckResult::kUpdateAvailable,
719                      metrics::CheckReaction::kUpdating,
720                      metrics::DownloadErrorCode::kUnset,
721                      &response,
722                      nullptr));
723  EXPECT_TRUE(response.update_exists);
724}
725
726TEST_F(OmahaRequestActionTest, CohortsArePersisted) {
727  OmahaResponse response;
728  OmahaRequestParams params = request_params_;
729  fake_update_response_.include_cohorts = true;
730  fake_update_response_.cohort = "s/154454/8479665";
731  fake_update_response_.cohorthint = "please-put-me-on-beta";
732  fake_update_response_.cohortname = "stable";
733
734  ASSERT_TRUE(TestUpdateCheck(&params,
735                              fake_update_response_.GetUpdateResponse(),
736                              -1,
737                              false,  // ping_only
738                              ErrorCode::kSuccess,
739                              metrics::CheckResult::kUpdateAvailable,
740                              metrics::CheckReaction::kUpdating,
741                              metrics::DownloadErrorCode::kUnset,
742                              &response,
743                              nullptr));
744
745  string value;
746  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
747  EXPECT_EQ(fake_update_response_.cohort, value);
748
749  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
750  EXPECT_EQ(fake_update_response_.cohorthint, value);
751
752  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
753  EXPECT_EQ(fake_update_response_.cohortname, value);
754}
755
756TEST_F(OmahaRequestActionTest, CohortsAreUpdated) {
757  OmahaResponse response;
758  OmahaRequestParams params = request_params_;
759  EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohort, "old_value"));
760  EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohortHint, "old_hint"));
761  EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohortName, "old_name"));
762  fake_update_response_.include_cohorts = true;
763  fake_update_response_.cohort = "s/154454/8479665";
764  fake_update_response_.cohorthint = "please-put-me-on-beta";
765  fake_update_response_.cohortname = "";
766
767  ASSERT_TRUE(TestUpdateCheck(&params,
768                              fake_update_response_.GetUpdateResponse(),
769                              -1,
770                              false,  // ping_only
771                              ErrorCode::kSuccess,
772                              metrics::CheckResult::kUpdateAvailable,
773                              metrics::CheckReaction::kUpdating,
774                              metrics::DownloadErrorCode::kUnset,
775                              &response,
776                              nullptr));
777
778  string value;
779  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
780  EXPECT_EQ(fake_update_response_.cohort, value);
781
782  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
783  EXPECT_EQ(fake_update_response_.cohorthint, value);
784
785  EXPECT_FALSE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
786}
787
788TEST_F(OmahaRequestActionTest, CohortsAreNotModifiedWhenMissing) {
789  OmahaResponse response;
790  OmahaRequestParams params = request_params_;
791  EXPECT_TRUE(fake_prefs_.SetString(kPrefsOmahaCohort, "old_value"));
792
793  ASSERT_TRUE(TestUpdateCheck(&params,
794                              fake_update_response_.GetUpdateResponse(),
795                              -1,
796                              false,  // ping_only
797                              ErrorCode::kSuccess,
798                              metrics::CheckResult::kUpdateAvailable,
799                              metrics::CheckReaction::kUpdating,
800                              metrics::DownloadErrorCode::kUnset,
801                              &response,
802                              nullptr));
803
804  string value;
805  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
806  EXPECT_EQ("old_value", value);
807
808  EXPECT_FALSE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
809  EXPECT_FALSE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
810}
811
812TEST_F(OmahaRequestActionTest, CohortsArePersistedWhenNoUpdate) {
813  OmahaResponse response;
814  OmahaRequestParams params = request_params_;
815  fake_update_response_.include_cohorts = true;
816  fake_update_response_.cohort = "s/154454/8479665";
817  fake_update_response_.cohorthint = "please-put-me-on-beta";
818  fake_update_response_.cohortname = "stable";
819
820  ASSERT_TRUE(TestUpdateCheck(&params,
821                              fake_update_response_.GetNoUpdateResponse(),
822                              -1,
823                              false,  // ping_only
824                              ErrorCode::kSuccess,
825                              metrics::CheckResult::kNoUpdateAvailable,
826                              metrics::CheckReaction::kUnset,
827                              metrics::DownloadErrorCode::kUnset,
828                              &response,
829                              nullptr));
830
831  string value;
832  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohort, &value));
833  EXPECT_EQ(fake_update_response_.cohort, value);
834
835  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortHint, &value));
836  EXPECT_EQ(fake_update_response_.cohorthint, value);
837
838  EXPECT_TRUE(fake_prefs_.GetString(kPrefsOmahaCohortName, &value));
839  EXPECT_EQ(fake_update_response_.cohortname, value);
840}
841
842TEST_F(OmahaRequestActionTest, NoOutputPipeTest) {
843  const string http_response(fake_update_response_.GetNoUpdateResponse());
844
845  brillo::FakeMessageLoop loop(nullptr);
846  loop.SetAsCurrent();
847
848  OmahaRequestParams params = request_params_;
849  fake_system_state_.set_request_params(&params);
850  OmahaRequestAction action(&fake_system_state_, nullptr,
851                            brillo::make_unique_ptr(
852                                new MockHttpFetcher(http_response.data(),
853                                                    http_response.size(),
854                                                    nullptr)),
855                            false);
856  OmahaRequestActionTestProcessorDelegate delegate;
857  ActionProcessor processor;
858  processor.set_delegate(&delegate);
859  processor.EnqueueAction(&action);
860
861  loop.PostTask(base::Bind([&processor] { processor.StartProcessing(); }));
862  loop.Run();
863  EXPECT_FALSE(loop.PendingTasks());
864  EXPECT_FALSE(processor.IsRunning());
865}
866
867TEST_F(OmahaRequestActionTest, InvalidXmlTest) {
868  OmahaResponse response;
869  ASSERT_FALSE(
870      TestUpdateCheck(nullptr,  // request_params
871                      "invalid xml>",
872                      -1,
873                      false,  // ping_only
874                      ErrorCode::kOmahaRequestXMLParseError,
875                      metrics::CheckResult::kParsingError,
876                      metrics::CheckReaction::kUnset,
877                      metrics::DownloadErrorCode::kUnset,
878                      &response,
879                      nullptr));
880  EXPECT_FALSE(response.update_exists);
881}
882
883TEST_F(OmahaRequestActionTest, EmptyResponseTest) {
884  OmahaResponse response;
885  ASSERT_FALSE(
886      TestUpdateCheck(nullptr,  // request_params
887                      "",
888                      -1,
889                      false,  // ping_only
890                      ErrorCode::kOmahaRequestEmptyResponseError,
891                      metrics::CheckResult::kParsingError,
892                      metrics::CheckReaction::kUnset,
893                      metrics::DownloadErrorCode::kUnset,
894                      &response,
895                      nullptr));
896  EXPECT_FALSE(response.update_exists);
897}
898
899TEST_F(OmahaRequestActionTest, MissingStatusTest) {
900  OmahaResponse response;
901  ASSERT_FALSE(TestUpdateCheck(
902      nullptr,  // request_params
903      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
904      "<daystart elapsed_seconds=\"100\"/>"
905      "<app appid=\"foo\" status=\"ok\">"
906      "<ping status=\"ok\"/>"
907      "<updatecheck/></app></response>",
908      -1,
909      false,  // ping_only
910      ErrorCode::kOmahaResponseInvalid,
911      metrics::CheckResult::kParsingError,
912      metrics::CheckReaction::kUnset,
913      metrics::DownloadErrorCode::kUnset,
914      &response,
915      nullptr));
916  EXPECT_FALSE(response.update_exists);
917}
918
919TEST_F(OmahaRequestActionTest, InvalidStatusTest) {
920  OmahaResponse response;
921  ASSERT_FALSE(TestUpdateCheck(
922      nullptr,  // request_params
923      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
924      "<daystart elapsed_seconds=\"100\"/>"
925      "<app appid=\"foo\" status=\"ok\">"
926      "<ping status=\"ok\"/>"
927      "<updatecheck status=\"InvalidStatusTest\"/></app></response>",
928      -1,
929      false,  // ping_only
930      ErrorCode::kOmahaResponseInvalid,
931      metrics::CheckResult::kParsingError,
932      metrics::CheckReaction::kUnset,
933      metrics::DownloadErrorCode::kUnset,
934      &response,
935      nullptr));
936  EXPECT_FALSE(response.update_exists);
937}
938
939TEST_F(OmahaRequestActionTest, MissingNodesetTest) {
940  OmahaResponse response;
941  ASSERT_FALSE(TestUpdateCheck(
942      nullptr,  // request_params
943      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
944      "<daystart elapsed_seconds=\"100\"/>"
945      "<app appid=\"foo\" status=\"ok\">"
946      "<ping status=\"ok\"/>"
947      "</app></response>",
948      -1,
949      false,  // ping_only
950      ErrorCode::kOmahaResponseInvalid,
951      metrics::CheckResult::kParsingError,
952      metrics::CheckReaction::kUnset,
953      metrics::DownloadErrorCode::kUnset,
954      &response,
955      nullptr));
956  EXPECT_FALSE(response.update_exists);
957}
958
959TEST_F(OmahaRequestActionTest, MissingFieldTest) {
960  string input_response =
961      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response protocol=\"3.0\">"
962      "<daystart elapsed_seconds=\"100\"/>"
963      "<app appid=\"xyz\" status=\"ok\">"
964      "<updatecheck status=\"ok\">"
965      "<urls><url codebase=\"http://missing/field/test/\"/></urls>"
966      "<manifest version=\"10.2.3.4\">"
967      "<packages><package hash=\"not-used\" name=\"f\" "
968      "size=\"587\"/></packages>"
969      "<actions><action event=\"postinstall\" "
970      "ChromeOSVersion=\"10.2.3.4\" "
971      "Prompt=\"false\" "
972      "IsDelta=\"true\" "
973      "IsDeltaPayload=\"false\" "
974      "sha256=\"lkq34j5345\" "
975      "needsadmin=\"true\" "
976      "/></actions></manifest></updatecheck></app></response>";
977  LOG(INFO) << "Input Response = " << input_response;
978
979  OmahaResponse response;
980  ASSERT_TRUE(TestUpdateCheck(nullptr,  // request_params
981                              input_response,
982                              -1,
983                              false,  // ping_only
984                              ErrorCode::kSuccess,
985                              metrics::CheckResult::kUpdateAvailable,
986                              metrics::CheckReaction::kUpdating,
987                              metrics::DownloadErrorCode::kUnset,
988                              &response,
989                              nullptr));
990  EXPECT_TRUE(response.update_exists);
991  EXPECT_EQ("10.2.3.4", response.version);
992  EXPECT_EQ("http://missing/field/test/f", response.payload_urls[0]);
993  EXPECT_EQ("", response.more_info_url);
994  EXPECT_EQ("lkq34j5345", response.hash);
995  EXPECT_EQ(587, response.size);
996  EXPECT_FALSE(response.prompt);
997  EXPECT_TRUE(response.deadline.empty());
998}
999
1000namespace {
1001class TerminateEarlyTestProcessorDelegate : public ActionProcessorDelegate {
1002 public:
1003  void ProcessingStopped(const ActionProcessor* processor) {
1004    brillo::MessageLoop::current()->BreakLoop();
1005  }
1006};
1007
1008void TerminateTransferTestStarter(ActionProcessor* processor) {
1009  processor->StartProcessing();
1010  CHECK(processor->IsRunning());
1011  processor->StopProcessing();
1012}
1013}  // namespace
1014
1015TEST_F(OmahaRequestActionTest, TerminateTransferTest) {
1016  brillo::FakeMessageLoop loop(nullptr);
1017  loop.SetAsCurrent();
1018
1019  string http_response("doesn't matter");
1020  OmahaRequestAction action(&fake_system_state_, nullptr,
1021                            brillo::make_unique_ptr(
1022                                new MockHttpFetcher(http_response.data(),
1023                                                    http_response.size(),
1024                                                    nullptr)),
1025                            false);
1026  TerminateEarlyTestProcessorDelegate delegate;
1027  ActionProcessor processor;
1028  processor.set_delegate(&delegate);
1029  processor.EnqueueAction(&action);
1030
1031  loop.PostTask(base::Bind(&TerminateTransferTestStarter, &processor));
1032  loop.Run();
1033  EXPECT_FALSE(loop.PendingTasks());
1034}
1035
1036TEST_F(OmahaRequestActionTest, XmlEncodeTest) {
1037  string output;
1038  EXPECT_TRUE(XmlEncode("ab", &output));
1039  EXPECT_EQ("ab", output);
1040  EXPECT_TRUE(XmlEncode("a<b", &output));
1041  EXPECT_EQ("a&lt;b", output);
1042  EXPECT_TRUE(XmlEncode("<&>\"\'\\", &output));
1043  EXPECT_EQ("&lt;&amp;&gt;&quot;&apos;\\", output);
1044  EXPECT_TRUE(XmlEncode("&lt;&amp;&gt;", &output));
1045  EXPECT_EQ("&amp;lt;&amp;amp;&amp;gt;", output);
1046  // Check that unterminated UTF-8 strings are handled properly.
1047  EXPECT_FALSE(XmlEncode("\xc2", &output));
1048  // Fail with invalid ASCII-7 chars.
1049  EXPECT_FALSE(XmlEncode("This is an 'n' with a tilde: \xc3\xb1", &output));
1050}
1051
1052TEST_F(OmahaRequestActionTest, XmlEncodeWithDefaultTest) {
1053  EXPECT_EQ("&lt;&amp;&gt;", XmlEncodeWithDefault("<&>", "something else"));
1054  EXPECT_EQ("<not escaped>", XmlEncodeWithDefault("\xc2", "<not escaped>"));
1055}
1056
1057TEST_F(OmahaRequestActionTest, XmlEncodeIsUsedForParams) {
1058  brillo::Blob post_data;
1059
1060  // Make sure XML Encode is being called on the params
1061  OmahaRequestParams params(&fake_system_state_,
1062                            constants::kOmahaPlatformName,
1063                            OmahaRequestParams::kOsVersion,
1064                            "testtheservice_pack>",
1065                            "x86 generic<id",
1066                            kTestAppId,
1067                            "0.1.0.0",
1068                            "en-US",
1069                            "unittest_track&lt;",
1070                            "<OEM MODEL>",
1071                            "ChromeOSFirmware.1.0",
1072                            "EC100",
1073                            false,   // delta okay
1074                            false,   // interactive
1075                            "http://url",
1076                            "");     // target_version_prefix
1077  fake_prefs_.SetString(kPrefsOmahaCohort, "evil\nstring");
1078  fake_prefs_.SetString(kPrefsOmahaCohortHint, "evil&string\\");
1079  fake_prefs_.SetString(kPrefsOmahaCohortName,
1080                        base::JoinString(
1081                            vector<string>(100, "My spoon is too big."), " "));
1082  OmahaResponse response;
1083  ASSERT_FALSE(
1084      TestUpdateCheck(&params,
1085                      "invalid xml>",
1086                      -1,
1087                      false,  // ping_only
1088                      ErrorCode::kOmahaRequestXMLParseError,
1089                      metrics::CheckResult::kParsingError,
1090                      metrics::CheckReaction::kUnset,
1091                      metrics::DownloadErrorCode::kUnset,
1092                      &response,
1093                      &post_data));
1094  // convert post_data to string
1095  string post_str(post_data.begin(), post_data.end());
1096  EXPECT_NE(string::npos, post_str.find("testtheservice_pack&gt;"));
1097  EXPECT_EQ(string::npos, post_str.find("testtheservice_pack>"));
1098  EXPECT_NE(string::npos, post_str.find("x86 generic&lt;id"));
1099  EXPECT_EQ(string::npos, post_str.find("x86 generic<id"));
1100  EXPECT_NE(string::npos, post_str.find("unittest_track&amp;lt;"));
1101  EXPECT_EQ(string::npos, post_str.find("unittest_track&lt;"));
1102  EXPECT_NE(string::npos, post_str.find("&lt;OEM MODEL&gt;"));
1103  EXPECT_EQ(string::npos, post_str.find("<OEM MODEL>"));
1104  EXPECT_NE(string::npos, post_str.find("cohort=\"evil\nstring\""));
1105  EXPECT_EQ(string::npos, post_str.find("cohorthint=\"evil&string\\\""));
1106  EXPECT_NE(string::npos, post_str.find("cohorthint=\"evil&amp;string\\\""));
1107  // Values from Prefs that are too big are removed from the XML instead of
1108  // encoded.
1109  EXPECT_EQ(string::npos, post_str.find("cohortname="));
1110}
1111
1112TEST_F(OmahaRequestActionTest, XmlDecodeTest) {
1113  OmahaResponse response;
1114  fake_update_response_.deadline = "&lt;20110101";
1115  fake_update_response_.more_info_url = "testthe&lt;url";
1116  fake_update_response_.codebase = "testthe&amp;codebase/";
1117  ASSERT_TRUE(
1118      TestUpdateCheck(nullptr,  // request_params
1119                      fake_update_response_.GetUpdateResponse(),
1120                      -1,
1121                      false,  // ping_only
1122                      ErrorCode::kSuccess,
1123                      metrics::CheckResult::kUpdateAvailable,
1124                      metrics::CheckReaction::kUpdating,
1125                      metrics::DownloadErrorCode::kUnset,
1126                      &response,
1127                      nullptr));
1128
1129  EXPECT_EQ(response.more_info_url, "testthe<url");
1130  EXPECT_EQ(response.payload_urls[0], "testthe&codebase/file.signed");
1131  EXPECT_EQ(response.deadline, "<20110101");
1132}
1133
1134TEST_F(OmahaRequestActionTest, ParseIntTest) {
1135  OmahaResponse response;
1136  // overflows int32_t:
1137  fake_update_response_.size = 123123123123123ll;
1138  ASSERT_TRUE(
1139      TestUpdateCheck(nullptr,  // request_params
1140                      fake_update_response_.GetUpdateResponse(),
1141                      -1,
1142                      false,  // ping_only
1143                      ErrorCode::kSuccess,
1144                      metrics::CheckResult::kUpdateAvailable,
1145                      metrics::CheckReaction::kUpdating,
1146                      metrics::DownloadErrorCode::kUnset,
1147                      &response,
1148                      nullptr));
1149
1150  EXPECT_EQ(response.size, 123123123123123ll);
1151}
1152
1153TEST_F(OmahaRequestActionTest, FormatUpdateCheckOutputTest) {
1154  brillo::Blob post_data;
1155  NiceMock<MockPrefs> prefs;
1156  fake_system_state_.set_prefs(&prefs);
1157
1158  EXPECT_CALL(prefs, GetString(kPrefsPreviousVersion, _))
1159      .WillOnce(DoAll(SetArgumentPointee<1>(string("")), Return(true)));
1160  // An existing but empty previous version means that we didn't reboot to a new
1161  // update, therefore, no need to update the previous version.
1162  EXPECT_CALL(prefs, SetString(kPrefsPreviousVersion, _)).Times(0);
1163  ASSERT_FALSE(TestUpdateCheck(nullptr,  // request_params
1164                               "invalid xml>",
1165                               -1,
1166                               false,  // ping_only
1167                               ErrorCode::kOmahaRequestXMLParseError,
1168                               metrics::CheckResult::kParsingError,
1169                               metrics::CheckReaction::kUnset,
1170                               metrics::DownloadErrorCode::kUnset,
1171                               nullptr,  // response
1172                               &post_data));
1173  // convert post_data to string
1174  string post_str(post_data.begin(), post_data.end());
1175  EXPECT_NE(post_str.find(
1176      "        <ping active=\"1\" a=\"-1\" r=\"-1\"></ping>\n"
1177      "        <updatecheck targetversionprefix=\"\"></updatecheck>\n"),
1178      string::npos);
1179  EXPECT_NE(post_str.find("hardware_class=\"OEM MODEL 09235 7471\""),
1180            string::npos);
1181  EXPECT_NE(post_str.find("fw_version=\"ChromeOSFirmware.1.0\""),
1182            string::npos);
1183  EXPECT_NE(post_str.find("ec_version=\"0X0A1\""),
1184            string::npos);
1185  // No <event> tag should be sent if we didn't reboot to an update.
1186  EXPECT_EQ(post_str.find("<event"), string::npos);
1187}
1188
1189
1190TEST_F(OmahaRequestActionTest, FormatSuccessEventOutputTest) {
1191  brillo::Blob post_data;
1192  TestEvent(request_params_,
1193            new OmahaEvent(OmahaEvent::kTypeUpdateDownloadStarted),
1194            "invalid xml>",
1195            &post_data);
1196  // convert post_data to string
1197  string post_str(post_data.begin(), post_data.end());
1198  string expected_event = base::StringPrintf(
1199      "        <event eventtype=\"%d\" eventresult=\"%d\"></event>\n",
1200      OmahaEvent::kTypeUpdateDownloadStarted,
1201      OmahaEvent::kResultSuccess);
1202  EXPECT_NE(post_str.find(expected_event), string::npos);
1203  EXPECT_EQ(post_str.find("ping"), string::npos);
1204  EXPECT_EQ(post_str.find("updatecheck"), string::npos);
1205}
1206
1207TEST_F(OmahaRequestActionTest, FormatErrorEventOutputTest) {
1208  brillo::Blob post_data;
1209  TestEvent(request_params_,
1210            new OmahaEvent(OmahaEvent::kTypeDownloadComplete,
1211                           OmahaEvent::kResultError,
1212                           ErrorCode::kError),
1213            "invalid xml>",
1214            &post_data);
1215  // convert post_data to string
1216  string post_str(post_data.begin(), post_data.end());
1217  string expected_event = base::StringPrintf(
1218      "        <event eventtype=\"%d\" eventresult=\"%d\" "
1219      "errorcode=\"%d\"></event>\n",
1220      OmahaEvent::kTypeDownloadComplete,
1221      OmahaEvent::kResultError,
1222      static_cast<int>(ErrorCode::kError));
1223  EXPECT_NE(post_str.find(expected_event), string::npos);
1224  EXPECT_EQ(post_str.find("updatecheck"), string::npos);
1225}
1226
1227TEST_F(OmahaRequestActionTest, IsEventTest) {
1228  string http_response("doesn't matter");
1229  // Create a copy of the OmahaRequestParams to reuse it later.
1230  OmahaRequestParams params = request_params_;
1231  fake_system_state_.set_request_params(&params);
1232  OmahaRequestAction update_check_action(
1233      &fake_system_state_,
1234      nullptr,
1235      brillo::make_unique_ptr(
1236          new MockHttpFetcher(http_response.data(),
1237                              http_response.size(),
1238                              nullptr)),
1239      false);
1240  EXPECT_FALSE(update_check_action.IsEvent());
1241
1242  params = request_params_;
1243  fake_system_state_.set_request_params(&params);
1244  OmahaRequestAction event_action(
1245      &fake_system_state_,
1246      new OmahaEvent(OmahaEvent::kTypeUpdateComplete),
1247      brillo::make_unique_ptr(
1248          new MockHttpFetcher(http_response.data(),
1249                              http_response.size(),
1250                              nullptr)),
1251      false);
1252  EXPECT_TRUE(event_action.IsEvent());
1253}
1254
1255TEST_F(OmahaRequestActionTest, FormatDeltaOkayOutputTest) {
1256  for (int i = 0; i < 2; i++) {
1257    bool delta_okay = i == 1;
1258    const char* delta_okay_str = delta_okay ? "true" : "false";
1259    brillo::Blob post_data;
1260    OmahaRequestParams params(&fake_system_state_,
1261                              constants::kOmahaPlatformName,
1262                              OmahaRequestParams::kOsVersion,
1263                              "service_pack",
1264                              "x86-generic",
1265                              kTestAppId,
1266                              "0.1.0.0",
1267                              "en-US",
1268                              "unittest_track",
1269                              "OEM MODEL REV 1234",
1270                              "ChromeOSFirmware.1.0",
1271                              "EC100",
1272                              delta_okay,
1273                              false,  // interactive
1274                              "http://url",
1275                              "");    // target_version_prefix
1276    ASSERT_FALSE(TestUpdateCheck(&params,
1277                                 "invalid xml>",
1278                                 -1,
1279                                 false,  // ping_only
1280                                 ErrorCode::kOmahaRequestXMLParseError,
1281                                 metrics::CheckResult::kParsingError,
1282                                 metrics::CheckReaction::kUnset,
1283                                 metrics::DownloadErrorCode::kUnset,
1284                                 nullptr,
1285                                 &post_data));
1286    // convert post_data to string
1287    string post_str(post_data.begin(), post_data.end());
1288    EXPECT_NE(post_str.find(base::StringPrintf(" delta_okay=\"%s\"",
1289                                               delta_okay_str)),
1290              string::npos)
1291        << "i = " << i;
1292  }
1293}
1294
1295TEST_F(OmahaRequestActionTest, FormatInteractiveOutputTest) {
1296  for (int i = 0; i < 2; i++) {
1297    bool interactive = i == 1;
1298    const char* interactive_str = interactive ? "ondemandupdate" : "scheduler";
1299    brillo::Blob post_data;
1300    FakeSystemState fake_system_state;
1301    OmahaRequestParams params(&fake_system_state_,
1302                              constants::kOmahaPlatformName,
1303                              OmahaRequestParams::kOsVersion,
1304                              "service_pack",
1305                              "x86-generic",
1306                              kTestAppId,
1307                              "0.1.0.0",
1308                              "en-US",
1309                              "unittest_track",
1310                              "OEM MODEL REV 1234",
1311                              "ChromeOSFirmware.1.0",
1312                              "EC100",
1313                              true,   // delta_okay
1314                              interactive,
1315                              "http://url",
1316                              "");    // target_version_prefix
1317    ASSERT_FALSE(TestUpdateCheck(&params,
1318                                 "invalid xml>",
1319                                 -1,
1320                                 false,  // ping_only
1321                                 ErrorCode::kOmahaRequestXMLParseError,
1322                                 metrics::CheckResult::kParsingError,
1323                                 metrics::CheckReaction::kUnset,
1324                                 metrics::DownloadErrorCode::kUnset,
1325                                 nullptr,
1326                                 &post_data));
1327    // convert post_data to string
1328    string post_str(post_data.begin(), post_data.end());
1329    EXPECT_NE(post_str.find(base::StringPrintf("installsource=\"%s\"",
1330                                               interactive_str)),
1331              string::npos)
1332        << "i = " << i;
1333  }
1334}
1335
1336TEST_F(OmahaRequestActionTest, OmahaEventTest) {
1337  OmahaEvent default_event;
1338  EXPECT_EQ(OmahaEvent::kTypeUnknown, default_event.type);
1339  EXPECT_EQ(OmahaEvent::kResultError, default_event.result);
1340  EXPECT_EQ(ErrorCode::kError, default_event.error_code);
1341
1342  OmahaEvent success_event(OmahaEvent::kTypeUpdateDownloadStarted);
1343  EXPECT_EQ(OmahaEvent::kTypeUpdateDownloadStarted, success_event.type);
1344  EXPECT_EQ(OmahaEvent::kResultSuccess, success_event.result);
1345  EXPECT_EQ(ErrorCode::kSuccess, success_event.error_code);
1346
1347  OmahaEvent error_event(OmahaEvent::kTypeUpdateDownloadFinished,
1348                         OmahaEvent::kResultError,
1349                         ErrorCode::kError);
1350  EXPECT_EQ(OmahaEvent::kTypeUpdateDownloadFinished, error_event.type);
1351  EXPECT_EQ(OmahaEvent::kResultError, error_event.result);
1352  EXPECT_EQ(ErrorCode::kError, error_event.error_code);
1353}
1354
1355void OmahaRequestActionTest::PingTest(bool ping_only) {
1356  NiceMock<MockPrefs> prefs;
1357  fake_system_state_.set_prefs(&prefs);
1358  EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1359    .Times(AnyNumber());
1360  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1361  // Add a few hours to the day difference to test no rounding, etc.
1362  int64_t five_days_ago =
1363      (Time::Now() - TimeDelta::FromHours(5 * 24 + 13)).ToInternalValue();
1364  int64_t six_days_ago =
1365      (Time::Now() - TimeDelta::FromHours(6 * 24 + 11)).ToInternalValue();
1366  EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1367      .WillOnce(DoAll(SetArgumentPointee<1>(0), Return(true)));
1368  EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1369      .WillOnce(DoAll(SetArgumentPointee<1>(six_days_ago), Return(true)));
1370  EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1371      .WillOnce(DoAll(SetArgumentPointee<1>(five_days_ago), Return(true)));
1372  brillo::Blob post_data;
1373  ASSERT_TRUE(
1374      TestUpdateCheck(nullptr,  // request_params
1375                      fake_update_response_.GetNoUpdateResponse(),
1376                      -1,
1377                      ping_only,
1378                      ErrorCode::kSuccess,
1379                      metrics::CheckResult::kUnset,
1380                      metrics::CheckReaction::kUnset,
1381                      metrics::DownloadErrorCode::kUnset,
1382                      nullptr,
1383                      &post_data));
1384  string post_str(post_data.begin(), post_data.end());
1385  EXPECT_NE(post_str.find("<ping active=\"1\" a=\"6\" r=\"5\"></ping>"),
1386            string::npos);
1387  if (ping_only) {
1388    EXPECT_EQ(post_str.find("updatecheck"), string::npos);
1389    EXPECT_EQ(post_str.find("previousversion"), string::npos);
1390  } else {
1391    EXPECT_NE(post_str.find("updatecheck"), string::npos);
1392    EXPECT_NE(post_str.find("previousversion"), string::npos);
1393  }
1394}
1395
1396TEST_F(OmahaRequestActionTest, PingTestSendOnlyAPing) {
1397  PingTest(true  /* ping_only */);
1398}
1399
1400TEST_F(OmahaRequestActionTest, PingTestSendAlsoAnUpdateCheck) {
1401  PingTest(false  /* ping_only */);
1402}
1403
1404TEST_F(OmahaRequestActionTest, ActivePingTest) {
1405  NiceMock<MockPrefs> prefs;
1406  fake_system_state_.set_prefs(&prefs);
1407  EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1408    .Times(AnyNumber());
1409  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1410  int64_t three_days_ago =
1411      (Time::Now() - TimeDelta::FromHours(3 * 24 + 12)).ToInternalValue();
1412  int64_t now = Time::Now().ToInternalValue();
1413  EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1414      .WillOnce(DoAll(SetArgumentPointee<1>(0), Return(true)));
1415  EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1416      .WillOnce(DoAll(SetArgumentPointee<1>(three_days_ago), Return(true)));
1417  EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1418      .WillOnce(DoAll(SetArgumentPointee<1>(now), Return(true)));
1419  brillo::Blob post_data;
1420  ASSERT_TRUE(
1421      TestUpdateCheck(nullptr,  // request_params
1422                      fake_update_response_.GetNoUpdateResponse(),
1423                      -1,
1424                      false,  // ping_only
1425                      ErrorCode::kSuccess,
1426                      metrics::CheckResult::kNoUpdateAvailable,
1427                      metrics::CheckReaction::kUnset,
1428                      metrics::DownloadErrorCode::kUnset,
1429                      nullptr,
1430                      &post_data));
1431  string post_str(post_data.begin(), post_data.end());
1432  EXPECT_NE(post_str.find("<ping active=\"1\" a=\"3\"></ping>"),
1433            string::npos);
1434}
1435
1436TEST_F(OmahaRequestActionTest, RollCallPingTest) {
1437  NiceMock<MockPrefs> prefs;
1438  fake_system_state_.set_prefs(&prefs);
1439  EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1440    .Times(AnyNumber());
1441  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1442  int64_t four_days_ago =
1443      (Time::Now() - TimeDelta::FromHours(4 * 24)).ToInternalValue();
1444  int64_t now = Time::Now().ToInternalValue();
1445  EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1446      .WillOnce(DoAll(SetArgumentPointee<1>(0), Return(true)));
1447  EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1448      .WillOnce(DoAll(SetArgumentPointee<1>(now), Return(true)));
1449  EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1450      .WillOnce(DoAll(SetArgumentPointee<1>(four_days_ago), Return(true)));
1451  brillo::Blob post_data;
1452  ASSERT_TRUE(
1453      TestUpdateCheck(nullptr,  // request_params
1454                      fake_update_response_.GetNoUpdateResponse(),
1455                      -1,
1456                      false,  // ping_only
1457                      ErrorCode::kSuccess,
1458                      metrics::CheckResult::kNoUpdateAvailable,
1459                      metrics::CheckReaction::kUnset,
1460                      metrics::DownloadErrorCode::kUnset,
1461                      nullptr,
1462                      &post_data));
1463  string post_str(post_data.begin(), post_data.end());
1464  EXPECT_NE(post_str.find("<ping active=\"1\" r=\"4\"></ping>\n"),
1465            string::npos);
1466}
1467
1468TEST_F(OmahaRequestActionTest, NoPingTest) {
1469  NiceMock<MockPrefs> prefs;
1470  fake_system_state_.set_prefs(&prefs);
1471  EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1472    .Times(AnyNumber());
1473  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1474  int64_t one_hour_ago =
1475      (Time::Now() - TimeDelta::FromHours(1)).ToInternalValue();
1476  EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1477      .WillOnce(DoAll(SetArgumentPointee<1>(0), Return(true)));
1478  EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1479      .WillOnce(DoAll(SetArgumentPointee<1>(one_hour_ago), Return(true)));
1480  EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1481      .WillOnce(DoAll(SetArgumentPointee<1>(one_hour_ago), Return(true)));
1482  // LastActivePingDay and PrefsLastRollCallPingDay are set even if we didn't
1483  // send a ping.
1484  EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _))
1485      .WillOnce(Return(true));
1486  EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _))
1487      .WillOnce(Return(true));
1488  brillo::Blob post_data;
1489  ASSERT_TRUE(
1490      TestUpdateCheck(nullptr,  // request_params
1491                      fake_update_response_.GetNoUpdateResponse(),
1492                      -1,
1493                      false,  // ping_only
1494                      ErrorCode::kSuccess,
1495                      metrics::CheckResult::kNoUpdateAvailable,
1496                      metrics::CheckReaction::kUnset,
1497                      metrics::DownloadErrorCode::kUnset,
1498                      nullptr,
1499                      &post_data));
1500  string post_str(post_data.begin(), post_data.end());
1501  EXPECT_EQ(post_str.find("ping"), string::npos);
1502}
1503
1504TEST_F(OmahaRequestActionTest, IgnoreEmptyPingTest) {
1505  // This test ensures that we ignore empty ping only requests.
1506  NiceMock<MockPrefs> prefs;
1507  fake_system_state_.set_prefs(&prefs);
1508  int64_t now = Time::Now().ToInternalValue();
1509  EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1510      .WillOnce(DoAll(SetArgumentPointee<1>(now), Return(true)));
1511  EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1512      .WillOnce(DoAll(SetArgumentPointee<1>(now), Return(true)));
1513  EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
1514  EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _)).Times(0);
1515  brillo::Blob post_data;
1516  EXPECT_TRUE(
1517      TestUpdateCheck(nullptr,  // request_params
1518                      fake_update_response_.GetNoUpdateResponse(),
1519                      -1,
1520                      true,  // ping_only
1521                      ErrorCode::kSuccess,
1522                      metrics::CheckResult::kUnset,
1523                      metrics::CheckReaction::kUnset,
1524                      metrics::DownloadErrorCode::kUnset,
1525                      nullptr,
1526                      &post_data));
1527  EXPECT_EQ(0U, post_data.size());
1528}
1529
1530TEST_F(OmahaRequestActionTest, BackInTimePingTest) {
1531  NiceMock<MockPrefs> prefs;
1532  fake_system_state_.set_prefs(&prefs);
1533  EXPECT_CALL(prefs, GetInt64(kPrefsMetricsCheckLastReportingTime, _))
1534    .Times(AnyNumber());
1535  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1536  int64_t future =
1537      (Time::Now() + TimeDelta::FromHours(3 * 24 + 4)).ToInternalValue();
1538  EXPECT_CALL(prefs, GetInt64(kPrefsInstallDateDays, _))
1539      .WillOnce(DoAll(SetArgumentPointee<1>(0), Return(true)));
1540  EXPECT_CALL(prefs, GetInt64(kPrefsLastActivePingDay, _))
1541      .WillOnce(DoAll(SetArgumentPointee<1>(future), Return(true)));
1542  EXPECT_CALL(prefs, GetInt64(kPrefsLastRollCallPingDay, _))
1543      .WillOnce(DoAll(SetArgumentPointee<1>(future), Return(true)));
1544  EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _))
1545      .WillOnce(Return(true));
1546  EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _))
1547      .WillOnce(Return(true));
1548  brillo::Blob post_data;
1549  ASSERT_TRUE(
1550      TestUpdateCheck(nullptr,  // request_params
1551                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
1552                      "protocol=\"3.0\"><daystart elapsed_seconds=\"100\"/>"
1553                      "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
1554                      "<updatecheck status=\"noupdate\"/></app></response>",
1555                      -1,
1556                      false,  // ping_only
1557                      ErrorCode::kSuccess,
1558                      metrics::CheckResult::kNoUpdateAvailable,
1559                      metrics::CheckReaction::kUnset,
1560                      metrics::DownloadErrorCode::kUnset,
1561                      nullptr,
1562                      &post_data));
1563  string post_str(post_data.begin(), post_data.end());
1564  EXPECT_EQ(post_str.find("ping"), string::npos);
1565}
1566
1567TEST_F(OmahaRequestActionTest, LastPingDayUpdateTest) {
1568  // This test checks that the action updates the last ping day to now
1569  // minus 200 seconds with a slack of 5 seconds. Therefore, the test
1570  // may fail if it runs for longer than 5 seconds. It shouldn't run
1571  // that long though.
1572  int64_t midnight =
1573      (Time::Now() - TimeDelta::FromSeconds(200)).ToInternalValue();
1574  int64_t midnight_slack =
1575      (Time::Now() - TimeDelta::FromSeconds(195)).ToInternalValue();
1576  NiceMock<MockPrefs> prefs;
1577  fake_system_state_.set_prefs(&prefs);
1578  EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
1579  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1580  EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay,
1581                              AllOf(Ge(midnight), Le(midnight_slack))))
1582      .WillOnce(Return(true));
1583  EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay,
1584                              AllOf(Ge(midnight), Le(midnight_slack))))
1585      .WillOnce(Return(true));
1586  ASSERT_TRUE(
1587      TestUpdateCheck(nullptr,  // request_params
1588                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
1589                      "protocol=\"3.0\"><daystart elapsed_seconds=\"200\"/>"
1590                      "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
1591                      "<updatecheck status=\"noupdate\"/></app></response>",
1592                      -1,
1593                      false,  // ping_only
1594                      ErrorCode::kSuccess,
1595                      metrics::CheckResult::kNoUpdateAvailable,
1596                      metrics::CheckReaction::kUnset,
1597                      metrics::DownloadErrorCode::kUnset,
1598                      nullptr,
1599                      nullptr));
1600}
1601
1602TEST_F(OmahaRequestActionTest, NoElapsedSecondsTest) {
1603  NiceMock<MockPrefs> prefs;
1604  fake_system_state_.set_prefs(&prefs);
1605  EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
1606  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1607  EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
1608  EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _)).Times(0);
1609  ASSERT_TRUE(
1610      TestUpdateCheck(nullptr,  // request_params
1611                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
1612                      "protocol=\"3.0\"><daystart blah=\"200\"/>"
1613                      "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
1614                      "<updatecheck status=\"noupdate\"/></app></response>",
1615                      -1,
1616                      false,  // ping_only
1617                      ErrorCode::kSuccess,
1618                      metrics::CheckResult::kNoUpdateAvailable,
1619                      metrics::CheckReaction::kUnset,
1620                      metrics::DownloadErrorCode::kUnset,
1621                      nullptr,
1622                      nullptr));
1623}
1624
1625TEST_F(OmahaRequestActionTest, BadElapsedSecondsTest) {
1626  NiceMock<MockPrefs> prefs;
1627  fake_system_state_.set_prefs(&prefs);
1628  EXPECT_CALL(prefs, GetInt64(_, _)).Times(AnyNumber());
1629  EXPECT_CALL(prefs, SetInt64(_, _)).Times(AnyNumber());
1630  EXPECT_CALL(prefs, SetInt64(kPrefsLastActivePingDay, _)).Times(0);
1631  EXPECT_CALL(prefs, SetInt64(kPrefsLastRollCallPingDay, _)).Times(0);
1632  ASSERT_TRUE(
1633      TestUpdateCheck(nullptr,  // request_params
1634                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response "
1635                      "protocol=\"3.0\"><daystart elapsed_seconds=\"x\"/>"
1636                      "<app appid=\"foo\" status=\"ok\"><ping status=\"ok\"/>"
1637                      "<updatecheck status=\"noupdate\"/></app></response>",
1638                      -1,
1639                      false,  // ping_only
1640                      ErrorCode::kSuccess,
1641                      metrics::CheckResult::kNoUpdateAvailable,
1642                      metrics::CheckReaction::kUnset,
1643                      metrics::DownloadErrorCode::kUnset,
1644                      nullptr,
1645                      nullptr));
1646}
1647
1648TEST_F(OmahaRequestActionTest, NoUniqueIDTest) {
1649  brillo::Blob post_data;
1650  ASSERT_FALSE(TestUpdateCheck(nullptr,  // request_params
1651                               "invalid xml>",
1652                               -1,
1653                               false,  // ping_only
1654                               ErrorCode::kOmahaRequestXMLParseError,
1655                               metrics::CheckResult::kParsingError,
1656                               metrics::CheckReaction::kUnset,
1657                               metrics::DownloadErrorCode::kUnset,
1658                               nullptr,  // response
1659                               &post_data));
1660  // convert post_data to string
1661  string post_str(post_data.begin(), post_data.end());
1662  EXPECT_EQ(post_str.find("machineid="), string::npos);
1663  EXPECT_EQ(post_str.find("userid="), string::npos);
1664}
1665
1666TEST_F(OmahaRequestActionTest, NetworkFailureTest) {
1667  OmahaResponse response;
1668  const int http_error_code =
1669      static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + 501;
1670  ASSERT_FALSE(
1671      TestUpdateCheck(nullptr,  // request_params
1672                      "",
1673                      501,
1674                      false,  // ping_only
1675                      static_cast<ErrorCode>(http_error_code),
1676                      metrics::CheckResult::kDownloadError,
1677                      metrics::CheckReaction::kUnset,
1678                      static_cast<metrics::DownloadErrorCode>(501),
1679                      &response,
1680                      nullptr));
1681  EXPECT_FALSE(response.update_exists);
1682}
1683
1684TEST_F(OmahaRequestActionTest, NetworkFailureBadHTTPCodeTest) {
1685  OmahaResponse response;
1686  const int http_error_code =
1687      static_cast<int>(ErrorCode::kOmahaRequestHTTPResponseBase) + 999;
1688  ASSERT_FALSE(
1689      TestUpdateCheck(nullptr,  // request_params
1690                      "",
1691                      1500,
1692                      false,  // ping_only
1693                      static_cast<ErrorCode>(http_error_code),
1694                      metrics::CheckResult::kDownloadError,
1695                      metrics::CheckReaction::kUnset,
1696                      metrics::DownloadErrorCode::kHttpStatusOther,
1697                      &response,
1698                      nullptr));
1699  EXPECT_FALSE(response.update_exists);
1700}
1701
1702TEST_F(OmahaRequestActionTest, TestUpdateFirstSeenAtGetsPersistedFirstTime) {
1703  OmahaResponse response;
1704  OmahaRequestParams params = request_params_;
1705  params.set_wall_clock_based_wait_enabled(true);
1706  params.set_waiting_period(TimeDelta().FromDays(1));
1707  params.set_update_check_count_wait_enabled(false);
1708
1709  ASSERT_FALSE(TestUpdateCheck(
1710                      &params,
1711                      fake_update_response_.GetUpdateResponse(),
1712                      -1,
1713                      false,  // ping_only
1714                      ErrorCode::kOmahaUpdateDeferredPerPolicy,
1715                      metrics::CheckResult::kUpdateAvailable,
1716                      metrics::CheckReaction::kDeferring,
1717                      metrics::DownloadErrorCode::kUnset,
1718                      &response,
1719                      nullptr));
1720
1721  int64_t timestamp = 0;
1722  ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateFirstSeenAt, &timestamp));
1723  ASSERT_GT(timestamp, 0);
1724  EXPECT_FALSE(response.update_exists);
1725
1726  // Verify if we are interactive check we don't defer.
1727  params.set_interactive(true);
1728  ASSERT_TRUE(
1729      TestUpdateCheck(&params,
1730                      fake_update_response_.GetUpdateResponse(),
1731                      -1,
1732                      false,  // ping_only
1733                      ErrorCode::kSuccess,
1734                      metrics::CheckResult::kUpdateAvailable,
1735                      metrics::CheckReaction::kUpdating,
1736                      metrics::DownloadErrorCode::kUnset,
1737                      &response,
1738                      nullptr));
1739  EXPECT_TRUE(response.update_exists);
1740}
1741
1742TEST_F(OmahaRequestActionTest, TestUpdateFirstSeenAtGetsUsedIfAlreadyPresent) {
1743  OmahaResponse response;
1744  OmahaRequestParams params = request_params_;
1745  params.set_wall_clock_based_wait_enabled(true);
1746  params.set_waiting_period(TimeDelta().FromDays(1));
1747  params.set_update_check_count_wait_enabled(false);
1748
1749  // Set the timestamp to a very old value such that it exceeds the
1750  // waiting period set above.
1751  Time t1;
1752  Time::FromString("1/1/2012", &t1);
1753  ASSERT_TRUE(fake_prefs_.SetInt64(
1754      kPrefsUpdateFirstSeenAt, t1.ToInternalValue()));
1755  ASSERT_TRUE(TestUpdateCheck(
1756                      &params,
1757                      fake_update_response_.GetUpdateResponse(),
1758                      -1,
1759                      false,  // ping_only
1760                      ErrorCode::kSuccess,
1761                      metrics::CheckResult::kUpdateAvailable,
1762                      metrics::CheckReaction::kUpdating,
1763                      metrics::DownloadErrorCode::kUnset,
1764                      &response,
1765                      nullptr));
1766
1767  EXPECT_TRUE(response.update_exists);
1768
1769  // Make sure the timestamp t1 is unchanged showing that it was reused.
1770  int64_t timestamp = 0;
1771  ASSERT_TRUE(fake_prefs_.GetInt64(kPrefsUpdateFirstSeenAt, &timestamp));
1772  ASSERT_TRUE(timestamp == t1.ToInternalValue());
1773}
1774
1775TEST_F(OmahaRequestActionTest, TestChangingToMoreStableChannel) {
1776  // Create a uniquely named test directory.
1777  string test_dir;
1778  ASSERT_TRUE(utils::MakeTempDirectory(
1779          "omaha_request_action-test-XXXXXX", &test_dir));
1780
1781  ASSERT_EQ(0, System(string("mkdir -p ") + test_dir + "/etc"));
1782  ASSERT_EQ(0, System(string("mkdir -p ") + test_dir +
1783                      kStatefulPartition + "/etc"));
1784  brillo::Blob post_data;
1785  NiceMock<MockPrefs> prefs;
1786  fake_system_state_.set_prefs(&prefs);
1787  ASSERT_TRUE(WriteFileString(
1788      test_dir + "/etc/lsb-release",
1789      "CHROMEOS_RELEASE_APPID={11111111-1111-1111-1111-111111111111}\n"
1790      "CHROMEOS_BOARD_APPID={22222222-2222-2222-2222-222222222222}\n"
1791      "CHROMEOS_RELEASE_TRACK=canary-channel\n"));
1792  ASSERT_TRUE(WriteFileString(
1793      test_dir + kStatefulPartition + "/etc/lsb-release",
1794      "CHROMEOS_IS_POWERWASH_ALLOWED=true\n"
1795      "CHROMEOS_RELEASE_TRACK=stable-channel\n"));
1796  OmahaRequestParams params = request_params_;
1797  params.set_root(test_dir);
1798  params.Init("1.2.3.4", "", 0);
1799  EXPECT_EQ("canary-channel", params.current_channel());
1800  EXPECT_EQ("stable-channel", params.target_channel());
1801  EXPECT_TRUE(params.to_more_stable_channel());
1802  EXPECT_TRUE(params.is_powerwash_allowed());
1803  ASSERT_FALSE(TestUpdateCheck(&params,
1804                               "invalid xml>",
1805                               -1,
1806                               false,  // ping_only
1807                               ErrorCode::kOmahaRequestXMLParseError,
1808                               metrics::CheckResult::kParsingError,
1809                               metrics::CheckReaction::kUnset,
1810                               metrics::DownloadErrorCode::kUnset,
1811                               nullptr,  // response
1812                               &post_data));
1813  // convert post_data to string
1814  string post_str(post_data.begin(), post_data.end());
1815  EXPECT_NE(string::npos, post_str.find(
1816      "appid=\"{22222222-2222-2222-2222-222222222222}\" "
1817      "version=\"0.0.0.0\" from_version=\"1.2.3.4\" "
1818      "track=\"stable-channel\" from_track=\"canary-channel\" "));
1819
1820  ASSERT_TRUE(base::DeleteFile(base::FilePath(test_dir), true));
1821}
1822
1823TEST_F(OmahaRequestActionTest, TestChangingToLessStableChannel) {
1824  // Create a uniquely named test directory.
1825  string test_dir;
1826  ASSERT_TRUE(utils::MakeTempDirectory(
1827          "omaha_request_action-test-XXXXXX", &test_dir));
1828
1829  ASSERT_EQ(0, System(string("mkdir -p ") + test_dir + "/etc"));
1830  ASSERT_EQ(0, System(string("mkdir -p ") + test_dir +
1831                      kStatefulPartition + "/etc"));
1832  brillo::Blob post_data;
1833  NiceMock<MockPrefs> prefs;
1834  fake_system_state_.set_prefs(&prefs);
1835  ASSERT_TRUE(WriteFileString(
1836      test_dir + "/etc/lsb-release",
1837      "CHROMEOS_RELEASE_APPID={11111111-1111-1111-1111-111111111111}\n"
1838      "CHROMEOS_BOARD_APPID={22222222-2222-2222-2222-222222222222}\n"
1839      "CHROMEOS_RELEASE_TRACK=stable-channel\n"));
1840  ASSERT_TRUE(WriteFileString(
1841      test_dir + kStatefulPartition + "/etc/lsb-release",
1842      "CHROMEOS_RELEASE_TRACK=canary-channel\n"));
1843  OmahaRequestParams params = request_params_;
1844  params.set_root(test_dir);
1845  params.Init("5.6.7.8", "", 0);
1846  EXPECT_EQ("stable-channel", params.current_channel());
1847  EXPECT_EQ("canary-channel", params.target_channel());
1848  EXPECT_FALSE(params.to_more_stable_channel());
1849  EXPECT_FALSE(params.is_powerwash_allowed());
1850  ASSERT_FALSE(TestUpdateCheck(&params,
1851                               "invalid xml>",
1852                               -1,
1853                               false,  // ping_only
1854                               ErrorCode::kOmahaRequestXMLParseError,
1855                               metrics::CheckResult::kParsingError,
1856                               metrics::CheckReaction::kUnset,
1857                               metrics::DownloadErrorCode::kUnset,
1858                               nullptr,  // response
1859                               &post_data));
1860  // convert post_data to string
1861  string post_str(post_data.begin(), post_data.end());
1862  EXPECT_NE(string::npos, post_str.find(
1863      "appid=\"{11111111-1111-1111-1111-111111111111}\" "
1864      "version=\"5.6.7.8\" "
1865      "track=\"canary-channel\" from_track=\"stable-channel\""));
1866  EXPECT_EQ(string::npos, post_str.find("from_version"));
1867}
1868
1869// Checks that the initial ping with a=-1 r=-1 is not send when the device
1870// was powerwashed.
1871TEST_F(OmahaRequestActionTest, PingWhenPowerwashed) {
1872  fake_prefs_.SetString(kPrefsPreviousVersion, "");
1873
1874  // Flag that the device was powerwashed in the past.
1875  fake_system_state_.fake_hardware()->SetPowerwashCount(1);
1876
1877  brillo::Blob post_data;
1878  ASSERT_TRUE(
1879      TestUpdateCheck(nullptr,  // request_params
1880                      fake_update_response_.GetNoUpdateResponse(),
1881                      -1,
1882                      false,  // ping_only
1883                      ErrorCode::kSuccess,
1884                      metrics::CheckResult::kNoUpdateAvailable,
1885                      metrics::CheckReaction::kUnset,
1886                      metrics::DownloadErrorCode::kUnset,
1887                      nullptr,
1888                      &post_data));
1889  // We shouldn't send a ping in this case since powerwash > 0.
1890  string post_str(post_data.begin(), post_data.end());
1891  EXPECT_EQ(string::npos, post_str.find("<ping"));
1892}
1893
1894// Checks that the event 54 is sent on a reboot to a new update.
1895TEST_F(OmahaRequestActionTest, RebootAfterUpdateEvent) {
1896  // Flag that the device was updated in a previous boot.
1897  fake_prefs_.SetString(kPrefsPreviousVersion, "1.2.3.4");
1898
1899  brillo::Blob post_data;
1900  ASSERT_TRUE(
1901      TestUpdateCheck(nullptr,  // request_params
1902                      fake_update_response_.GetNoUpdateResponse(),
1903                      -1,
1904                      false,  // ping_only
1905                      ErrorCode::kSuccess,
1906                      metrics::CheckResult::kNoUpdateAvailable,
1907                      metrics::CheckReaction::kUnset,
1908                      metrics::DownloadErrorCode::kUnset,
1909                      nullptr,
1910                      &post_data));
1911  string post_str(post_data.begin(), post_data.end());
1912
1913  // An event 54 is included and has the right version.
1914  EXPECT_NE(string::npos,
1915            post_str.find(base::StringPrintf(
1916                              "<event eventtype=\"%d\"",
1917                              OmahaEvent::kTypeRebootedAfterUpdate)));
1918  EXPECT_NE(string::npos,
1919            post_str.find("previousversion=\"1.2.3.4\"></event>"));
1920
1921  // The previous version flag should have been removed.
1922  EXPECT_TRUE(fake_prefs_.Exists(kPrefsPreviousVersion));
1923  string prev_version;
1924  EXPECT_TRUE(fake_prefs_.GetString(kPrefsPreviousVersion, &prev_version));
1925  EXPECT_TRUE(prev_version.empty());
1926}
1927
1928void OmahaRequestActionTest::P2PTest(
1929    bool initial_allow_p2p_for_downloading,
1930    bool initial_allow_p2p_for_sharing,
1931    bool omaha_disable_p2p_for_downloading,
1932    bool omaha_disable_p2p_for_sharing,
1933    bool payload_state_allow_p2p_attempt,
1934    bool expect_p2p_client_lookup,
1935    const string& p2p_client_result_url,
1936    bool expected_allow_p2p_for_downloading,
1937    bool expected_allow_p2p_for_sharing,
1938    const string& expected_p2p_url) {
1939  OmahaResponse response;
1940  OmahaRequestParams request_params = request_params_;
1941  bool actual_allow_p2p_for_downloading = initial_allow_p2p_for_downloading;
1942  bool actual_allow_p2p_for_sharing = initial_allow_p2p_for_sharing;
1943  string actual_p2p_url;
1944
1945  MockPayloadState mock_payload_state;
1946  fake_system_state_.set_payload_state(&mock_payload_state);
1947  EXPECT_CALL(mock_payload_state, P2PAttemptAllowed())
1948      .WillRepeatedly(Return(payload_state_allow_p2p_attempt));
1949  EXPECT_CALL(mock_payload_state, GetUsingP2PForDownloading())
1950      .WillRepeatedly(ReturnPointee(&actual_allow_p2p_for_downloading));
1951  EXPECT_CALL(mock_payload_state, GetUsingP2PForSharing())
1952      .WillRepeatedly(ReturnPointee(&actual_allow_p2p_for_sharing));
1953  EXPECT_CALL(mock_payload_state, SetUsingP2PForDownloading(_))
1954      .WillRepeatedly(SaveArg<0>(&actual_allow_p2p_for_downloading));
1955  EXPECT_CALL(mock_payload_state, SetUsingP2PForSharing(_))
1956      .WillRepeatedly(SaveArg<0>(&actual_allow_p2p_for_sharing));
1957  EXPECT_CALL(mock_payload_state, SetP2PUrl(_))
1958      .WillRepeatedly(SaveArg<0>(&actual_p2p_url));
1959
1960  MockP2PManager mock_p2p_manager;
1961  fake_system_state_.set_p2p_manager(&mock_p2p_manager);
1962  mock_p2p_manager.fake().SetLookupUrlForFileResult(p2p_client_result_url);
1963
1964  TimeDelta timeout = TimeDelta::FromSeconds(kMaxP2PNetworkWaitTimeSeconds);
1965  EXPECT_CALL(mock_p2p_manager, LookupUrlForFile(_, _, timeout, _))
1966      .Times(expect_p2p_client_lookup ? 1 : 0);
1967
1968  fake_update_response_.disable_p2p_for_downloading =
1969      omaha_disable_p2p_for_downloading;
1970  fake_update_response_.disable_p2p_for_sharing = omaha_disable_p2p_for_sharing;
1971  ASSERT_TRUE(
1972      TestUpdateCheck(&request_params,
1973                      fake_update_response_.GetUpdateResponse(),
1974                      -1,
1975                      false,  // ping_only
1976                      ErrorCode::kSuccess,
1977                      metrics::CheckResult::kUpdateAvailable,
1978                      metrics::CheckReaction::kUpdating,
1979                      metrics::DownloadErrorCode::kUnset,
1980                      &response,
1981                      nullptr));
1982  EXPECT_TRUE(response.update_exists);
1983
1984  EXPECT_EQ(omaha_disable_p2p_for_downloading,
1985            response.disable_p2p_for_downloading);
1986  EXPECT_EQ(omaha_disable_p2p_for_sharing,
1987            response.disable_p2p_for_sharing);
1988
1989  EXPECT_EQ(expected_allow_p2p_for_downloading,
1990            actual_allow_p2p_for_downloading);
1991  EXPECT_EQ(expected_allow_p2p_for_sharing, actual_allow_p2p_for_sharing);
1992  EXPECT_EQ(expected_p2p_url, actual_p2p_url);
1993}
1994
1995TEST_F(OmahaRequestActionTest, P2PWithPeer) {
1996  P2PTest(true,                   // initial_allow_p2p_for_downloading
1997          true,                   // initial_allow_p2p_for_sharing
1998          false,                  // omaha_disable_p2p_for_downloading
1999          false,                  // omaha_disable_p2p_for_sharing
2000          true,                   // payload_state_allow_p2p_attempt
2001          true,                   // expect_p2p_client_lookup
2002          "http://1.3.5.7/p2p",   // p2p_client_result_url
2003          true,                   // expected_allow_p2p_for_downloading
2004          true,                   // expected_allow_p2p_for_sharing
2005          "http://1.3.5.7/p2p");  // expected_p2p_url
2006}
2007
2008TEST_F(OmahaRequestActionTest, P2PWithoutPeer) {
2009  P2PTest(true,                   // initial_allow_p2p_for_downloading
2010          true,                   // initial_allow_p2p_for_sharing
2011          false,                  // omaha_disable_p2p_for_downloading
2012          false,                  // omaha_disable_p2p_for_sharing
2013          true,                   // payload_state_allow_p2p_attempt
2014          true,                   // expect_p2p_client_lookup
2015          "",                     // p2p_client_result_url
2016          false,                  // expected_allow_p2p_for_downloading
2017          true,                   // expected_allow_p2p_for_sharing
2018          "");                    // expected_p2p_url
2019}
2020
2021TEST_F(OmahaRequestActionTest, P2PDownloadNotAllowed) {
2022  P2PTest(false,                  // initial_allow_p2p_for_downloading
2023          true,                   // initial_allow_p2p_for_sharing
2024          false,                  // omaha_disable_p2p_for_downloading
2025          false,                  // omaha_disable_p2p_for_sharing
2026          true,                   // payload_state_allow_p2p_attempt
2027          false,                  // expect_p2p_client_lookup
2028          "unset",                // p2p_client_result_url
2029          false,                  // expected_allow_p2p_for_downloading
2030          true,                   // expected_allow_p2p_for_sharing
2031          "");                    // expected_p2p_url
2032}
2033
2034TEST_F(OmahaRequestActionTest, P2PWithPeerDownloadDisabledByOmaha) {
2035  P2PTest(true,                   // initial_allow_p2p_for_downloading
2036          true,                   // initial_allow_p2p_for_sharing
2037          true,                   // omaha_disable_p2p_for_downloading
2038          false,                  // omaha_disable_p2p_for_sharing
2039          true,                   // payload_state_allow_p2p_attempt
2040          false,                  // expect_p2p_client_lookup
2041          "unset",                // p2p_client_result_url
2042          false,                  // expected_allow_p2p_for_downloading
2043          true,                   // expected_allow_p2p_for_sharing
2044          "");                    // expected_p2p_url
2045}
2046
2047TEST_F(OmahaRequestActionTest, P2PWithPeerSharingDisabledByOmaha) {
2048  P2PTest(true,                   // initial_allow_p2p_for_downloading
2049          true,                   // initial_allow_p2p_for_sharing
2050          false,                  // omaha_disable_p2p_for_downloading
2051          true,                   // omaha_disable_p2p_for_sharing
2052          true,                   // payload_state_allow_p2p_attempt
2053          true,                   // expect_p2p_client_lookup
2054          "http://1.3.5.7/p2p",   // p2p_client_result_url
2055          true,                   // expected_allow_p2p_for_downloading
2056          false,                  // expected_allow_p2p_for_sharing
2057          "http://1.3.5.7/p2p");  // expected_p2p_url
2058}
2059
2060TEST_F(OmahaRequestActionTest, P2PWithPeerBothDisabledByOmaha) {
2061  P2PTest(true,                   // initial_allow_p2p_for_downloading
2062          true,                   // initial_allow_p2p_for_sharing
2063          true,                   // omaha_disable_p2p_for_downloading
2064          true,                   // omaha_disable_p2p_for_sharing
2065          true,                   // payload_state_allow_p2p_attempt
2066          false,                  // expect_p2p_client_lookup
2067          "unset",                // p2p_client_result_url
2068          false,                  // expected_allow_p2p_for_downloading
2069          false,                  // expected_allow_p2p_for_sharing
2070          "");                    // expected_p2p_url
2071}
2072
2073bool OmahaRequestActionTest::InstallDateParseHelper(const string &elapsed_days,
2074                                                    OmahaResponse *response) {
2075  fake_update_response_.elapsed_days = elapsed_days;
2076  return
2077      TestUpdateCheck(nullptr,  // request_params
2078                      fake_update_response_.GetUpdateResponse(),
2079                      -1,
2080                      false,  // ping_only
2081                      ErrorCode::kSuccess,
2082                      metrics::CheckResult::kUpdateAvailable,
2083                      metrics::CheckReaction::kUpdating,
2084                      metrics::DownloadErrorCode::kUnset,
2085                      response,
2086                      nullptr);
2087}
2088
2089TEST_F(OmahaRequestActionTest, ParseInstallDateFromResponse) {
2090  OmahaResponse response;
2091
2092  // Check that we parse elapsed_days in the Omaha Response correctly.
2093  // and that the kPrefsInstallDateDays value is written to.
2094  EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
2095  EXPECT_TRUE(InstallDateParseHelper("42", &response));
2096  EXPECT_TRUE(response.update_exists);
2097  EXPECT_EQ(42, response.install_date_days);
2098  EXPECT_TRUE(fake_prefs_.Exists(kPrefsInstallDateDays));
2099  int64_t prefs_days;
2100  EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2101  EXPECT_EQ(prefs_days, 42);
2102
2103  // If there already is a value set, we shouldn't do anything.
2104  EXPECT_TRUE(InstallDateParseHelper("7", &response));
2105  EXPECT_TRUE(response.update_exists);
2106  EXPECT_EQ(7, response.install_date_days);
2107  EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2108  EXPECT_EQ(prefs_days, 42);
2109
2110  // Note that elapsed_days is not necessarily divisible by 7 so check
2111  // that we round down correctly when populating kPrefsInstallDateDays.
2112  EXPECT_TRUE(fake_prefs_.Delete(kPrefsInstallDateDays));
2113  EXPECT_TRUE(InstallDateParseHelper("23", &response));
2114  EXPECT_TRUE(response.update_exists);
2115  EXPECT_EQ(23, response.install_date_days);
2116  EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2117  EXPECT_EQ(prefs_days, 21);
2118
2119  // Check that we correctly handle elapsed_days not being included in
2120  // the Omaha Response.
2121  EXPECT_TRUE(InstallDateParseHelper("", &response));
2122  EXPECT_TRUE(response.update_exists);
2123  EXPECT_EQ(-1, response.install_date_days);
2124}
2125
2126// If there is no prefs and OOBE is not complete, we should not
2127// report anything to Omaha.
2128TEST_F(OmahaRequestActionTest, GetInstallDateWhenNoPrefsNorOOBE) {
2129  EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), -1);
2130  EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
2131}
2132
2133// If OOBE is complete and happened on a valid date (e.g. after Jan
2134// 1 2007 0:00 PST), that date should be used and written to
2135// prefs. However, first try with an invalid date and check we do
2136// nothing.
2137TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedWithInvalidDate) {
2138  Time oobe_date = Time::FromTimeT(42);  // Dec 31, 1969 16:00:42 PST.
2139  fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
2140  EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), -1);
2141  EXPECT_FALSE(fake_prefs_.Exists(kPrefsInstallDateDays));
2142}
2143
2144// Then check with a valid date. The date Jan 20, 2007 0:00 PST
2145// should yield an InstallDate of 14.
2146TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedWithValidDate) {
2147  Time oobe_date = Time::FromTimeT(1169280000);  // Jan 20, 2007 0:00 PST.
2148  fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
2149  EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 14);
2150  EXPECT_TRUE(fake_prefs_.Exists(kPrefsInstallDateDays));
2151
2152  int64_t prefs_days;
2153  EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2154  EXPECT_EQ(prefs_days, 14);
2155}
2156
2157// Now that we have a valid date in prefs, check that we keep using
2158// that even if OOBE date reports something else. The date Jan 30,
2159// 2007 0:00 PST should yield an InstallDate of 28... but since
2160// there's a prefs file, we should still get 14.
2161TEST_F(OmahaRequestActionTest, GetInstallDateWhenOOBECompletedDateChanges) {
2162  // Set a valid date in the prefs first.
2163  EXPECT_TRUE(fake_prefs_.SetInt64(kPrefsInstallDateDays, 14));
2164
2165  Time oobe_date = Time::FromTimeT(1170144000);  // Jan 30, 2007 0:00 PST.
2166  fake_system_state_.fake_hardware()->SetIsOOBEComplete(oobe_date);
2167  EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 14);
2168
2169  int64_t prefs_days;
2170  EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2171  EXPECT_EQ(prefs_days, 14);
2172
2173  // If we delete the prefs file, we should get 28 days.
2174  EXPECT_TRUE(fake_prefs_.Delete(kPrefsInstallDateDays));
2175  EXPECT_EQ(OmahaRequestAction::GetInstallDate(&fake_system_state_), 28);
2176  EXPECT_TRUE(fake_prefs_.GetInt64(kPrefsInstallDateDays, &prefs_days));
2177  EXPECT_EQ(prefs_days, 28);
2178}
2179
2180}  // namespace chromeos_update_engine
2181