summaryrefslogtreecommitdiffstats
path: root/device/usb/mojo/device_impl_unittest.cc
blob: c6c2e495053e8461831093d9a0242b9811d83f2e (plain)
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/usb/mojo/device_impl.h"

#include <stddef.h>
#include <stdint.h>

#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "device/usb/mock_usb_device.h"
#include "device/usb/mock_usb_device_handle.h"
#include "device/usb/mojo/fake_permission_provider.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "net/base/io_buffer.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::Invoke;
using ::testing::_;

namespace device {
namespace usb {

namespace {

class ConfigBuilder {
 public:
  explicit ConfigBuilder(uint8_t value) { config_.configuration_value = value; }

  ConfigBuilder& AddInterface(uint8_t interface_number,
                              uint8_t alternate_setting,
                              uint8_t class_code,
                              uint8_t subclass_code,
                              uint8_t protocol_code) {
    UsbInterfaceDescriptor interface;
    interface.interface_number = interface_number;
    interface.alternate_setting = alternate_setting;
    interface.interface_class = class_code;
    interface.interface_subclass = subclass_code;
    interface.interface_protocol = protocol_code;
    config_.interfaces.push_back(interface);
    return *this;
  }

  const UsbConfigDescriptor& config() const { return config_; }

 private:
  UsbConfigDescriptor config_;
};

void ExpectOpenAndThen(OpenDeviceError expected,
                       const base::Closure& continuation,
                       OpenDeviceError error) {
  EXPECT_EQ(expected, error);
  continuation.Run();
}

void ExpectDeviceInfoAndThen(const std::string& guid,
                             uint16_t vendor_id,
                             uint16_t product_id,
                             const std::string& manufacturer_name,
                             const std::string& product_name,
                             const std::string& serial_number,
                             const base::Closure& continuation,
                             DeviceInfoPtr device_info) {
  EXPECT_EQ(guid, device_info->guid);
  EXPECT_EQ(vendor_id, device_info->vendor_id);
  EXPECT_EQ(product_id, device_info->product_id);
  EXPECT_EQ(manufacturer_name, device_info->manufacturer_name);
  EXPECT_EQ(product_name, device_info->product_name);
  EXPECT_EQ(serial_number, device_info->serial_number);
  continuation.Run();
}

void ExpectResultAndThen(bool expected_result,
                         const base::Closure& continuation,
                         bool actual_result) {
  EXPECT_EQ(expected_result, actual_result);
  continuation.Run();
}

void ExpectTransferInAndThen(TransferStatus expected_status,
                             const std::vector<uint8_t>& expected_bytes,
                             const base::Closure& continuation,
                             TransferStatus actual_status,
                             mojo::Array<uint8_t> actual_bytes) {
  EXPECT_EQ(expected_status, actual_status);
  ASSERT_EQ(expected_bytes.size(), actual_bytes.size());
  for (size_t i = 0; i < actual_bytes.size(); ++i) {
    EXPECT_EQ(expected_bytes[i], actual_bytes[i])
        << "Contents differ at index: " << i;
  }
  continuation.Run();
}

void ExpectPacketsOutAndThen(const std::vector<uint32_t>& expected_packets,
                             const base::Closure& continuation,
                             mojo::Array<IsochronousPacketPtr> actual_packets) {
  ASSERT_EQ(expected_packets.size(), actual_packets.size());
  for (size_t i = 0; i < expected_packets.size(); ++i) {
    EXPECT_EQ(expected_packets[i], actual_packets[i]->transferred_length)
        << "Packet lengths differ at index: " << i;
    EXPECT_EQ(TransferStatus::COMPLETED, actual_packets[i]->status)
        << "Packet at index " << i << " not completed.";
  }
  continuation.Run();
}

void ExpectPacketsInAndThen(const std::vector<uint8_t>& expected_bytes,
                            const std::vector<uint32_t>& expected_packets,
                            const base::Closure& continuation,
                            mojo::Array<uint8_t> actual_bytes,
                            mojo::Array<IsochronousPacketPtr> actual_packets) {
  ASSERT_EQ(expected_packets.size(), actual_packets.size());
  for (size_t i = 0; i < expected_packets.size(); ++i) {
    EXPECT_EQ(expected_packets[i], actual_packets[i]->transferred_length)
        << "Packet lengths differ at index: " << i;
    EXPECT_EQ(TransferStatus::COMPLETED, actual_packets[i]->status)
        << "Packet at index " << i << " not completed.";
  }
  ASSERT_EQ(expected_bytes.size(), actual_bytes.size());
  for (size_t i = 0; i < expected_bytes.size(); ++i) {
    EXPECT_EQ(expected_bytes[i], actual_bytes[i])
        << "Contents differ at index: " << i;
  }
  continuation.Run();
}

void ExpectTransferStatusAndThen(TransferStatus expected_status,
                                 const base::Closure& continuation,
                                 TransferStatus actual_status) {
  EXPECT_EQ(expected_status, actual_status);
  continuation.Run();
}

class USBDeviceImplTest : public testing::Test {
 public:
  USBDeviceImplTest()
      : message_loop_(new base::MessageLoop),
        is_device_open_(false),
        allow_reset_(false),
        current_config_(0) {}

