File: tether_connector_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 (875 lines) | stat: -rw-r--r-- 38,424 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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
// Copyright 2017 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/tether_connector_impl.h"

#include <memory>

#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "chromeos/ash/components/multidevice/remote_device_ref.h"
#include "chromeos/ash/components/multidevice/remote_device_test_util.h"
#include "chromeos/ash/components/network/network_connection_handler.h"
#include "chromeos/ash/components/network/network_handler_test_helper.h"
#include "chromeos/ash/components/network/network_state.h"
#include "chromeos/ash/components/network/network_state_handler.h"
#include "chromeos/ash/components/network/network_state_test_helper.h"
#include "chromeos/ash/components/tether/connect_tethering_operation.h"
#include "chromeos/ash/components/tether/device_id_tether_network_guid_map.h"
#include "chromeos/ash/components/tether/fake_active_host.h"
#include "chromeos/ash/components/tether/fake_disconnect_tethering_request_sender.h"
#include "chromeos/ash/components/tether/fake_host_connection.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/fake_wifi_hotspot_connector.h"
#include "chromeos/ash/components/tether/fake_wifi_hotspot_disconnector.h"
#include "chromeos/ash/components/tether/host_connection_metrics_logger.h"
#include "chromeos/ash/components/tether/mock_host_connection_metrics_logger.h"
#include "chromeos/ash/components/tether/mock_tether_host_response_recorder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

using testing::Eq;
using testing::Optional;
using testing::StrictMock;

namespace ash {

namespace tether {

namespace {

const char kSuccessResult[] = "success";

const char kSsid[] = "ssid";
const char kPassword[] = "password";

const char kWifiNetworkGuid[] = "wifiNetworkGuid";

std::string CreateWifiConfigurationJsonString() {
  std::stringstream ss;
  ss << "{" << "  \"GUID\": \"" << kWifiNetworkGuid << "\"," << "  \"Type\": \""
     << shill::kTypeWifi << "\"," << "  \"State\": \"" << shill::kStateIdle
     << "\"" << "}";
  return ss.str();
}

using ::testing::Optional;

class FakeConnectTetheringOperation : public ConnectTetheringOperation {
 public:
  FakeConnectTetheringOperation(
      const TetherHost& tether_host,
      HostConnection::Factory* host_connection_factory,
      bool setup_required)
      : ConnectTetheringOperation(tether_host,
                                  host_connection_factory,
                                  setup_required),
        tether_host_(tether_host),
        setup_required_(setup_required) {}

  ~FakeConnectTetheringOperation() override = default;

  void NotifyConnectTetheringRequestSent() {
    ConnectTetheringOperation::NotifyConnectTetheringRequestSent();
  }

  void SendSuccessfulResponse(const std::string& ssid,
                              const std::string& password) {
    NotifyObserversOfSuccessfulResponse(ssid, password);
  }

  void SendFailedResponse(
      ConnectTetheringOperation::HostResponseErrorCode error_code) {
    NotifyObserversOfConnectionFailure(error_code);
  }

  TetherHost tether_host() { return tether_host_; }

  bool setup_required() { return setup_required_; }

 private:
  TetherHost tether_host_;
  bool setup_required_;
};

class FakeConnectTetheringOperationFactory
    : public ConnectTetheringOperation::Factory {
 public:
  FakeConnectTetheringOperationFactory() = default;
  ~FakeConnectTetheringOperationFactory() override = default;

  std::vector<raw_ptr<FakeConnectTetheringOperation, VectorExperimental>>&
  created_operations() {
    return created_operations_;
  }

 protected:
  // ConnectTetheringOperation::Factory:
  std::unique_ptr<ConnectTetheringOperation> CreateInstance(
      const TetherHost& tether_host,
      raw_ptr<HostConnection::Factory> host_connection_factory,
      bool setup_required) override {
    FakeConnectTetheringOperation* operation =
        new FakeConnectTetheringOperation(tether_host, host_connection_factory,
                                          setup_required);
    created_operations_.push_back(operation);
    return base::WrapUnique(operation);
  }

 private:
  std::vector<raw_ptr<FakeConnectTetheringOperation, VectorExperimental>>
      created_operations_;
};

}  // namespace

class TetherConnectorImplTest : public testing::Test {
 public:
  TetherConnectorImplTest()
      : test_devices_(multidevice::CreateRemoteDeviceRefListForTest(2u)) {}

