File: host_scanner_impl_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (807 lines) | stat: -rw-r--r-- 34,235 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/tether/host_scanner_impl.h"

#include <algorithm>
#include <memory>
#include <vector>

#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/run_loop.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "chromeos/ash/components/multidevice/remote_device_test_util.h"
#include "chromeos/ash/components/network/network_state_test_helper.h"
#include "chromeos/ash/components/tether/device_id_tether_network_guid_map.h"
#include "chromeos/ash/components/tether/fake_connection_preserver.h"
#include "chromeos/ash/components/tether/fake_host_scan_cache.h"
#include "chromeos/ash/components/tether/fake_notification_presenter.h"
#include "chromeos/ash/components/tether/fake_tether_host_fetcher.h"
#include "chromeos/ash/components/tether/gms_core_notifications_state_tracker_impl.h"
#include "chromeos/ash/components/tether/host_scanner.h"
#include "chromeos/ash/components/tether/mock_tether_host_response_recorder.h"
#include "chromeos/ash/components/tether/proto_test_util.h"
#include "chromeos/ash/components/tether/top_level_host_scan_cache.h"
#include "chromeos/ash/services/device_sync/public/cpp/fake_device_sync_client.h"
#include "chromeos/ash/services/secure_channel/public/cpp/client/fake_secure_channel_client.h"
#include "chromeos/ash/services/secure_channel/public/cpp/client/secure_channel_client.h"
#include "components/session_manager/core/session_manager.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

namespace ash {

namespace tether {

namespace {

class TestObserver final : public HostScanner::Observer {
 public:
  void ScanFinished() override { scan_finished_count_++; }

  int scan_finished_count() { return scan_finished_count_; }

 private:
  int scan_finished_count_ = 0;
};

class FakeTetherAvailabilityOperationOrchestrator
    : public TetherAvailabilityOperationOrchestrator {
 public:
  FakeTetherAvailabilityOperationOrchestrator()
      : TetherAvailabilityOperationOrchestrator(
            /*tether_availability_operation_initializer=*/nullptr) {}

  ~FakeTetherAvailabilityOperationOrchestrator() override = default;

  void SendScannedDeviceListUpdate(
      const std::vector<ScannedDeviceInfo>& scanned_device_list_so_far,
      bool is_final_scan_result) {
    for (auto& observer : observers_) {
      observer.OnTetherAvailabilityResponse(
          scanned_device_list_so_far, gms_core_notifications_disabled_devices_,
          is_final_scan_result);
    }
    scanned_device_list_so_far_ = scanned_device_list_so_far;
  }

  void Start() override { is_started_ = true; }

  bool is_started() { return is_started_; }

 private:
  bool is_started_ = false;
};

class FakeTetherAvailabilityOperationOrchestratorFactory
    : public TetherAvailabilityOperationOrchestrator::Factory {
 public:
  FakeTetherAvailabilityOperationOrchestratorFactory() {}

  ~FakeTetherAvailabilityOperationOrchestratorFactory() override {}

  std::unique_ptr<TetherAvailabilityOperationOrchestrator> CreateInstance()
      override {
    FakeTetherAvailabilityOperationOrchestrator* orchestrator =
        new FakeTetherAvailabilityOperationOrchestrator();
    created_orchestrators_.push_back(orchestrator);
    return base::WrapUnique(orchestrator);
  }

  std::vector<
      raw_ptr<FakeTetherAvailabilityOperationOrchestrator, VectorExperimental>>&
  created_orchestrators() {
    return created_orchestrators_;
  }

 private:
  std::vector<
      raw_ptr<FakeTetherAvailabilityOperationOrchestrator, VectorExperimental>>
      created_orchestrators_;
};

std::string GenerateCellProviderForDevice(
    multidevice::RemoteDeviceRef remote_device) {
  // Return a string unique to |remote_device|.
  return "cellProvider" + remote_device.GetTruncatedDeviceIdForLogs();
}

std::vector<ScannedDeviceInfo> CreateFakeScannedDeviceInfos(
    const multidevice::RemoteDeviceRefList& remote_devices) {
  // At least 4 ScannedDeviceInfos should be created to ensure that all 4 cases
  // described below are tested.
  EXPECT_GT(remote_devices.size(), 3u);

  std::vector<ScannedDeviceInfo> scanned_device_infos;

  for (size_t i = 0; i < remote_devices.size(); ++i) {
    // Four field possibilities:
    // i % 4 == 0: Field is not supplied.
    // i % 4 == 1: Field is below the minimum value (int fields only).
    // i % 4 == 2: Field is within the valid range (int fields only).
    // i % 4 == 3: Field is above the maximium value (int fields only).
    std::string cell_provider_name;
    int battery_percentage;
    int connection_strength;
    switch (i % 4) {
      case 0:
        cell_provider_name = proto_test_util::kDoNotSetStringField;
        battery_percentage = proto_test_util::kDoNotSetIntField;
        connection_strength = proto_test_util::kDoNotSetIntField;
        break;
      case 1:
        cell_provider_name = GenerateCellProviderForDevice(remote_devices[i]);
        battery_percentage = -1 - i;
        connection_strength = -1 - i;
        break;
      case 2:
        cell_provider_name = GenerateCellProviderForDevice(remote_devices[i]);
        battery_percentage = (50 + i) % 100;  // Valid range is [0, 100].
        connection_strength = (1 + i) % 4;    // Valid range is [0, 4].
        break;
      case 3:
        cell_provider_name = GenerateCellProviderForDevice(remote_devices[i]);
        battery_percentage = 101 + i;
        connection_strength = 101 + i;
        break;
      default:
        NOTREACHED();
    }

    DeviceStatus device_status = CreateTestDeviceStatus(
        cell_provider_name, battery_percentage, connection_strength);

    // Require set-up for odd-numbered device indices.
    bool setup_required = i % 2 == 0;

    scanned_device_infos.push_back(ScannedDeviceInfo(
        remote_devices[i].GetDeviceId(), remote_devices[i].name(),
        device_status, setup_required, /*notifications_enabled=*/true));
  }

  return scanned_device_infos;
}

}  // namespace

class HostScannerImplTest : public testing::Test {
 public:
  HostScannerImplTest(const HostScannerImplTest&) = delete;
  HostScannerImplTest& operator=(const HostScannerImplTest&) = delete;