  ~USBDeviceImplTest() override {}

 protected:
  MockUsbDevice& mock_device() { return *mock_device_.get(); }
  bool is_device_open() const { return is_device_open_; }
  MockUsbDeviceHandle& mock_handle() { return *mock_handle_.get(); }

  void set_allow_reset(bool allow_reset) { allow_reset_ = allow_reset; }

  // Creates a mock device and binds a Device proxy to a Device service impl
  // wrapping the mock device.
  DevicePtr GetMockDeviceProxy(uint16_t vendor_id,
                               uint16_t product_id,
                               const std::string& manufacturer,
                               const std::string& product,
                               const std::string& serial) {
    mock_device_ =
        new MockUsbDevice(vendor_id, product_id, manufacturer, product, serial);
    mock_handle_ = new MockUsbDeviceHandle(mock_device_.get());

    PermissionProviderPtr permission_provider;
    permission_provider_.Bind(mojo::GetProxy(&permission_provider));
    DevicePtr proxy;
    new DeviceImpl(mock_device_, std::move(permission_provider),
                   mojo::GetProxy(&proxy));

    // Set up mock handle calls to respond based on mock device configs
    // established by the test.
    ON_CALL(mock_device(), Open(_))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::OpenMockHandle));
    ON_CALL(mock_device(), GetActiveConfiguration())
        .WillByDefault(
            Invoke(this, &USBDeviceImplTest::GetActiveConfiguration));
    ON_CALL(mock_handle(), Close())
        .WillByDefault(Invoke(this, &USBDeviceImplTest::CloseMockHandle));
    ON_CALL(mock_handle(), SetConfiguration(_, _))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::SetConfiguration));
    ON_CALL(mock_handle(), ClaimInterface(_, _))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::ClaimInterface));
    ON_CALL(mock_handle(), ReleaseInterface(_, _))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::ReleaseInterface));
    ON_CALL(mock_handle(), SetInterfaceAlternateSetting(_, _, _))
        .WillByDefault(
            Invoke(this, &USBDeviceImplTest::SetInterfaceAlternateSetting));
    ON_CALL(mock_handle(), ResetDevice(_))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::ResetDevice));
    ON_CALL(mock_handle(), ControlTransfer(_, _, _, _, _, _, _, _, _, _))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::ControlTransfer));
    ON_CALL(mock_handle(), GenericTransfer(_, _, _, _, _, _))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::GenericTransfer));
    ON_CALL(mock_handle(), IsochronousTransferIn(_, _, _, _))
        .WillByDefault(Invoke(this, &USBDeviceImplTest::IsochronousTransferIn));
    ON_CALL(mock_handle(), IsochronousTransferOut(_, _, _, _, _))
        .WillByDefault(
            Invoke(this, &USBDeviceImplTest::IsochronousTransferOut));

    return proxy;
  }

  DevicePtr GetMockDeviceProxy() {
    return GetMockDeviceProxy(0x1234, 0x5678, "ACME", "Frobinator", "ABCDEF");
  }

  void AddMockConfig(const ConfigBuilder& builder) {
    const UsbConfigDescriptor& config = builder.config();
    DCHECK(!ContainsKey(mock_configs_, config.configuration_value));
    mock_configs_[config.configuration_value] = config;
  }

  void AddMockInboundData(const std::vector<uint8_t>& data) {
    mock_inbound_data_.push(data);
  }

  void AddMockInboundPackets(
      const std::vector<uint8_t>& data,
      const std::vector<UsbDeviceHandle::IsochronousPacket>& packets) {
    mock_inbound_data_.push(data);
    mock_inbound_packets_.push(packets);
  }

  void AddMockOutboundData(const std::vector<uint8_t>& data) {
    mock_outbound_data_.push(data);
  }

  void AddMockOutboundPackets(
      const std::vector<uint8_t>& data,
      const std::vector<UsbDeviceHandle::IsochronousPacket>& packets) {
    mock_outbound_data_.push(data);
    mock_outbound_packets_.push(packets);
  }

 private:
  void OpenMockHandle(const UsbDevice::OpenCallback& callback) {
    EXPECT_FALSE(is_device_open_);
    is_device_open_ = true;
    callback.Run(mock_handle_);
  }

  void CloseMockHandle() {
    EXPECT_TRUE(is_device_open_);
    is_device_open_ = false;
  }

  const UsbConfigDescriptor* GetActiveConfiguration() {
    if (current_config_ == 0) {
      return nullptr;
    } else {
      const auto it = mock_configs_.find(current_config_);
      EXPECT_TRUE(it != mock_configs_.end());
      return &it->second;
    }
  }

  void SetConfiguration(uint8_t value,
                        const UsbDeviceHandle::ResultCallback& callback) {
    if (mock_configs_.find(value) != mock_configs_.end()) {
      current_config_ = value;
      callback.Run(true);
    } else {
      callback.Run(false);
    }
  }

  void ClaimInterface(uint8_t interface_number,
                      const UsbDeviceHandle::ResultCallback& callback) {
    for (const auto& config : mock_configs_) {
      for (const auto& interface : config.second.interfaces) {
        if (interface.interface_number == interface_number) {
          claimed_interfaces_.insert(interface_number);
          callback.Run(true);
          return;
        }
      }
    }
    callback.Run(false);
  }

  void ReleaseInterface(uint8_t interface_number,
                        const UsbDeviceHandle::ResultCallback& callback) {
    if (ContainsKey(claimed_interfaces_, interface_number)) {
      claimed_interfaces_.erase(interface_number);
      callback.Run(true);
    } else {
      callback.Run(false);
    }
  }

  void SetInterfaceAlternateSetting(
      uint8_t interface_number,
      uint8_t alternate_setting,
      const UsbDeviceHandle::ResultCallback& callback) {
    for (const auto& config : mock_configs_) {
      for (const auto& interface : config.second.interfaces) {
        if (interface.interface_number == interface_number &&
            interface.alternate_setting == alternate_setting) {
          callback.Run(true);
          return;
        }
      }
    }
    callback.Run(false);
  }

  void ResetDevice(const UsbDeviceHandle::ResultCallback& callback) {
    callback.Run(allow_reset_);
  }

  void InboundTransfer(const UsbDeviceHandle::TransferCallback& callback) {
    ASSERT_GE(mock_inbound_data_.size(), 1u);
    const std::vector<uint8_t>& bytes = mock_inbound_data_.front();
    size_t length = bytes.size();
    scoped_refptr<net::IOBuffer> buffer = new net::IOBuffer(length);
    std::copy(bytes.begin(), bytes.end(), buffer->data());
    mock_inbound_data_.pop();
    callback.Run(USB_TRANSFER_COMPLETED, buffer, length);
  }

  void OutboundTransfer(scoped_refptr<net::IOBuffer> buffer,
                        size_t length,
                        const UsbDeviceHandle::TransferCallback& callback) {
    ASSERT_GE(mock_outbound_data_.size(), 1u);
    const std::vector<uint8_t>& bytes = mock_outbound_data_.front();
    ASSERT_EQ(bytes.size(), length);
    for (size_t i = 0; i < length; ++i) {
      EXPECT_EQ(bytes[i], buffer->data()[i]) << "Contents differ at index: "
                                             << i;
    }
    mock_outbound_data_.pop();
    callback.Run(USB_TRANSFER_COMPLETED, buffer, length);
  }

  void ControlTransfer(UsbEndpointDirection direction,
                       UsbDeviceHandle::TransferRequestType request_type,
                       UsbDeviceHandle::TransferRecipient recipient,
                       uint8_t request,
                       uint16_t value,
                       uint16_t index,
                       scoped_refptr<net::IOBuffer> buffer,
                       size_t length,
                       unsigned int timeout,
                       const UsbDeviceHandle::TransferCallback& callback) {
    if (direction == USB_DIRECTION_INBOUND)
      InboundTransfer(callback);
    else
      OutboundTransfer(buffer, length, callback);
  }

  void GenericTransfer(UsbEndpointDirection direction,
                       uint8_t endpoint,
                       scoped_refptr<net::IOBuffer> buffer,
                       size_t length,
                       unsigned int timeout,
                       const UsbDeviceHandle::TransferCallback& callback) {
    if (direction == USB_DIRECTION_INBOUND)
      InboundTransfer(callback);
    else
      OutboundTransfer(buffer, length, callback);
  }

  void IsochronousTransferIn(
      uint8_t endpoint_number,
      const std::vector<uint32_t>& packet_lengths,
      unsigned int timeout,
      const UsbDeviceHandle::IsochronousTransferCallback& callback) {
    ASSERT_FALSE(mock_inbound_data_.empty());
    const std::vector<uint8_t>& bytes = mock_inbound_data_.front();
    size_t length = bytes.size();
    scoped_refptr<net::IOBuffer> buffer = new net::IOBuffer(length);
    std::copy(bytes.begin(), bytes.end(), buffer->data());
    mock_inbound_data_.pop();

    ASSERT_FALSE(mock_inbound_packets_.empty());
    std::vector<UsbDeviceHandle::IsochronousPacket> packets =
        mock_inbound_packets_.front();
    ASSERT_EQ(packets.size(), packet_lengths.size());
    for (size_t i = 0; i < packets.size(); ++i) {
      EXPECT_EQ(packets[i].length, packet_lengths[i])
          << "Packet lengths differ at index: " << i;
    }
    mock_inbound_packets_.pop();

    callback.Run(buffer, packets);
  }

  void IsochronousTransferOut(
      uint8_t endpoint_number,
      scoped_refptr<net::IOBuffer> buffer,
      const std::vector<uint32_t>& packet_lengths,
      unsigned int timeout,
      const UsbDeviceHandle::IsochronousTransferCallback& callback) {
    ASSERT_FALSE(mock_outbound_data_.empty());
    const std::vector<uint8_t>& bytes = mock_outbound_data_.front();
    size_t length =
        std::accumulate(packet_lengths.begin(), packet_lengths.end(), 0u);
    ASSERT_EQ(bytes.size(), length);
    for (size_t i = 0; i < length; ++i) {
      EXPECT_EQ(bytes[i], buffer->data()[i]) << "Contents differ at index: "
                                             << i;
    }
    mock_outbound_data_.pop();

    ASSERT_FALSE(mock_outbound_packets_.empty());
    std::vector<UsbDeviceHandle::IsochronousPacket> packets =
        mock_outbound_packets_.front();
    ASSERT_EQ(packets.size(), packet_lengths.size());
    for (size_t i = 0; i < packets.size(); ++i) {
      EXPECT_EQ(packets[i].length, packet_lengths[i])
          << "Packet lengths differ at index: " << i;
    }
    mock_outbound_packets_.pop();

    callback.Run(buffer, packets);
  }

  scoped_ptr<base::MessageLoop> message_loop_;
  scoped_refptr<MockUsbDevice> mock_device_;
  scoped_refptr<MockUsbDeviceHandle> mock_handle_;
  bool is_device_open_;
  bool allow_reset_;

  std::map<uint8_t, UsbConfigDescriptor> mock_configs_;
  uint8_t current_config_;

  std::queue<std::vector<uint8_t>> mock_inbound_data_;
  std::queue<std::vector<uint8_t>> mock_outbound_data_;
  std::queue<std::vector<UsbDeviceHandle::IsochronousPacket>>
      mock_inbound_packets_;
  std::queue<std::vector<UsbDeviceHandle::IsochronousPacket>>
      mock_outbound_packets_;

  std::set<uint8_t> claimed_interfaces_;

  FakePermissionProvider permission_provider_;

  DISALLOW_COPY_AND_ASSIGN(USBDeviceImplTest);
};

}  // namespace