  TetherConnectorImplTest(const TetherConnectorImplTest&) = delete;
  TetherConnectorImplTest& operator=(const TetherConnectorImplTest&) = delete;

  ~TetherConnectorImplTest() override = default;

  void SetUp() override {
    NetworkHandler::Get()->network_state_handler()->SetTetherTechnologyState(
        NetworkStateHandler::TECHNOLOGY_ENABLED);

    fake_operation_factory_ =
        base::WrapUnique(new FakeConnectTetheringOperationFactory());
    ConnectTetheringOperation::Factory::SetFactoryForTesting(
        fake_operation_factory_.get());
    fake_wifi_hotspot_connector_ =
        std::make_unique<FakeWifiHotspotConnector>(NetworkHandler::Get());
    fake_active_host_ = std::make_unique<FakeActiveHost>();
    fake_tether_host_fetcher_ =
        std::make_unique<FakeTetherHostFetcher>(test_devices_[0]);
    mock_tether_host_response_recorder_ =
        std::make_unique<MockTetherHostResponseRecorder>();
    device_id_tether_network_guid_map_ =
        std::make_unique<DeviceIdTetherNetworkGuidMap>();
    fake_host_scan_cache_ = std::make_unique<FakeHostScanCache>();
    fake_notification_presenter_ =
        std::make_unique<FakeNotificationPresenter>();
    mock_host_connection_metrics_logger_ =
        base::WrapUnique(new StrictMock<MockHostConnectionMetricsLogger>(
            fake_active_host_.get()));
    fake_disconnect_tethering_request_sender_ =
        std::make_unique<FakeDisconnectTetheringRequestSender>();
    fake_wifi_hotspot_disconnector_ =
        std::make_unique<FakeWifiHotspotDisconnector>();
    fake_host_connection_factory_ =
        std::make_unique<FakeHostConnection::Factory>();

    result_.clear();

    tether_connector_ = base::WrapUnique(new TetherConnectorImpl(
        fake_host_connection_factory_.get(),
        NetworkHandler::Get()->network_state_handler(),
        fake_wifi_hotspot_connector_.get(), fake_active_host_.get(),
        fake_tether_host_fetcher_.get(),
        mock_tether_host_response_recorder_.get(),
        device_id_tether_network_guid_map_.get(), fake_host_scan_cache_.get(),
        fake_notification_presenter_.get(),
        mock_host_connection_metrics_logger_.get(),
        fake_disconnect_tethering_request_sender_.get(),
        fake_wifi_hotspot_disconnector_.get()));

    SetUpTetherNetworks();
  }

  std::string GetTetherNetworkGuid(const std::string& device_id) {
    return device_id_tether_network_guid_map_->GetTetherNetworkGuidForDeviceId(
        device_id);
  }

  void SetUpTetherNetworks() {
    // Add a tether network corresponding to both of the test devices. These
    // networks are expected to be added already before
    // TetherConnectorImpl::ConnectToNetwork is called.
    AddTetherNetwork(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
                     "TetherNetworkName1", "TetherNetworkCarrier1",
                     85 /* battery_percentage */, 75 /* signal_strength */,
                     true /* has_connected_to_host */,
                     false /* setup_required */);
    AddTetherNetwork(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()),
                     "TetherNetworkName2", "TetherNetworkCarrier2",
                     90 /* battery_percentage */, 50 /* signal_strength */,
                     true /* has_connected_to_host */,
                     true /* setup_required */);
  }