 protected:
  HostScannerImplTest()
      : test_devices_(multidevice::CreateRemoteDeviceRefListForTest(4)),
        test_scanned_device_infos(CreateFakeScannedDeviceInfos(test_devices_)) {
  }

  void SetUp() override {
    scanned_device_infos_from_current_scan_.clear();

    fake_device_sync_client_ =
        std::make_unique<device_sync::FakeDeviceSyncClient>();
    fake_secure_channel_client_ =
        std::make_unique<secure_channel::FakeSecureChannelClient>();
    session_manager_ = std::make_unique<session_manager::SessionManager>();
    fake_tether_host_fetcher_ =
        std::make_unique<FakeTetherHostFetcher>(test_devices_[0]);
    mock_tether_host_response_recorder_ =
        std::make_unique<MockTetherHostResponseRecorder>();
    gms_core_notifications_state_tracker_ =
        std::make_unique<GmsCoreNotificationsStateTrackerImpl>();
    fake_notification_presenter_ =
        std::make_unique<FakeNotificationPresenter>();
    device_id_tether_network_guid_map_ =
        std::make_unique<DeviceIdTetherNetworkGuidMap>();
    fake_host_scan_cache_ = std::make_unique<FakeHostScanCache>();

    fake_tether_availability_operation_factory_ =
        new FakeTetherAvailabilityOperationOrchestratorFactory();

    fake_connection_preserver_ = std::make_unique<FakeConnectionPreserver>();

    test_clock_ = std::make_unique<base::SimpleTestClock>();

    host_scanner_ = base::WrapUnique(new HostScannerImpl(
        base::WrapUnique<TetherAvailabilityOperationOrchestrator::Factory>(
            fake_tether_availability_operation_factory_),
        helper_.network_state_handler(), session_manager_.get(),
        gms_core_notifications_state_tracker_.get(),
        fake_notification_presenter_.get(),
        device_id_tether_network_guid_map_.get(), fake_host_scan_cache_.get(),
        test_clock_.get()));

    test_observer_ = std::make_unique<TestObserver>();
    host_scanner_->AddObserver(test_observer_.get());
  }