TEST_F(USBDeviceImplTest, Open) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_FALSE(is_device_open());

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::ALREADY_OPEN,
                            loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, Close) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_FALSE(is_device_open());

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());

  {
    base::RunLoop loop;
    device->Close(loop.QuitClosure());
    loop.Run();
  }

  EXPECT_FALSE(is_device_open());
}

// Test that the information returned via the Device::GetDeviceInfo matches that
// of the underlying device.
TEST_F(USBDeviceImplTest, GetDeviceInfo) {
  DevicePtr device =
      GetMockDeviceProxy(0x1234, 0x5678, "ACME", "Frobinator", "ABCDEF");

  base::RunLoop loop;
  device->GetDeviceInfo(base::Bind(&ExpectDeviceInfoAndThen,
                                   mock_device().guid(), 0x1234, 0x5678, "ACME",
                                   "Frobinator", "ABCDEF", loop.QuitClosure()));
  loop.Run();
}

TEST_F(USBDeviceImplTest, SetInvalidConfiguration) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), SetConfiguration(42, _));

  {
    // SetConfiguration should fail because 42 is not a valid mock
    // configuration.
    base::RunLoop loop;
    device->SetConfiguration(
        42, base::Bind(&ExpectResultAndThen, false, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, SetValidConfiguration) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), SetConfiguration(42, _));

  AddMockConfig(ConfigBuilder(42));

  {
    // SetConfiguration should succeed because 42 is a valid mock configuration.
    base::RunLoop loop;
    device->SetConfiguration(
        42, base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

// Verify that the result of Reset() reflects the underlying UsbDeviceHandle's
// ResetDevice() result.
TEST_F(USBDeviceImplTest, Reset) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), ResetDevice(_));

  set_allow_reset(true);

  {
    base::RunLoop loop;
    device->Reset(base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), ResetDevice(_));

  set_allow_reset(false);

  {
    base::RunLoop loop;
    device->Reset(base::Bind(&ExpectResultAndThen, false, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, ClaimAndReleaseInterface) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  // Now add a mock interface #1.
  AddMockConfig(ConfigBuilder(1).AddInterface(1, 0, 1, 2, 3));

  EXPECT_CALL(mock_handle(), SetConfiguration(1, _));

  {
    base::RunLoop loop;
    device->SetConfiguration(
        1, base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_device(), GetActiveConfiguration());
  EXPECT_CALL(mock_handle(), ClaimInterface(2, _));

  {
    // Try to claim an invalid interface and expect failure.
    base::RunLoop loop;
    device->ClaimInterface(
        2, base::Bind(&ExpectResultAndThen, false, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_device(), GetActiveConfiguration());
  EXPECT_CALL(mock_handle(), ClaimInterface(1, _));

  {
    base::RunLoop loop;
    device->ClaimInterface(
        1, base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), ReleaseInterface(2, _));

  {
    // Releasing a non-existent interface should fail.
    base::RunLoop loop;
    device->ReleaseInterface(
        2, base::Bind(&ExpectResultAndThen, false, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), ReleaseInterface(1, _));

  {
    // Now this should release the claimed interface and close the handle.
    base::RunLoop loop;
    device->ReleaseInterface(
        1, base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, SetInterfaceAlternateSetting) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  AddMockConfig(ConfigBuilder(1)
                    .AddInterface(1, 0, 1, 2, 3)
                    .AddInterface(1, 42, 1, 2, 3)
                    .AddInterface(2, 0, 1, 2, 3));

  EXPECT_CALL(mock_handle(), SetInterfaceAlternateSetting(1, 42, _));

  {
    base::RunLoop loop;
    device->SetInterfaceAlternateSetting(
        1, 42, base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), SetInterfaceAlternateSetting(1, 100, _));

  {
    base::RunLoop loop;
    device->SetInterfaceAlternateSetting(
        1, 100, base::Bind(&ExpectResultAndThen, false, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, ControlTransfer) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  AddMockConfig(ConfigBuilder(1).AddInterface(7, 0, 1, 2, 3));

  EXPECT_CALL(mock_device(), GetActiveConfiguration());
  EXPECT_CALL(mock_handle(), SetConfiguration(1, _));

  {
    base::RunLoop loop;
    device->SetConfiguration(
        1, base::Bind(&ExpectResultAndThen, true, loop.QuitClosure()));
    loop.Run();
  }

  std::vector<uint8_t> fake_data;
  fake_data.push_back(41);
  fake_data.push_back(42);
  fake_data.push_back(43);

  AddMockInboundData(fake_data);

  EXPECT_CALL(mock_handle(),
              ControlTransfer(USB_DIRECTION_INBOUND, UsbDeviceHandle::STANDARD,
                              UsbDeviceHandle::DEVICE, 5, 6, 7, _, _, 0, _));

  {
    auto params = ControlTransferParams::New();
    params->type = ControlTransferType::STANDARD;
    params->recipient = ControlTransferRecipient::DEVICE;
    params->request = 5;
    params->value = 6;
    params->index = 7;
    base::RunLoop loop;
    device->ControlTransferIn(
        std::move(params), static_cast<uint32_t>(fake_data.size()), 0,
        base::Bind(&ExpectTransferInAndThen, TransferStatus::COMPLETED,
                   fake_data, loop.QuitClosure()));
    loop.Run();
  }

  AddMockOutboundData(fake_data);

  EXPECT_CALL(mock_device(), GetActiveConfiguration());
  EXPECT_CALL(mock_handle(),
              ControlTransfer(USB_DIRECTION_OUTBOUND, UsbDeviceHandle::STANDARD,
                              UsbDeviceHandle::INTERFACE, 5, 6, 7, _, _, 0, _));

  {
    auto params = ControlTransferParams::New();
    params->type = ControlTransferType::STANDARD;
    params->recipient = ControlTransferRecipient::INTERFACE;
    params->request = 5;
    params->value = 6;
    params->index = 7;
    base::RunLoop loop;
    device->ControlTransferOut(
        std::move(params), mojo::Array<uint8_t>::From(fake_data), 0,
        base::Bind(&ExpectTransferStatusAndThen, TransferStatus::COMPLETED,
                   loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, GenericTransfer) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  std::string message1 = "say hello please";
  std::vector<uint8_t> fake_outbound_data(message1.size());
  std::copy(message1.begin(), message1.end(), fake_outbound_data.begin());

  std::string message2 = "hello world!";
  std::vector<uint8_t> fake_inbound_data(message2.size());
  std::copy(message2.begin(), message2.end(), fake_inbound_data.begin());

  AddMockConfig(ConfigBuilder(1).AddInterface(7, 0, 1, 2, 3));
  AddMockOutboundData(fake_outbound_data);
  AddMockInboundData(fake_inbound_data);

  EXPECT_CALL(mock_handle(), GenericTransfer(USB_DIRECTION_OUTBOUND, 0x01, _,
                                             fake_outbound_data.size(), 0, _));

  {
    base::RunLoop loop;
    device->GenericTransferOut(
        1, mojo::Array<uint8_t>::From(fake_outbound_data), 0,
        base::Bind(&ExpectTransferStatusAndThen, TransferStatus::COMPLETED,
                   loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), GenericTransfer(USB_DIRECTION_INBOUND, 0x81, _,
                                             fake_inbound_data.size(), 0, _));

  {
    base::RunLoop loop;
    device->GenericTransferIn(
        1, static_cast<uint32_t>(fake_inbound_data.size()), 0,
        base::Bind(&ExpectTransferInAndThen, TransferStatus::COMPLETED,
                   fake_inbound_data, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

TEST_F(USBDeviceImplTest, IsochronousTransfer) {
  DevicePtr device = GetMockDeviceProxy();

  EXPECT_CALL(mock_device(), Open(_));

  {
    base::RunLoop loop;
    device->Open(base::Bind(&ExpectOpenAndThen, OpenDeviceError::OK,
                            loop.QuitClosure()));
    loop.Run();
  }

  std::vector<UsbDeviceHandle::IsochronousPacket> fake_packets(4);
  for (size_t i = 0; i < fake_packets.size(); ++i) {
    fake_packets[i].length = 8;
    fake_packets[i].transferred_length = 8;
    fake_packets[i].status = USB_TRANSFER_COMPLETED;
  }
  std::vector<uint32_t> fake_packet_lengths(4, 8);

  std::vector<uint32_t> expected_transferred_lengths(4, 8);

  std::string outbound_data = "aaaaaaaabbbbbbbbccccccccdddddddd";
  std::vector<uint8_t> fake_outbound_data(outbound_data.size());
  std::copy(outbound_data.begin(), outbound_data.end(),
            fake_outbound_data.begin());

  std::string inbound_data = "ddddddddccccccccbbbbbbbbaaaaaaaa";
  std::vector<uint8_t> fake_inbound_data(inbound_data.size());
  std::copy(inbound_data.begin(), inbound_data.end(),
            fake_inbound_data.begin());

  AddMockConfig(ConfigBuilder(1).AddInterface(7, 0, 1, 2, 3));
  AddMockOutboundPackets(fake_outbound_data, fake_packets);
  AddMockInboundPackets(fake_inbound_data, fake_packets);

  EXPECT_CALL(mock_handle(),
              IsochronousTransferOut(0x01, _, fake_packet_lengths, 0, _));

  {
    base::RunLoop loop;
    device->IsochronousTransferOut(
        1, mojo::Array<uint8_t>::From(fake_outbound_data),
        mojo::Array<uint32_t>::From(fake_packet_lengths), 0,
        base::Bind(&ExpectPacketsOutAndThen, expected_transferred_lengths,
                   loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(),
              IsochronousTransferIn(0x81, fake_packet_lengths, 0, _));

  {
    base::RunLoop loop;
    device->IsochronousTransferIn(
        1, mojo::Array<uint32_t>::From(fake_packet_lengths), 0,
        base::Bind(&ExpectPacketsInAndThen, fake_inbound_data,
                   expected_transferred_lengths, loop.QuitClosure()));
    loop.Run();
  }

  EXPECT_CALL(mock_handle(), Close());
}

}  // namespace usb
}  // namespace device