  virtual void AddTetherNetwork(const std::string& tether_network_guid,
                                const std::string& device_name,
                                const std::string& carrier,
                                int battery_percentage,
                                int signal_strength,
                                bool has_connected_to_host,
                                bool setup_required) {
    NetworkHandler::Get()->network_state_handler()->AddTetherNetworkState(
        tether_network_guid, device_name, carrier, battery_percentage,
        signal_strength, has_connected_to_host);
    fake_host_scan_cache_->SetHostScanResult(
        *HostScanCacheEntry::Builder()
             .SetTetherNetworkGuid(tether_network_guid)
             .SetDeviceName(device_name)
             .SetCarrier(carrier)
             .SetBatteryPercentage(battery_percentage)
             .SetSignalStrength(signal_strength)
             .SetSetupRequired(setup_required)
             .Build());
  }

  void SuccessfullyJoinWifiNetwork() {
    helper_.ConfigureService(CreateWifiConfigurationJsonString());
    fake_wifi_hotspot_connector_->CallMostRecentCallback(kWifiNetworkGuid);
  }

  void SuccessCallback() { result_ = kSuccessResult; }

  void ErrorCallback(const std::string& error_name) { result_ = error_name; }

  void CallConnect(const std::string& tether_network_guid) {
    tether_connector_->ConnectToNetwork(
        tether_network_guid,
        base::BindOnce(&TetherConnectorImplTest::SuccessCallback,
                       base::Unretained(this)),
        base::BindOnce(&TetherConnectorImplTest::ErrorCallback,
                       base::Unretained(this)));
  }

  void VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode response_code,
      bool setup_required,
      HostConnectionMetricsLogger::ConnectionToHostResult expected_event_type,
      std::optional<HostConnectionMetricsLogger::ConnectionToHostInternalError>
          expected_internal_error) {
    EXPECT_CALL(*mock_tether_host_response_recorder_,
                RecordSuccessfulConnectTetheringResponse(testing::_))
        .Times(0);

    EXPECT_CALL(*mock_host_connection_metrics_logger_,
                RecordConnectionToHostResult(
                    expected_event_type,
                    test_devices_[setup_required ? 1 : 0].GetDeviceId(),
                    expected_internal_error));

    EXPECT_FALSE(
        fake_notification_presenter_->is_setup_required_notification_shown());

    // test_devices_[0] does not require first-time setup, but test_devices_[1]
    // does require first-time setup. See SetUpTetherNetworks().
    multidevice::RemoteDeviceRef test_device =
        test_devices_[setup_required ? 1 : 0];

    fake_tether_host_fetcher_->SetTetherHost(test_device);
    fake_host_connection_factory_->SetupConnectionAttempt(
        TetherHost(test_device));
    CallConnect(GetTetherNetworkGuid(test_device.GetDeviceId()));
    EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
              fake_active_host_->GetActiveHostStatus());
    EXPECT_EQ(test_device.GetDeviceId(),
              fake_active_host_->GetActiveHostDeviceId());
    EXPECT_EQ(GetTetherNetworkGuid(test_device.GetDeviceId()),
              fake_active_host_->GetTetherNetworkGuid());
    EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());
    EXPECT_FALSE(
        fake_notification_presenter_->is_setup_required_notification_shown());
    EXPECT_EQ(
        setup_required,
        fake_operation_factory_->created_operations()[0]->setup_required());

    // Simulate a failed connection attempt (either the host cannot provide
    // tethering at this time or a timeout occurs).
    EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());
    fake_operation_factory_->created_operations()[0]
        ->NotifyConnectTetheringRequestSent();
    fake_operation_factory_->created_operations()[0]->SendFailedResponse(
        response_code);

    EXPECT_FALSE(
        fake_notification_presenter_->is_setup_required_notification_shown());

    // The failure should have resulted in the host being disconnected.
    EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED,
              fake_active_host_->GetActiveHostStatus());
    EXPECT_EQ(NetworkConnectionHandler::kErrorConnectFailed,
              GetResultAndReset());
    EXPECT_TRUE(fake_notification_presenter_
                    ->is_connection_failed_notification_shown());
  }

  std::string GetResultAndReset() {
    std::string result;
    result.swap(result_);
    return result;
  }

  const multidevice::RemoteDeviceRefList test_devices_;
  base::test::SingleThreadTaskEnvironment task_environment_;
  NetworkHandlerTestHelper helper_{};

  std::unique_ptr<FakeConnectTetheringOperationFactory> fake_operation_factory_;
  std::unique_ptr<FakeWifiHotspotConnector> fake_wifi_hotspot_connector_;
  std::unique_ptr<FakeActiveHost> fake_active_host_;
  std::unique_ptr<FakeHostConnection::Factory> fake_host_connection_factory_;
  std::unique_ptr<FakeTetherHostFetcher> fake_tether_host_fetcher_;
  std::unique_ptr<MockTetherHostResponseRecorder>
      mock_tether_host_response_recorder_;
  // 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<FakeNotificationPresenter> fake_notification_presenter_;
  std::unique_ptr<StrictMock<MockHostConnectionMetricsLogger>>
      mock_host_connection_metrics_logger_;
  std::unique_ptr<FakeDisconnectTetheringRequestSender>
      fake_disconnect_tethering_request_sender_;
  std::unique_ptr<FakeWifiHotspotDisconnector> fake_wifi_hotspot_disconnector_;

  std::string result_;
  base::HistogramTester histogram_tester_;

  std::unique_ptr<TetherConnectorImpl> tether_connector_;
};