  void TearDown() override {
    host_scanner_->RemoveObserver(test_observer_.get());
  }

  // Causes |fake_orchestrator| to receive the scan result in
  // |test_scanned_device_infos| vector at the index |test_device_index| with
  // the "final result" value of |is_final_scan_result|.
  void ReceiveScanResultAndVerifySuccess(
      FakeTetherAvailabilityOperationOrchestrator* fake_orchestrator,
      size_t test_device_index,
      bool is_final_scan_result,
      NotificationPresenter::PotentialHotspotNotificationState
          expected_notification_state,
      int num_expected_host_scan_histogram_samples = 1) {
    bool already_in_list = false;
    for (auto& scanned_device_info : scanned_device_infos_from_current_scan_) {
      if (scanned_device_info.device_id ==
          test_devices_[test_device_index].GetDeviceId()) {
        already_in_list = true;
        break;
      }
    }

    if (!already_in_list) {
      scanned_device_infos_from_current_scan_.push_back(
          test_scanned_device_infos[test_device_index]);
    }

    int previous_scan_finished_count = test_observer_->scan_finished_count();
    fake_orchestrator->SendScannedDeviceListUpdate(
        scanned_device_infos_from_current_scan_, is_final_scan_result);
    VerifyScanResultsMatchCache();
    EXPECT_EQ(previous_scan_finished_count + (is_final_scan_result ? 1 : 0),
              test_observer_->scan_finished_count());

    EXPECT_EQ(
        expected_notification_state,
        fake_notification_presenter_->GetPotentialHotspotNotificationState());

    if (is_final_scan_result) {
      HostScannerImpl::HostScanResultEventType expected_event_type =
          HostScannerImpl::HostScanResultEventType::NO_HOSTS_FOUND;
      if (!scanned_device_infos_from_current_scan_.empty() &&
          expected_notification_state ==
              NotificationPresenter::PotentialHotspotNotificationState::
                  NO_HOTSPOT_NOTIFICATION_SHOWN) {
        expected_event_type = HostScannerImpl::HostScanResultEventType::
            HOSTS_FOUND_BUT_NO_NOTIFICATION_SHOWN;
      } else if (scanned_device_infos_from_current_scan_.size() == 1) {
        expected_event_type = HostScannerImpl::HostScanResultEventType::
            NOTIFICATION_SHOWN_SINGLE_HOST;
      } else if (scanned_device_infos_from_current_scan_.size() > 1) {
        expected_event_type = HostScannerImpl::HostScanResultEventType::
            NOTIFICATION_SHOWN_MULTIPLE_HOSTS;
      }
      histogram_tester_.ExpectUniqueSample(
          "InstantTethering.HostScanResult", expected_event_type,
          num_expected_host_scan_histogram_samples);
    }
  }

  void VerifyScanResultsMatchCache() {
    std::vector<ScannedDeviceInfo> combined_device_infos =
        scanned_device_infos_from_current_scan_;
    for (const auto& previous_scan_result :
         scanned_device_infos_from_previous_scans_) {
      bool already_in_combined = false;
      for (const auto& combined_device_info : combined_device_infos) {
        if (previous_scan_result.device_id == combined_device_info.device_id) {
          already_in_combined = true;
          break;
        }
      }
      if (!already_in_combined) {
        combined_device_infos.push_back(previous_scan_result);
      }
    }

    ASSERT_EQ(combined_device_infos.size(), fake_host_scan_cache_->size());
    for (auto& scanned_device_info : combined_device_infos) {
      std::string tether_network_guid =
          device_id_tether_network_guid_map_->GetTetherNetworkGuidForDeviceId(
              scanned_device_info.device_id);
      const HostScanCacheEntry* entry =
          fake_host_scan_cache_->GetCacheEntry(tether_network_guid);
      ASSERT_TRUE(entry);
      VerifyScannedDeviceInfoAndCacheEntryAreEquivalent(scanned_device_info,
                                                        *entry);
    }
  }

