File: zeroconf_printer_detector_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 (671 lines) | stat: -rw-r--r-- 28,691 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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/printing/zeroconf_printer_detector.h"

#include <algorithm>
#include <functional>
#include <map>
#include <memory>
#include <random>
#include <string>
#include <utility>
#include <vector>

#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/test/task_environment.h"
#include "chrome/browser/local_discovery/fake_service_discovery_device_lister.h"
#include "chrome/browser/local_discovery/service_discovery_device_lister.h"
#include "net/base/ip_address.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace ash {
namespace {

using ::local_discovery::FakeServiceDiscoveryDeviceLister;
using ::local_discovery::ServiceDescription;
using ::local_discovery::ServiceDiscoveryDeviceLister;

// Determine basic printer attributes deterministically but pseudorandomly based
// on the printer name.  The exact values returned here are not really
// important, the important parts are that there's variety based on the name,
// and it's deterministic.

// Should this printer provide usb_MFG and usb_MDL fields?
bool GetUsbFor(const std::string& name) {
  return std::hash<std::string>()(name) & 1;
}

// Get an IP address for this printer.  The returned address may be IPv4 or IPv6
net::IPAddress GetIPAddressFor(const std::string& name) {
  std::mt19937 rng(std::hash<std::string>()(name));
  if (rng() & 1) {
    // Give an IPv4 address.
    return net::IPAddress(rng(), rng(), rng(), rng());
  } else {
    // Give an IPv6 address.
    return net::IPAddress(rng(), rng(), rng(), rng(), rng(), rng(), rng(),
                          rng(), rng(), rng(), rng(), rng(), rng(), rng(),
                          rng(), rng());
  }
}

int GetPortFor(const std::string& name) {
  return (std::hash<std::string>()(name) % 1000) + 1;
}

// Enums for MakeExpectedPrinter().
enum class ServiceType {
  kIpp,     // IPP
  kIpps,    // IPPS
  kIppE,    // IPP-Everywhere
  kIppsE,   // IPPS-Everywhere
  kSocket,  // Socket
  kLpd,     // LPD
};

// This corresponds to MakeServiceDescription() below. Given the same name (and
// the correct service type), this generates the DetectedPrinter record we
// expect from ZeroconfPrinterDetector when it gets that ServiceDescription.
// This needs to be kept in sync with MakeServiceDescription().
PrinterDetector::DetectedPrinter MakeExpectedPrinter(const std::string& name,
                                                     ServiceType service_type) {
  PrinterDetector::DetectedPrinter detected;
  chromeos::Printer& printer = detected.printer;
  int port = GetPortFor(name);
  std::string scheme;
  std::string rp = base::StrCat({name, "_rp"});
  switch (service_type) {
    case ServiceType::kIpp:
      scheme = "ipp";
      break;
    case ServiceType::kIpps:
      scheme = "ipps";
      break;
    case ServiceType::kIppE:
      scheme = "ipp";
      printer.mutable_ppd_reference()->autoconf = true;
      break;
    case ServiceType::kIppsE:
      scheme = "ipps";
      printer.mutable_ppd_reference()->autoconf = true;
      break;
    case ServiceType::kSocket:
      scheme = "socket";
      rp = "";
      break;
    case ServiceType::kLpd:
      scheme = "lpd";
      break;
  }
  printer.SetUri(base::StringPrintf("%s://%s.local:%d/%s", scheme.c_str(),
                                    name.c_str(), port, rp.c_str()));

  printer.set_uuid(base::StrCat({name, "_UUID"}));
  printer.set_display_name(name);
  printer.set_description(base::StrCat({name, "_note"}));
  printer.set_make_and_model(base::StrCat({name, "_ty"}));
  detected.ppd_search_data.make_and_model.push_back(printer.make_and_model());
  detected.ppd_search_data.make_and_model.push_back(
      base::StrCat({name, "_product"}));
  if (GetUsbFor(name)) {
    // We should get an effective make and model guess from the usb fields
    // if they exist.
    detected.ppd_search_data.make_and_model.push_back(
        base::StrCat({name, "_usb_MFG ", name, "_usb_MDL"}));
  }

  return detected;
}

// Creates a deterministic ServiceDescription based on the service name and
// type. See the note on MakeExpectedPrinter() above. This must be kept in sync
// with MakeExpectedPrinter().
ServiceDescription MakeServiceDescription(const std::string& name,
                                          const std::string& service_type) {
  ServiceDescription sd;
  sd.service_name = base::StrCat({name, ".", service_type});
  sd.metadata.push_back(base::StrCat({"ty=", name, "_ty"}));
  sd.metadata.push_back(base::StrCat({"product=(", name, "_product)"}));
  if (GetUsbFor(name)) {
    sd.metadata.push_back(base::StrCat({"usb_MFG=", name, "_usb_MFG"}));
    sd.metadata.push_back(base::StrCat({"usb_MDL=", name, "_usb_MDL"}));
  }
  sd.metadata.push_back(base::StrCat({"rp=", name, "_rp"}));
  sd.metadata.push_back(base::StrCat({"note=", name, "_note"}));
  sd.metadata.push_back(base::StrCat({"UUID=", name, "_UUID"}));
  sd.address.set_host(base::StrCat({name, ".local"}));
  sd.ip_address = GetIPAddressFor(name);
  sd.address.set_port(GetPortFor(name));
  return sd;
}

class ZeroconfPrinterDetectorTest : public testing::Test {
 public:
  ZeroconfPrinterDetectorTest() {
    auto* runner = task_environment_.GetMainThreadTaskRunner().get();
    auto ipp_lister = std::make_unique<FakeServiceDiscoveryDeviceLister>(
        runner, ZeroconfPrinterDetector::kIppServiceName);
    ipp_lister_ = ipp_lister.get();
    auto ipps_lister = std::make_unique<FakeServiceDiscoveryDeviceLister>(
        runner, ZeroconfPrinterDetector::kIppsServiceName);
    ipps_lister_ = ipps_lister.get();
    auto ippe_lister = std::make_unique<FakeServiceDiscoveryDeviceLister>(
        runner, ZeroconfPrinterDetector::kIppEverywhereServiceName);
    ippe_lister_ = ippe_lister.get();
    auto ippse_lister = std::make_unique<FakeServiceDiscoveryDeviceLister>(
        runner, ZeroconfPrinterDetector::kIppsEverywhereServiceName);
    ippse_lister_ = ippse_lister.get();
    auto socket_lister = std::make_unique<FakeServiceDiscoveryDeviceLister>(
        runner, ZeroconfPrinterDetector::kSocketServiceName);
    socket_lister_ = socket_lister.get();
    auto lpd_lister = std::make_unique<FakeServiceDiscoveryDeviceLister>(
        runner, ZeroconfPrinterDetector::kLpdServiceName);
    lpd_lister_ = lpd_lister.get();

    listers_[ZeroconfPrinterDetector::kIppServiceName] = std::move(ipp_lister);
    listers_[ZeroconfPrinterDetector::kIppsServiceName] =
        std::move(ipps_lister);
    listers_[ZeroconfPrinterDetector::kIppEverywhereServiceName] =
        std::move(ippe_lister);
    listers_[ZeroconfPrinterDetector::kIppsEverywhereServiceName] =
        std::move(ippse_lister);
    listers_[ZeroconfPrinterDetector::kSocketServiceName] =
        std::move(socket_lister);
    listers_[ZeroconfPrinterDetector::kLpdServiceName] = std::move(lpd_lister);
  }
  ~ZeroconfPrinterDetectorTest() override = default;