TEST_F(TetherConnectorImplTest, TestCannotFetchDevice) {
  fake_tether_host_fetcher_->SetTetherHost(std::nullopt);
  // Base64-encoded version of "nonexistentDeviceId".
  const char kNonexistentDeviceId[] = "bm9uZXhpc3RlbnREZXZpY2VJZA==";

  EXPECT_CALL(
      *mock_host_connection_metrics_logger_,
      RecordConnectionToHostResult(
          HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
          kNonexistentDeviceId,
          std::optional(
              HostConnectionMetricsLogger::ConnectionToHostInternalError::
                  CLIENT_CONNECTION_INTERNAL_ERROR)));

  CallConnect(GetTetherNetworkGuid(kNonexistentDeviceId));

  // Since an invalid device ID was used, no connection should have been
  // started.
  EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(NetworkConnectionHandler::kErrorConnectFailed, GetResultAndReset());
  EXPECT_TRUE(
      fake_notification_presenter_->is_connection_failed_notification_shown());
}

TEST_F(TetherConnectorImplTest, TestCancelWhileOperationActive) {
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::
                      USER_CANCELLATION,
                  test_devices_[0].GetDeviceId(), Eq(std::nullopt)));

  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());

  // Simulate a failed connection attempt (either the host cannot provide
  // tethering at this time or a timeout occurs).
  EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());
  EXPECT_FALSE(
      fake_operation_factory_->created_operations()[0]->setup_required());
  tether_connector_->CancelConnectionAttempt(
      GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));

  EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(NetworkConnectionHandler::kErrorConnectCanceled,
            GetResultAndReset());
  EXPECT_EQ(
      std::vector<std::string>{test_devices_[0].GetDeviceId()},
      fake_disconnect_tethering_request_sender_->device_ids_sent_requests());
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_SetupNotRequired) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::UNKNOWN_ERROR,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      std::optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                        UNKNOWN_ERROR));
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_SetupRequired) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::UNKNOWN_ERROR,
      true /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      std::optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                        UNKNOWN_ERROR));
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_ProvisioningFailed) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::PROVISIONING_FAILED,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::PROVISIONING_FAILURE,
      std::nullopt);
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_TetheringTimeout_SetupNotRequired) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::TETHERING_TIMEOUT,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      std::optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                        TETHERING_TIMED_OUT_FIRST_TIME_SETUP_NOT_REQUIRED));
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_TetheringTimeout_SetupRequired) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::TETHERING_TIMEOUT,
      true /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      std::optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                        TETHERING_TIMED_OUT_FIRST_TIME_SETUP_REQUIRED));
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_TetheringUnsupported) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::TETHERING_UNSUPPORTED,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::
          TETHERING_UNSUPPORTED,
      std::nullopt);
}