  void VerifyScannedDeviceInfoAndCacheEntryAreEquivalent(
      const ScannedDeviceInfo& scanned_device_info,
      const HostScanCacheEntry& entry) {
    EXPECT_EQ(scanned_device_info.device_name, entry.device_name);

    const DeviceStatus& status = scanned_device_info.device_status.value();
    if (!status.has_cell_provider() || status.cell_provider().empty()) {
      EXPECT_EQ("unknown-carrier", entry.carrier);
    } else {
      EXPECT_EQ(status.cell_provider(), entry.carrier);
    }

    if (!status.has_battery_percentage() || status.battery_percentage() > 100) {
      EXPECT_EQ(100, entry.battery_percentage);
    } else if (status.battery_percentage() < 0) {
      EXPECT_EQ(0, entry.battery_percentage);
    } else {
      EXPECT_EQ(status.battery_percentage(), entry.battery_percentage);
    }

    if (!status.has_connection_strength() || status.connection_strength() > 4) {
      EXPECT_EQ(100, entry.signal_strength);
    } else if (status.connection_strength() < 0) {
      EXPECT_EQ(0, entry.signal_strength);
    } else {
      EXPECT_EQ(status.connection_strength() * 25, entry.signal_strength);
    }

    EXPECT_EQ(scanned_device_info.setup_required, entry.setup_required);
  }

  // Clears scan results from |scanned_device_infos_from_current_scan_| and
  // transfers them to |scanned_device_infos_from_previous_scans_|.
  void ClearCurrentScanResults() {
    scanned_device_infos_from_previous_scans_ =
        scanned_device_infos_from_current_scan_;
    scanned_device_infos_from_current_scan_.clear();
  }

  void StartConnectingToWifiNetwork() {
    std::stringstream ss;
    ss << "{" << "  \"GUID\": \"wifiNetworkGuid\"," << "  \"Type\": \""
       << shill::kTypeWifi << "\"," << "  \"State\": \""
       << shill::kStateConfiguration << "\"" << "}";

    helper_.ConfigureService(ss.str());
  }

  void SetScreenLockedState(bool is_locked) {
    session_manager_->SetSessionState(
        is_locked ? session_manager::SessionState::LOCKED
                  : session_manager::SessionState::LOGIN_PRIMARY);
  }

  NetworkStateHandler* network_state_handler() {
    return helper_.network_state_handler();
  }

  base::test::TaskEnvironment task_environment_;

  NetworkStateTestHelper helper_{/*use_default_devices_and_services=*/true};
  const multidevice::RemoteDeviceRefList test_devices_;
  const std::vector<ScannedDeviceInfo> test_scanned_device_infos;

  std::unique_ptr<device_sync::FakeDeviceSyncClient> fake_device_sync_client_;
  std::unique_ptr<secure_channel::SecureChannelClient>
      fake_secure_channel_client_;
  std::unique_ptr<session_manager::SessionManager> session_manager_;
  std::unique_ptr<FakeTetherHostFetcher> fake_tether_host_fetcher_;
  std::unique_ptr<MockTetherHostResponseRecorder>
      mock_tether_host_response_recorder_;
  std::unique_ptr<GmsCoreNotificationsStateTrackerImpl>
      gms_core_notifications_state_tracker_;
  std::unique_ptr<FakeNotificationPresenter> fake_notification_presenter_;
  // TODO(hansberry): Use a fake for this when a real mapping scheme is created.
  std::unique_ptr<DeviceIdTetherNetworkGuidMap>
      device_id_tether_network_guid_map_;
  std::unique_ptr<FakeHostScanCache> fake_host_scan_cache_;
  std::unique_ptr<FakeConnectionPreserver> fake_connection_preserver_;

  std::unique_ptr<base::SimpleTestClock> test_clock_;
  std::unique_ptr<TestObserver> test_observer_;