  void CreateDetectorWithIppRejectList(
      base::flat_set<std::string> ipp_reject_list) {
    detector_ = ZeroconfPrinterDetector::CreateForTesting(
        &listers_, std::move(ipp_reject_list));
    // The previously allocated listers_ are swapped into the detector_, and so
    // the unique_ptr values of the listers_ map are no longer valid at this
    // point.  The ipp[se]_lister_ raw pointers are kept as seperate members to
    // keep the lister fakes accessible after ownership is transferred into the
    // detector.
    listers_.clear();
    detector_->RegisterPrintersFoundCallback(base::BindRepeating(
        &ZeroconfPrinterDetectorTest::OnPrintersFound, base::Unretained(this)));
    ipp_lister_->SetDelegate(detector_.get());
    ipps_lister_->SetDelegate(detector_.get());
    ippe_lister_->SetDelegate(detector_.get());
    ippse_lister_->SetDelegate(detector_.get());
    socket_lister_->SetDelegate(detector_.get());
    lpd_lister_->SetDelegate(detector_.get());
  }

  void CreateDetector() { CreateDetectorWithIppRejectList({}); }

  // Expect that the most up-to-date results from the detector match those
  // in printers.
  void ExpectPrintersAre(
      const std::vector<PrinterDetector::DetectedPrinter>& printers) {
    // The last observer callback should tell us the same thing as the querying
    // the detector manually.
    ASSERT_FALSE(printers_found_callbacks_.empty());
    ExpectPrintersEq(printers, printers_found_callbacks_.back());
    ExpectPrintersEq(printers, detector_->GetPrinters());
  }