TEST_F(TetherConnectorImplTest, TestConnectTetheringOperationFails_NoCellData) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::NO_CELL_DATA,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::NO_CELLULAR_DATA,
      std::nullopt);
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_EnableHotspotFailed) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::ENABLING_HOTSPOT_FAILED,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      std::optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                        ENABLING_HOTSPOT_FAILED));
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_EnableHotspotTimeout) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::
          ENABLING_HOTSPOT_TIMEOUT,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      std::optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                        ENABLING_HOTSPOT_TIMEOUT));
}

TEST_F(TetherConnectorImplTest, TestConnectTetheringOperationFails_NoResponse) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::NO_RESPONSE,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      HostConnectionMetricsLogger::ConnectionToHostInternalError::
          SUCCESSFUL_REQUEST_BUT_NO_RESPONSE);
}

TEST_F(TetherConnectorImplTest,
       TestConnectTetheringOperationFails_InvalidHotspotCredentials) {
  VerifyConnectTetheringOperationFails(
      ConnectTetheringOperation::HostResponseErrorCode::
          INVALID_HOTSPOT_CREDENTIALS,
      false /* setup_required */,
      HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
      HostConnectionMetricsLogger::ConnectionToHostInternalError::
          INVALID_HOTSPOT_CREDENTIALS);
}

TEST_F(TetherConnectorImplTest,
       ConnectionToHostFailedNotificationRemovedWhenConnectionStarts) {
  // Start with the "connection to host failed" notification showing.
  fake_notification_presenter_->NotifyConnectionToHostFailed();

  // Starting a connection should result in it being removed.
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());
}

TEST_F(TetherConnectorImplTest, TestConnectingToWifiFails) {
  EXPECT_CALL(
      *mock_host_connection_metrics_logger_,
      RecordConnectionToHostResult(
          HostConnectionMetricsLogger::ConnectionToHostResult::INTERNAL_ERROR,
          test_devices_[0].GetDeviceId(),
          Optional(HostConnectionMetricsLogger::ConnectionToHostInternalError::
                       CLIENT_CONNECTION_TIMEOUT)));

  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());

  // Receive a successful response. We should still be connecting.
  EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());
  EXPECT_FALSE(
      fake_operation_factory_->created_operations()[0]->setup_required());
  fake_operation_factory_->created_operations()[0]
      ->NotifyConnectTetheringRequestSent();
  fake_operation_factory_->created_operations()[0]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());

  // |fake_wifi_hotspot_connector_| should have received the SSID and password
  // above. Verify this, then return an empty string, signaling a failure to
  // connect.
  EXPECT_EQ(kSsid, fake_wifi_hotspot_connector_->most_recent_ssid());
  EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password());
  EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(),
            fake_wifi_hotspot_connector_->most_recent_tether_network_guid());
  fake_wifi_hotspot_connector_->CallMostRecentCallback(base::unexpected(
      WifiHotspotConnector::WifiHotspotConnectionError::kTimeout));

  // The failure should have resulted in the host being disconnected.
  EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(NetworkConnectionHandler::kErrorConnectFailed, GetResultAndReset());
  EXPECT_TRUE(
      fake_notification_presenter_->is_connection_failed_notification_shown());
}

TEST_F(TetherConnectorImplTest, TestCancelWhileConnectingToWifi) {
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::
                      USER_CANCELLATION,
                  test_devices_[0].GetDeviceId(), Eq(std::nullopt)));

  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());

  // Receive a successful response. We should still be connecting.
  EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());
  EXPECT_FALSE(
      fake_operation_factory_->created_operations()[0]->setup_required());
  fake_operation_factory_->created_operations()[0]
      ->NotifyConnectTetheringRequestSent();
  fake_operation_factory_->created_operations()[0]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());

  tether_connector_->CancelConnectionAttempt(
      GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));

  EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(NetworkConnectionHandler::kErrorConnectCanceled,
            GetResultAndReset());
  EXPECT_EQ(
      std::vector<std::string>{test_devices_[0].GetDeviceId()},
      fake_disconnect_tethering_request_sender_->device_ids_sent_requests());
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());

  // Now, simulate the Wi-Fi connection connecting. |tether_connector_| should
  // request that the connection be disconnected.
  SuccessfullyJoinWifiNetwork();
  EXPECT_EQ(
      kWifiNetworkGuid,
      fake_wifi_hotspot_disconnector_->last_disconnected_wifi_network_guid());
}