  raw_ptr<FakeTetherAvailabilityOperationOrchestratorFactory>
      fake_tether_availability_operation_factory_;

  std::vector<ScannedDeviceInfo> scanned_device_infos_from_current_scan_;
  std::vector<ScannedDeviceInfo> scanned_device_infos_from_previous_scans_;

  std::unique_ptr<HostScanner> host_scanner_;

  base::HistogramTester histogram_tester_;
};

TEST_F(HostScannerImplTest, DISABLED_TestScan_ConnectingToExistingNetwork) {
  StartConnectingToWifiNetwork();
  EXPECT_TRUE(network_state_handler()->DefaultNetwork());

  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      1u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      2u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      3u /* test_device_index */, true /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest,
       DISABLED_TestNotificationNotDisplayedMultipleTimes) {
  StartConnectingToWifiNetwork();
  EXPECT_TRUE(network_state_handler()->DefaultNetwork());

  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      1u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      2u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      3u /* test_device_index */, true /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest,
       DISABLED_TestNotificationDisplaysMultipleTimesWhenUnlocked) {
  // Start a scan and receive a result.
  host_scanner_->StartScan();
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, true /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN);
  EXPECT_FALSE(host_scanner_->IsScanActive());

  // The scan has completed, and the "single hotspot nearby" notification should
  // be shown. Remove it.
  EXPECT_EQ(
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN,
      fake_notification_presenter_->GetPotentialHotspotNotificationState());
  fake_notification_presenter_->RemovePotentialHotspotNotification();

  // Now, simulate locking then unlocking the device.
  SetScreenLockedState(true /* is_locked */);
  SetScreenLockedState(false /* is_locked */);

  // Start another scan and receive a result.
  host_scanner_->StartScan();
  ASSERT_EQ(2u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[1],
      0u /* test_device_index */, true /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN,
      2 /* num_expected_host_scan_histogram_samples */);
  EXPECT_FALSE(host_scanner_->IsScanActive());

  // The notification should be visible since the device was locked and unlocked
  // since the last time it was shown.
  EXPECT_EQ(
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN,
      fake_notification_presenter_->GetPotentialHotspotNotificationState());
}

TEST_F(HostScannerImplTest, DISABLED_TestScan_ResultsFromAllDevices) {
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      1u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      2u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      3u /* test_device_index */, true /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest, DISABLED_TestScan_ResultsFromNoDevices) {
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  fake_tether_availability_operation_factory_->created_orchestrators()[0]
      ->SendScannedDeviceListUpdate(std::vector<ScannedDeviceInfo>(),
                                    true /* is_final_scan_result */);
  EXPECT_EQ(0u, fake_host_scan_cache_->size());
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest, DISABLED_StopScan) {
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  host_scanner_->StopScan();
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest, DISABLED_TestScan_ResultsFromSomeDevices) {
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // Only receive updates from the 0th and 1st device.
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      1u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());

  fake_tether_availability_operation_factory_->created_orchestrators()[0]
      ->SendScannedDeviceListUpdate(scanned_device_infos_from_current_scan_,
                                    true /* is_final_scan_result */);
  EXPECT_EQ(scanned_device_infos_from_current_scan_.size(),
            fake_host_scan_cache_->size());
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest,
       DISABLED_TestScan_MultipleScanCallsDuringOperation) {
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // Call StartScan again before the final scan result has been received. This
  // should be a no-op.
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // No devices should have been received yet.
  EXPECT_EQ(0u, fake_host_scan_cache_->size());

  // Receive updates from the 0th device.
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // Call StartScan again after a scan result has been received but before
  // the final scan result ha been received. This should be a no-op.
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // The scanned devices so far should be the same (i.e., they should not have
  // been affected by the extra call to StartScan()).
  EXPECT_EQ(scanned_device_infos_from_current_scan_.size(),
            fake_host_scan_cache_->size());

  // Finally, finish the scan.
  fake_tether_availability_operation_factory_->created_orchestrators()[0]
      ->SendScannedDeviceListUpdate(scanned_device_infos_from_current_scan_,
                                    true /* is_final_scan_result */);
  EXPECT_EQ(scanned_device_infos_from_current_scan_.size(),
            fake_host_scan_cache_->size());
  EXPECT_FALSE(host_scanner_->IsScanActive());
}