  // Expect that the detected printers list is empty.
  void ExpectPrintersEmpty() {
    // Assert that the most recent callbacks are empty.
    ASSERT_FALSE(printers_found_callbacks_.empty());
    ASSERT_TRUE(printers_found_callbacks_.back().empty());
    ASSERT_TRUE(detector_->GetPrinters().empty());
  }

  // Expect that the given vectors have the same contents.  The ordering
  // may be different.
  void ExpectPrintersEq(
      const std::vector<PrinterDetector::DetectedPrinter>& expected,
      const std::vector<PrinterDetector::DetectedPrinter>& actual) {
    if (expected.size() != actual.size()) {
      ADD_FAILURE() << "Printers size mismatch, found " << actual.size()
                    << " expected " << expected.size();
      return;
    }
    std::vector<PrinterDetector::DetectedPrinter> sorted_expected = expected;
    std::vector<PrinterDetector::DetectedPrinter> sorted_actual = actual;

    std::sort(sorted_expected.begin(), sorted_expected.end(),
              [](const PrinterDetector::DetectedPrinter& a,
                 const PrinterDetector::DetectedPrinter& b) -> bool {
                return a.printer.uuid() < b.printer.uuid();
              });
    std::sort(sorted_actual.begin(), sorted_actual.end(),
              [](const PrinterDetector::DetectedPrinter& a,
                 const PrinterDetector::DetectedPrinter& b) -> bool {
                return a.printer.uuid() < b.printer.uuid();
              });
    for (size_t i = 0; i < sorted_expected.size(); ++i) {
      ExpectPrinterEq(sorted_expected[i], sorted_actual[i]);
    }
  }

  void ExpectPrinterEq(const PrinterDetector::DetectedPrinter& expected,
                       const PrinterDetector::DetectedPrinter& actual) {
    EXPECT_EQ(expected.printer.uri(), actual.printer.uri());
    // We don't have a good way to directly check for an expected id.
    EXPECT_EQ(expected.printer.uuid(), actual.printer.uuid());
    EXPECT_EQ(expected.printer.display_name(), actual.printer.display_name());
    EXPECT_EQ(expected.printer.description(), actual.printer.description());
    EXPECT_EQ(expected.printer.IsIppEverywhere(),
              actual.printer.IsIppEverywhere());
    EXPECT_EQ(expected.printer.make_and_model(),
              actual.printer.make_and_model());
    EXPECT_EQ(expected.ppd_search_data.usb_vendor_id,
              actual.ppd_search_data.usb_vendor_id);
    EXPECT_EQ(expected.ppd_search_data.usb_product_id,
              actual.ppd_search_data.usb_product_id);
    EXPECT_EQ(expected.ppd_search_data.make_and_model,
              actual.ppd_search_data.make_and_model);
  }