MATCHER_P(HasID, id, "") {
  return true;
}

TEST_F(TetherConnectorImplTest, TestSuccessfulConnection) {
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::SUCCESS,
                  test_devices_[0].GetDeviceId(), Eq(std::nullopt)));

  EXPECT_CALL(
      *mock_tether_host_response_recorder_,
      RecordSuccessfulConnectTetheringResponse(test_devices_[0].GetDeviceId()));

  fake_tether_host_fetcher_->SetTetherHost(test_devices_[0]);
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());
  EXPECT_FALSE(
      fake_notification_presenter_->is_setup_required_notification_shown());

  // Receive a successful response. We should still be connecting.
  EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());
  EXPECT_FALSE(
      fake_operation_factory_->created_operations()[0]->setup_required());
  fake_operation_factory_->created_operations()[0]
      ->NotifyConnectTetheringRequestSent();
  fake_operation_factory_->created_operations()[0]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());

  // |fake_wifi_hotspot_connector_| should have received the SSID and password
  // above. Verify this, then return the GUID corresponding to the connected
  // Wi-Fi network.
  EXPECT_EQ(kSsid, fake_wifi_hotspot_connector_->most_recent_ssid());
  EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password());
  EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(),
            fake_wifi_hotspot_connector_->most_recent_tether_network_guid());

  SuccessfullyJoinWifiNetwork();

  // The active host should now be connected.
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTED,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_EQ(kWifiNetworkGuid, fake_active_host_->GetWifiNetworkGuid());

  EXPECT_EQ(kSuccessResult, GetResultAndReset());
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());
}

TEST_F(TetherConnectorImplTest, TestSuccessfulConnection_SetupRequired) {
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::SUCCESS,
                  test_devices_[1].GetDeviceId(), Eq(std::nullopt)));
  EXPECT_FALSE(
      fake_notification_presenter_->is_setup_required_notification_shown());

  fake_tether_host_fetcher_->SetTetherHost(test_devices_[1]);
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()));
  EXPECT_FALSE(
      fake_notification_presenter_->is_setup_required_notification_shown());
  EXPECT_TRUE(
      fake_operation_factory_->created_operations()[0]->setup_required());

  fake_operation_factory_->created_operations()[0]
      ->NotifyConnectTetheringRequestSent();
  EXPECT_TRUE(
      fake_notification_presenter_->is_setup_required_notification_shown());

  fake_operation_factory_->created_operations()[0]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_TRUE(
      fake_notification_presenter_->is_setup_required_notification_shown());

  SuccessfullyJoinWifiNetwork();

  EXPECT_FALSE(
      fake_notification_presenter_->is_setup_required_notification_shown());

  EXPECT_EQ(kSuccessResult, GetResultAndReset());
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());
}