TEST_F(HostScannerImplTest, DISABLED_TestScan_MultipleCompleteScanSessions) {
  // Start the first scan session.
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(1u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // Receive updates from devices 0-2.
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      1u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[0],
      2u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // Finish the first scan.
  fake_tether_availability_operation_factory_->created_orchestrators()[0]
      ->SendScannedDeviceListUpdate(scanned_device_infos_from_current_scan_,
                                    true /* is_final_scan_result */);
  EXPECT_EQ(scanned_device_infos_from_current_scan_.size(),
            fake_host_scan_cache_->size());
  EXPECT_FALSE(host_scanner_->IsScanActive());

  // The notification should still be visible.
  EXPECT_EQ(
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN,
      fake_notification_presenter_->GetPotentialHotspotNotificationState());

  // Now, start the second scan session. Since the notification was still
  // visible from the first scan session, it should still be able to be shown
  // for the second scan session.
  ClearCurrentScanResults();
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(2u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // The cache should be unaffected by the start of a new scan.
  VerifyScanResultsMatchCache();

  // Receive results from devices 0 only. Results from devices 1 and 2 should
  // still be present in the cache even though no results have been received
  // from that device during this scan session.
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[1],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          MULTIPLE_HOTSPOTS_NEARBY_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  VerifyScanResultsMatchCache();

  // Finish the second scan. Since results were not received from devices 1 or
  // 2, previous results from those devices should now be removed from the
  // cache.
  fake_tether_availability_operation_factory_->created_orchestrators()[1]
      ->SendScannedDeviceListUpdate(scanned_device_infos_from_current_scan_,
                                    true /* is_final_scan_result */);
  EXPECT_FALSE(host_scanner_->IsScanActive());

  // The notification should have been changed to a single hotspot. Remove it
  // before starting the third scan session.
  EXPECT_EQ(
      NotificationPresenter::PotentialHotspotNotificationState::
          SINGLE_HOTSPOT_NEARBY_SHOWN,
      fake_notification_presenter_->GetPotentialHotspotNotificationState());
  fake_notification_presenter_->RemovePotentialHotspotNotification();

  // Now, start the third scan session. Since the notification was hidden before
  // the session started, it should not be shown for this session.
  ClearCurrentScanResults();
  EXPECT_FALSE(host_scanner_->IsScanActive());
  host_scanner_->StartScan();
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ASSERT_EQ(3u,
            fake_tether_availability_operation_factory_->created_orchestrators()
                .size());
  EXPECT_TRUE(host_scanner_->IsScanActive());

  // The cache should be unaffected by the start of a new scan.
  VerifyScanResultsMatchCache();

  // Receive results from devices 0, 2 and 3. Results from device 1 should still
  // be present in the cache even though no results have been received from that
  // device during this scan session.
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[2],
      0u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[2],
      2u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  ReceiveScanResultAndVerifySuccess(
      fake_tether_availability_operation_factory_->created_orchestrators()[2],
      3u /* test_device_index */, false /* is_final_scan_result */,
      NotificationPresenter::PotentialHotspotNotificationState::
          NO_HOTSPOT_NOTIFICATION_SHOWN);
  EXPECT_TRUE(host_scanner_->IsScanActive());
  VerifyScanResultsMatchCache();

  // Finish the second scan. Since results were not received from device 1,
  // previous results from device 1 should now be removed from the cache.
  fake_tether_availability_operation_factory_->created_orchestrators()[2]
      ->SendScannedDeviceListUpdate(scanned_device_infos_from_current_scan_,
                                    true /* is_final_scan_result */);
  EXPECT_FALSE(host_scanner_->IsScanActive());

  ClearCurrentScanResults();
  VerifyScanResultsMatchCache();
}

}  // namespace tether

}  // namespace ash