  // PrinterDetector callback.
  void OnPrintersFound(
      const std::vector<PrinterDetector::DetectedPrinter>& printers) {
    printers_found_callbacks_.push_back(printers);
  }

 protected:
  // Runs pending tasks regardless of delay.
  void CompleteTasks() { task_environment_.FastForwardUntilNoTasksRemain(); }

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  // Device listers fakes.  These are initialized when the test is constructed.
  // These pointers don't involve ownership; ownership of the listers starts
  // with this class in listers_ when the test starts, and is transferred to
  // detector_ when the detector is created.  Throughout, the listers remain
  // available to the test via these pointers.
  raw_ptr<FakeServiceDiscoveryDeviceLister, DanglingUntriaged> ipp_lister_;
  raw_ptr<FakeServiceDiscoveryDeviceLister, DanglingUntriaged> ipps_lister_;
  raw_ptr<FakeServiceDiscoveryDeviceLister, DanglingUntriaged> ippe_lister_;
  raw_ptr<FakeServiceDiscoveryDeviceLister, DanglingUntriaged> ippse_lister_;
  raw_ptr<FakeServiceDiscoveryDeviceLister, DanglingUntriaged> socket_lister_;
  raw_ptr<FakeServiceDiscoveryDeviceLister, DanglingUntriaged> lpd_lister_;

  // Detector under test.
  std::unique_ptr<ZeroconfPrinterDetector> detector_;

  // Saved copies of all the things given to OnPrintersFound.
  std::vector<std::vector<PrinterDetector::DetectedPrinter>>
      printers_found_callbacks_;

 private:
  // Temporary storage for the device listers, between the time the test is
  // constructed and the detector is created.  Tests shouldn't access this
  // directly, use the ipp*_lister_ variables instead.
  std::map<std::string, std::unique_ptr<ServiceDiscoveryDeviceLister>> listers_;
};

// Very basic stuff, one printer of each protocol we support.
TEST_F(ZeroconfPrinterDetectorTest, SingleIppPrinter) {
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kIppServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer1", ServiceType::kIpp)});
}

TEST_F(ZeroconfPrinterDetectorTest, SingleIppsPrinter) {
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer2", ZeroconfPrinterDetector::kIppsServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer2", ServiceType::kIpps)});
}

TEST_F(ZeroconfPrinterDetectorTest, SingleIppEverywherePrinter) {
  ippe_lister_->Announce(MakeServiceDescription(
      "Printer3", ZeroconfPrinterDetector::kIppEverywhereServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer3", ServiceType::kIppE)});
}

TEST_F(ZeroconfPrinterDetectorTest, SingleIppsEverywherePrinter) {
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer4", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer4", ServiceType::kIppsE)});
}

TEST_F(ZeroconfPrinterDetectorTest, SingleSocketPrinter) {
  socket_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kSocketServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kSocket)});
}

TEST_F(ZeroconfPrinterDetectorTest, SingleLpdPrinter) {
  lpd_lister_->Announce(MakeServiceDescription(
      "Printer6", ZeroconfPrinterDetector::kLpdServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer6", ServiceType::kLpd)});
}

// Test that an announce after the detector creation shows up as a printer.
TEST_F(ZeroconfPrinterDetectorTest, AnnounceAfterDetectorCreation) {
  CreateDetector();
  CompleteTasks();
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer4", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer4", ServiceType::kIppsE)});
}