TEST_F(TetherConnectorImplTest,
       TestNewConnectionAttemptDuringOperation_DifferentDevice) {
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::
                      USER_CANCELLATION,
                  test_devices_[0].GetDeviceId(), Eq(std::nullopt)));
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::SUCCESS,
                  test_devices_[1].GetDeviceId(), Eq(std::nullopt)));

  fake_tether_host_fetcher_->SetTetherHost(test_devices_[0]);
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));

  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());

  // An operation should have been created.
  EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());

  // Before the created operation replies, start a new connection to device 1.
  fake_tether_host_fetcher_->SetTetherHost(test_devices_[1]);
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()));

  // The first connection attempt should have resulted in a connect canceled
  // error.
  EXPECT_EQ(NetworkConnectionHandler::kErrorConnectCanceled,
            GetResultAndReset());
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());

  // Now, the active host should be the second device.
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[1].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());

  // A second operation should have been created.
  EXPECT_EQ(2u, fake_operation_factory_->created_operations().size());

  // No connection should have been started.
  EXPECT_TRUE(fake_wifi_hotspot_connector_->most_recent_ssid().empty());
  EXPECT_TRUE(fake_wifi_hotspot_connector_->most_recent_password().empty());
  EXPECT_TRUE(
      fake_wifi_hotspot_connector_->most_recent_tether_network_guid().empty());

  // The second operation replies successfully, and this response should
  // result in a Wi-Fi connection attempt.
  fake_operation_factory_->created_operations()[1]
      ->NotifyConnectTetheringRequestSent();
  fake_operation_factory_->created_operations()[1]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_EQ(kSsid, fake_wifi_hotspot_connector_->most_recent_ssid());
  EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password());
  EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(),
            fake_wifi_hotspot_connector_->most_recent_tether_network_guid());

  SuccessfullyJoinWifiNetwork();
}

TEST_F(TetherConnectorImplTest,
       TestNewConnectionAttemptDuringWifiConnection_DifferentDevice) {
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::
                      USER_CANCELLATION,
                  test_devices_[0].GetDeviceId(), Eq(std::nullopt)));
  EXPECT_CALL(*mock_host_connection_metrics_logger_,
              RecordConnectionToHostResult(
                  HostConnectionMetricsLogger::ConnectionToHostResult::SUCCESS,
                  test_devices_[1].GetDeviceId(), Eq(std::nullopt)));

  fake_tether_host_fetcher_->SetTetherHost(test_devices_[0]);
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[0].GetDeviceId()));

  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[0].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());

  EXPECT_EQ(1u, fake_operation_factory_->created_operations().size());
  fake_operation_factory_->created_operations()[0]
      ->NotifyConnectTetheringRequestSent();
  fake_operation_factory_->created_operations()[0]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(kSsid, fake_wifi_hotspot_connector_->most_recent_ssid());
  EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password());
  EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(),
            fake_wifi_hotspot_connector_->most_recent_tether_network_guid());

  // While the connection to the Wi-Fi network is in progress, start a new
  // connection attempt.
  fake_tether_host_fetcher_->SetTetherHost(test_devices_[1]);
  fake_host_connection_factory_->SetupConnectionAttempt(
      TetherHost(test_devices_[0]));
  CallConnect(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()));

  // The first connection attempt should have resulted in a connect canceled
  // error.
  EXPECT_EQ(NetworkConnectionHandler::kErrorConnectCanceled,
            GetResultAndReset());
  EXPECT_FALSE(
      fake_notification_presenter_->is_connection_failed_notification_shown());

  // Connect successfully to the first Wi-Fi network. Even though a temporary
  // connection has succeeded, the active host should be CONNECTING to device 1.
  SuccessfullyJoinWifiNetwork();
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTING,
            fake_active_host_->GetActiveHostStatus());
  EXPECT_EQ(test_devices_[1].GetDeviceId(),
            fake_active_host_->GetActiveHostDeviceId());
  EXPECT_EQ(GetTetherNetworkGuid(test_devices_[1].GetDeviceId()),
            fake_active_host_->GetTetherNetworkGuid());
  EXPECT_TRUE(fake_active_host_->GetWifiNetworkGuid().empty());

  // The second operation replies successfully, and this response should
  // result in a Wi-Fi connection attempt.
  fake_operation_factory_->created_operations()[1]
      ->NotifyConnectTetheringRequestSent();
  fake_operation_factory_->created_operations()[1]->SendSuccessfulResponse(
      kSsid, kPassword);
  EXPECT_EQ(kSsid, fake_wifi_hotspot_connector_->most_recent_ssid());
  EXPECT_EQ(kPassword, fake_wifi_hotspot_connector_->most_recent_password());
  EXPECT_EQ(fake_active_host_->GetTetherNetworkGuid(),
            fake_wifi_hotspot_connector_->most_recent_tether_network_guid());

  SuccessfullyJoinWifiNetwork();
}

}  // namespace tether

}  // namespace ash