// Test that we use the same printer ID regardless of which service type it
// comes to us from.
TEST_F(ZeroconfPrinterDetectorTest, StableIds) {
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kIppServiceName));
  CreateDetector();
  CompleteTasks();
  ASSERT_FALSE(printers_found_callbacks_.empty());
  ASSERT_EQ(1U, printers_found_callbacks_.back().size());
  // Grab the id when it's an IPPS printer We should continue to get the same id
  // regardless of service type.
  std::string id = printers_found_callbacks_.back()[0].printer.id();

  // Remove it as an IPP printer, add it as an IPPS printer.
  ipp_lister_->Remove("Printer1");
  CompleteTasks();
  ASSERT_TRUE(printers_found_callbacks_.back().empty());
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kIppsServiceName));
  CompleteTasks();
  ASSERT_EQ(1U, printers_found_callbacks_.back().size());
  // Id should be the same.
  ASSERT_EQ(id, printers_found_callbacks_.back()[0].printer.id());

  // Remove it as an IPPS printer, add it as an IPP-Everywhere printer.
  ipps_lister_->Remove("Printer1");
  CompleteTasks();
  ASSERT_TRUE(printers_found_callbacks_.back().empty());
  ippe_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kIppEverywhereServiceName));
  CompleteTasks();
  ASSERT_EQ(1U, printers_found_callbacks_.back().size());
  // Id should be the same.
  ASSERT_EQ(id, printers_found_callbacks_.back()[0].printer.id());

  // Remove it as an IPP-Everywhere printer, add it as an IPPS-Everywhere
  // printer.
  ippe_lister_->Remove("Printer1");
  CompleteTasks();
  ASSERT_TRUE(printers_found_callbacks_.back().empty());
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  CompleteTasks();
  ASSERT_EQ(1U, printers_found_callbacks_.back().size());
  // Id should be the same.
  ASSERT_EQ(id, printers_found_callbacks_.back()[0].printer.id());

  // Remove it as an IPPS-Everywhere printer, add it as a socket printer.
  ippse_lister_->Remove("Printer1");
  CompleteTasks();
  ASSERT_TRUE(printers_found_callbacks_.back().empty());
  socket_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kSocketServiceName));
  CompleteTasks();
  ASSERT_EQ(1U, printers_found_callbacks_.back().size());
  // Id should be the same.
  ASSERT_EQ(id, printers_found_callbacks_.back()[0].printer.id());

  // Remove it as a socket printer, add it as an LPD printer.
  socket_lister_->Remove("Printer1");
  CompleteTasks();
  ASSERT_TRUE(printers_found_callbacks_.back().empty());
  lpd_lister_->Announce(MakeServiceDescription(
      "Printer1", ZeroconfPrinterDetector::kLpdServiceName));
  CompleteTasks();
  ASSERT_EQ(1U, printers_found_callbacks_.back().size());
  // Id should be the same.
  ASSERT_EQ(id, printers_found_callbacks_.back()[0].printer.id());
}

// Test a basic removal.
TEST_F(ZeroconfPrinterDetectorTest, Removal) {
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kIppServiceName));
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer6", ZeroconfPrinterDetector::kIppServiceName));
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer7", ZeroconfPrinterDetector::kIppServiceName));
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer8", ZeroconfPrinterDetector::kIppServiceName));
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer9", ZeroconfPrinterDetector::kIppServiceName));
  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer6", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer7", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer8", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer9", ServiceType::kIpp)});
  ipp_lister_->Remove("Printer7");
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer6", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer8", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer9", ServiceType::kIpp)});
}

// Test that, when the same printer appears in multiple services, we
// use the highest priority one.  Priorities, from highest to lowest
// are IPPS-E, IPP-E, IPPS, IPP, Socket, LPD.
TEST_F(ZeroconfPrinterDetectorTest, ServiceTypePriorities) {
  // Advertise on all services.
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kIppServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kIppsServiceName));
  ippe_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kIppEverywhereServiceName));
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  socket_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kSocketServiceName));
  lpd_lister_->Announce(MakeServiceDescription(
      "Printer5", ZeroconfPrinterDetector::kLpdServiceName));
  CreateDetector();
  CompleteTasks();
  // IPPS-E is highest priority.
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kIppsE)});
  ippse_lister_->Remove("Printer5");
  CompleteTasks();
  // IPP-E is highest remaining priority.
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kIppE)});

  ippe_lister_->Remove("Printer5");
  CompleteTasks();
  // IPPS is highest remaining priority.
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kIpps)});

  ipps_lister_->Remove("Printer5");
  CompleteTasks();
  // IPP is highest remaining priority.
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kIpp)});

  ipp_lister_->Remove("Printer5");
  CompleteTasks();
  // Socket is highest remaining entry.
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kSocket)});

  socket_lister_->Remove("Printer5");
  CompleteTasks();
  // LPD is only remaining entry.
  ExpectPrintersAre({MakeExpectedPrinter("Printer5", ServiceType::kLpd)});

  lpd_lister_->Remove("Printer5");
  CompleteTasks();
  // No entries left.
  ExpectPrintersEmpty();
}

// Test a printer that is known not to work with IPP/IPPS and make sure a
// different protocol is chosen.
TEST_F(ZeroconfPrinterDetectorTest, RejectIpp) {
  std::string bad_ipp_printer = "manufacturer awesome printer-name";
  base::flat_set<std::string> reject_list;
  // We have to add the _ty suffix to match how MakeServiceDescription and
  // MakeExpectedPrinter work.
  reject_list.insert(bad_ipp_printer + "_ty");
  // Advertise on IPP and LPD services.
  ipp_lister_->Announce(MakeServiceDescription(
      bad_ipp_printer, ZeroconfPrinterDetector::kIppServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      bad_ipp_printer, ZeroconfPrinterDetector::kIppsServiceName));
  lpd_lister_->Announce(MakeServiceDescription(
      bad_ipp_printer, ZeroconfPrinterDetector::kLpdServiceName));
  CreateDetectorWithIppRejectList(reject_list);
  CompleteTasks();

  // Should be rejected for IPPS-E and IPP-E, so it should only exist in LPD.
  ExpectPrintersAre({MakeExpectedPrinter(bad_ipp_printer, ServiceType::kLpd)});

  lpd_lister_->Remove(bad_ipp_printer);
  CompleteTasks();
  // No entries left.
  ExpectPrintersEmpty();
}

// Test that cache flushes appropriately remove entries.
TEST_F(ZeroconfPrinterDetectorTest, CacheFlushes) {
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer6", ZeroconfPrinterDetector::kIppServiceName));
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer7", ZeroconfPrinterDetector::kIppServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer7", ZeroconfPrinterDetector::kIppsServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer8", ZeroconfPrinterDetector::kIppsServiceName));
  ippe_lister_->Announce(MakeServiceDescription(
      "Printer8", ZeroconfPrinterDetector::kIppEverywhereServiceName));
  ippe_lister_->Announce(MakeServiceDescription(
      "Printer9", ZeroconfPrinterDetector::kIppEverywhereServiceName));
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer9", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer10", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  socket_lister_->Announce(MakeServiceDescription(
      "Printer10", ZeroconfPrinterDetector::kSocketServiceName));
  socket_lister_->Announce(MakeServiceDescription(
      "Printer11", ZeroconfPrinterDetector::kSocketServiceName));
  lpd_lister_->Announce(MakeServiceDescription(
      "Printer11", ZeroconfPrinterDetector::kLpdServiceName));
  lpd_lister_->Announce(MakeServiceDescription(
      "Printer12", ZeroconfPrinterDetector::kLpdServiceName));

  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer6", ServiceType::kIpp),
                     MakeExpectedPrinter("Printer7", ServiceType::kIpps),
                     MakeExpectedPrinter("Printer8", ServiceType::kIppE),
                     MakeExpectedPrinter("Printer9", ServiceType::kIppsE),
                     MakeExpectedPrinter("Printer10", ServiceType::kIppsE),
                     MakeExpectedPrinter("Printer11", ServiceType::kSocket),
                     MakeExpectedPrinter("Printer12", ServiceType::kLpd)});

  ipps_lister_->Clear();

  CompleteTasks();
  // With the IPPS lister cleared, all printers should be cleared.
  ExpectPrintersEmpty();

  // We should have restarted discovery after dealing with the cache flush.
  EXPECT_TRUE(ipps_lister_->discovery_started());

  // Just for kicks, announce something new at this point.
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer13", ZeroconfPrinterDetector::kIppsServiceName));
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer13", ServiceType::kIpps)});

  // Clear out the IPPS lister, which will clear all printers too.
  ipps_lister_->Clear();
  CompleteTasks();

  // With the IPPS lister cleared, Printer13 should disappear.
  ExpectPrintersEmpty();
  EXPECT_TRUE(ippe_lister_->discovery_started());
}

// Test some general traffic with a mix of everything we expect to handle.
TEST_F(ZeroconfPrinterDetectorTest, GeneralMixedTraffic) {
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer12", ZeroconfPrinterDetector::kIppServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer12", ZeroconfPrinterDetector::kIppsServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer13", ZeroconfPrinterDetector::kIppsServiceName));
  ippse_lister_->Announce(MakeServiceDescription(
      "Printer14", ZeroconfPrinterDetector::kIppsEverywhereServiceName));
  ipps_lister_->Announce(MakeServiceDescription(
      "Printer15", ZeroconfPrinterDetector::kIppsServiceName));
  socket_lister_->Announce(MakeServiceDescription(
      "Printer16", ZeroconfPrinterDetector::kSocketServiceName));
  lpd_lister_->Announce(MakeServiceDescription(
      "Printer17", ZeroconfPrinterDetector::kLpdServiceName));

  CreateDetector();
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer12", ServiceType::kIpps),
                     MakeExpectedPrinter("Printer13", ServiceType::kIpps),
                     MakeExpectedPrinter("Printer14", ServiceType::kIppsE),
                     MakeExpectedPrinter("Printer15", ServiceType::kIpps),
                     MakeExpectedPrinter("Printer16", ServiceType::kSocket),
                     MakeExpectedPrinter("Printer17", ServiceType::kLpd)});

  ippe_lister_->Announce(MakeServiceDescription(
      "Printer13", ZeroconfPrinterDetector::kIppEverywhereServiceName));
  ipp_lister_->Announce(MakeServiceDescription(
      "Printer18", ZeroconfPrinterDetector::kIppServiceName));
  CompleteTasks();
  ExpectPrintersAre({MakeExpectedPrinter("Printer12", ServiceType::kIpps),
                     MakeExpectedPrinter("Printer13", ServiceType::kIppE),
                     MakeExpectedPrinter("Printer14", ServiceType::kIppsE),
                     MakeExpectedPrinter("Printer15", ServiceType::kIpps),
                     MakeExpectedPrinter("Printer16", ServiceType::kSocket),
                     MakeExpectedPrinter("Printer17", ServiceType::kLpd),
                     MakeExpectedPrinter("Printer18", ServiceType::kIpp)});

  ipp_lister_->Remove("NonexistantPrinter");
  ipps_lister_->Remove("Printer12");
  ipps_lister_->Clear();
  CompleteTasks();
  ExpectPrintersEmpty();
}

// Verify tasks are cleaned up properly when class is destroyed.
TEST_F(ZeroconfPrinterDetectorTest, DestroyedWithTasksPending) {
  CreateDetector();
  // Cause a callback to be queued.
  ipp_lister_->Announce(MakeServiceDescription(
      "TestPrinter", ZeroconfPrinterDetector::kIppServiceName));
  // Run listers but don't run the delayed tasks.
  task_environment_.RunUntilIdle();

  // Delete the detector.
  detector_.reset();

  // Clear task queues where we would crash if we did something wrong.
  task_environment_.FastForwardUntilNoTasksRemain();
  SUCCEED();
}

}  // namespace
}  // namespace ash