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 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
|
// 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 "chrome/browser/ash/printing/cups_printers_manager.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_set>
#include <utility>
#include <vector>
#include "ash/constants/ash_features.h"
#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/values.h"
#include "chrome/browser/ash/printing/enterprise/enterprise_printers_provider.h"
#include "chrome/browser/ash/printing/printer_configurer.h"
#include "chrome/browser/ash/printing/printer_event_tracker.h"
#include "chrome/browser/ash/printing/printers_map.h"
#include "chrome/browser/ash/printing/server_printers_provider.h"
#include "chrome/browser/ash/printing/synced_printers_manager.h"
#include "chrome/browser/ash/printing/usb_printer_detector.h"
#include "chrome/browser/ash/printing/usb_printer_notification_controller.h"
#include "chrome/browser/printing/print_preview_sticky_settings.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chromeos/ash/components/dbus/debug_daemon/debug_daemon_client.h"
#include "chromeos/ash/components/dbus/dlcservice/fake_dlcservice_client.h"
#include "chromeos/ash/components/dbus/printscanmgr/printscanmgr_client.h"
#include "chromeos/ash/components/network/network_state_handler.h"
#include "chromeos/ash/services/network_config/public/cpp/cros_network_config_test_helper.h"
#include "chromeos/printing/ppd_provider.h"
#include "components/prefs/pref_service.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/test/browser_task_environment.h"
#include "printing/printing_features.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/dlcservice/dbus-constants.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"
namespace ash {
namespace {
using ::chromeos::kPrinterId;
using ::chromeos::PpdProvider;
using ::chromeos::Printer;
using ::chromeos::PrinterClass;
using ::chromeos::PrinterSearchData;
constexpr base::TimeDelta kMetricsDelayTimerInterval = base::Seconds(60);
// Fake backend for EnterprisePrintersProvider. This allows us to poke
// arbitrary changes in the enterprise printer lists.
class FakeEnterprisePrintersProvider : public EnterprisePrintersProvider {
public:
FakeEnterprisePrintersProvider() = default;
~FakeEnterprisePrintersProvider() override = default;
// Attach |observer| for notification of events. |observer| is expected to
// live on the same thread (UI) as this object. OnPrinter* methods are
// invoked inline so calling RegisterPrinter in response to OnPrinterAdded is
// forbidden.
void AddObserver(EnterprisePrintersProvider::Observer* observer) override {
observers_.AddObserver(observer);
}
// Remove |observer| so that it no longer receives notifications. After the
// completion of this method, the |observer| can be safely destroyed.
void RemoveObserver(EnterprisePrintersProvider::Observer* observer) override {
observers_.RemoveObserver(observer);
}
// Fake manipulation functions.
// Add the given printers to the list of enterprise printers and
// notify observers.
void AddEnterprisePrinters(const std::vector<Printer>& printers) {
enterprise_printers_.insert(enterprise_printers_.end(), printers.begin(),
printers.end());
for (Observer& observer : observers_) {
observer.OnPrintersChanged(true, enterprise_printers_);
}
}
private:
base::ObserverList<EnterprisePrintersProvider::Observer>::Unchecked
observers_;
std::vector<Printer> enterprise_printers_;
};
// Fake backend for SyncedPrintersManager. This allows us to poke arbitrary
// changes in the saved printer lists.
class FakeSyncedPrintersManager : public SyncedPrintersManager {
public:
FakeSyncedPrintersManager() = default;
~FakeSyncedPrintersManager() override = default;
// Returns the printers that are saved in preferences.
std::vector<Printer> GetSavedPrinters() const override {
return saved_printers_;
}
// Attach |observer| for notification of events. |observer| is expected to
// live on the same thread (UI) as this object. OnPrinter* methods are
// invoked inline so calling RegisterPrinter in response to OnPrinterAdded is
// forbidden.
void AddObserver(SyncedPrintersManager::Observer* observer) override {
observers_.AddObserver(observer);
}
// Remove |observer| so that it no longer receives notifications. After the
// completion of this method, the |observer| can be safely destroyed.
void RemoveObserver(SyncedPrintersManager::Observer* observer) override {
observers_.RemoveObserver(observer);
}
void UpdateSavedPrinter(const Printer& printer) override {
if (!IsPrinterAlreadySaved(printer)) {
SavePrinter(printer);
return;
}
for (size_t i = 0; i < saved_printers_.size(); ++i) {
if (saved_printers_[i].id() == printer.id()) {
saved_printers_[i] = printer;
break;
}
}
NotifyOnSavedPrintersObservers();
}
bool RemoveSavedPrinter(const std::string& printer_id) override {
for (auto it = saved_printers_.begin(); it != saved_printers_.end(); ++it) {
if (it->id() == printer_id) {
saved_printers_.erase(it);
NotifyOnSavedPrintersObservers();
return true;
}
}
return false;
}
// Everything else in the interface we either don't use in
// CupsPrintersManager, or just use in a simple pass-through manner that's not
// worth additional layers of testing on top of the testing in
// SyncedPrintersManager.
PrintersSyncBridge* GetSyncBridge() override { return nullptr; }
// Returns the printer with id |printer_id|, or nullptr if no such printer
// exists.
std::unique_ptr<Printer> GetPrinter(
const std::string& printer_id) const override {
return nullptr;
}
// Fake manipulation functions.
// Add the given printers to the list of saved printers and
// notify observers.
void AddSavedPrinters(const std::vector<Printer>& printers) {
saved_printers_.insert(saved_printers_.end(), printers.begin(),
printers.end());
NotifyOnSavedPrintersObservers();
}
// Remove the printers with the given ids from the set of saved printers,
// notify observers.
void RemoveSavedPrinters(const std::unordered_set<std::string>& ids) {
RemovePrinters(ids, &saved_printers_);
NotifyOnSavedPrintersObservers();
}
private:
void RemovePrinters(const std::unordered_set<std::string>& ids,
std::vector<Printer>* target) {
std::erase_if(*target, [&ids](const Printer& printer) {
return base::Contains(ids, printer.id());
});
}
bool IsPrinterAlreadySaved(const Printer& printer) const {
for (const Printer& saved_printer : saved_printers_) {
if (printer.id() == saved_printer.id()) {
return true;
}
}
return false;
}
void SavePrinter(const Printer& printer) {
DCHECK(!IsPrinterAlreadySaved(printer));
saved_printers_.push_back(printer);
NotifyOnSavedPrintersObservers();
}
void NotifyOnSavedPrintersObservers() const {
for (Observer& observer : observers_) {
observer.OnSavedPrintersChanged();
}
}
base::ObserverList<SyncedPrintersManager::Observer>::Unchecked observers_;
std::vector<Printer> saved_printers_;
};
class FakePrinterDetector : public PrinterDetector {
public:
FakePrinterDetector() = default;
~FakePrinterDetector() override = default;
void RegisterPrintersFoundCallback(OnPrintersFoundCallback cb) override {
on_printers_found_callback_ = std::move(cb);
}
std::vector<DetectedPrinter> GetPrinters() override { return detections_; }
void AddDetections(
const std::vector<PrinterDetector::DetectedPrinter>& new_detections) {
detections_.insert(detections_.end(), new_detections.begin(),
new_detections.end());
on_printers_found_callback_.Run(detections_);
}
// Remove printers that have ids in ids.
void RemoveDetections(const std::unordered_set<std::string>& ids) {
std::erase_if(detections_, [&ids](const DetectedPrinter& detection) {
return base::Contains(ids, detection.printer.id());
});
on_printers_found_callback_.Run(detections_);
}
void RunPrintersFoundCallback() {
on_printers_found_callback_.Run(detections_);
}
private:
std::vector<DetectedPrinter> detections_;
OnPrintersFoundCallback on_printers_found_callback_;
};
// Fake PpdProvider backend. This fake generates PpdReferences based on
// the passed make_and_model strings using these rules:
//
// If make_and_model is empty, then we say NOT_FOUND
// Otherwise, generate a ppd reference with make_and_model[0] as
// the effective make and model in the PpdReference.
class FakePpdProvider : public PpdProvider {
public:
FakePpdProvider() = default;
void ResolvePpdReference(const PrinterSearchData& search_data,
ResolvePpdReferenceCallback cb) override {
if (search_data.make_and_model.empty()) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(std::move(cb), PpdProvider::NOT_FOUND,
Printer::PpdReference(), usb_manufacturer_));
} else {
Printer::PpdReference ret;
ret.effective_make_and_model = search_data.make_and_model[0];
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(cb), PpdProvider::SUCCESS, ret,
"" /* usb_manufacturer */));
}
}
void SetUsbManufacturer(const std::string& manufacturer) {
usb_manufacturer_ = manufacturer;
}
void SetLicenseName(const std::string& license_name) {
license_name_ = license_name;
}
void SetPpdContent(const std::string& ppd_content) {
ppd_content_ = ppd_content;
}
void ResolvePpd(const Printer::PpdReference& reference,
ResolvePpdCallback cb) override {
std::move(cb).Run(PpdProvider::CallbackResultCode::SUCCESS, ppd_content_);
}
void ResolvePpdLicense(std::string_view effective_make_and_model,
ResolvePpdLicenseCallback cb) override {
std::move(cb).Run(PpdProvider::CallbackResultCode::SUCCESS, license_name_);
}
// These methods are not used by CupsPrintersManager.
void ResolveManufacturers(ResolveManufacturersCallback cb) override {}
void ResolvePrinters(const std::string& manufacturer,
ResolvePrintersCallback cb) override {}
void ReverseLookup(const std::string& effective_make_and_model,
ReverseLookupCallback cb) override {}
private:
~FakePpdProvider() override = default;
std::string usb_manufacturer_;
std::string license_name_;
std::string ppd_content_ = "ppd content";
};
class FakeLocalPrintersObserver
: public CupsPrintersManager::LocalPrintersObserver {
public:
FakeLocalPrintersObserver() = default;
~FakeLocalPrintersObserver() override = default;
void OnLocalPrintersUpdated() override { ++num_observer_calls_; }
size_t num_observer_calls() const { return num_observer_calls_; }
private:
size_t num_observer_calls_ = 0;
};
// Expect that the printers in printers have the given ids, without
// considering order.
void ExpectPrinterIdsAre(const std::vector<Printer>& printers,
const std::vector<std::string>& ids) {
std::vector<std::string> found_ids;
for (const Printer& printer : printers) {
found_ids.push_back(printer.id());
}
std::sort(found_ids.begin(), found_ids.end());
std::vector<std::string> sorted_ids(ids);
std::sort(sorted_ids.begin(), sorted_ids.end());
EXPECT_EQ(sorted_ids, found_ids);
}
class FakeUsbPrinterNotificationController
: public UsbPrinterNotificationController {
public:
FakeUsbPrinterNotificationController() = default;
~FakeUsbPrinterNotificationController() override = default;
void ShowEphemeralNotification(const Printer& printer) override {
// Do nothing.
}
void ShowConfigurationNotification(const Printer& printer) override {
configuration_notifications_.insert(printer.id());
}
void ShowSavedNotification(const Printer& printer) override {
saved_notifications_.insert(printer.id());
}
void RemoveNotification(const std::string& printer_id) override {
saved_notifications_.erase(printer_id);
configuration_notifications_.erase(printer_id);
}
bool IsNotificationDisplayed(const std::string& printer_id) const override {
return configuration_notifications_.contains(printer_id) ||
saved_notifications_.contains(printer_id);
}
bool IsSavedNotification(const std::string& printer_id) const {
return saved_notifications_.contains(printer_id);
}
bool IsConfigurationNotification(const std::string& printer_id) const {
return configuration_notifications_.contains(printer_id);
}
private:
base::flat_set<std::string> saved_notifications_;
base::flat_set<std::string> configuration_notifications_;
};
class FakePrintServersManager : public PrintServersManager {
public:
FakePrintServersManager() = default;
~FakePrintServersManager() override = default;
void AddObserver(Observer* observer) override { observer_ = observer; }
void RemoveObserver(Observer* observer) override { observer_ = nullptr; }
void ChoosePrintServer(
const std::vector<std::string>& selected_print_server_ids) override {}
PrintServersConfig GetPrintServersConfig() const override {
return PrintServersConfig();
}
void ServerPrintersChanged(
const std::vector<PrinterDetector::DetectedPrinter>& printers) {
observer_->OnServerPrintersChanged(printers);
}
private:
raw_ptr<Observer> observer_;
};
class CupsPrintersManagerTest : public testing::Test,
public CupsPrintersManager::Observer {
public:
CupsPrintersManagerTest() : ppd_provider_(new FakePpdProvider) {
// Zeroconf and usb detector ownerships are taken by the manager, so we
// have to keep raw pointers to them.
auto zeroconf_detector = std::make_unique<FakePrinterDetector>();
zeroconf_detector_ = zeroconf_detector.get();
auto usb_detector = std::make_unique<FakePrinterDetector>();
usb_detector_ = usb_detector.get();
auto usb_notif_controller =
std::make_unique<FakeUsbPrinterNotificationController>();
usb_notif_controller_ = usb_notif_controller.get();
auto enterprise_printers_provider =
std::make_unique<FakeEnterprisePrintersProvider>();
enterprise_printers_provider_ = enterprise_printers_provider.get();
auto print_servers_manager = std::make_unique<FakePrintServersManager>();
print_servers_manager_ = print_servers_manager.get();
// To make sure it is not called.
dlc_service_client_.set_install_error(dlcservice::kErrorInternal);
// Register the pref |UserPrintersAllowed|
CupsPrintersManager::RegisterProfilePrefs(pref_service_.registry());
manager_ = CupsPrintersManager::CreateForTesting(
&synced_printers_manager_, std::move(usb_detector),
std::move(zeroconf_detector), ppd_provider_, &dlc_service_client_,
std::move(usb_notif_controller), std::move(print_servers_manager),
std::move(enterprise_printers_provider), &event_tracker_,
&pref_service_);
manager_->AddObserver(this);
}
~CupsPrintersManagerTest() override {
// Fast forwarding so that delayed tasks like |SendScannerCountToUMA| will
// run and not leak memory in unused callbacks.
task_environment_.FastForwardUntilNoTasksRemain();
}
void SetUp() override {
// TODO(b/257070388): Once the kAddPrinterViaPrintscanmgr feature is stable,
// remove the DebugDaemonClient and its test variants.
DebugDaemonClient::InitializeFake();
PrintscanmgrClient::InitializeFake();
}
void TearDown() override {
PrintscanmgrClient::Shutdown();
DebugDaemonClient::Shutdown();
}
// CupsPrintersManager::Observer implementation
void OnPrintersChanged(PrinterClass printer_class,
const std::vector<Printer>& printers) override {
observed_printers_[printer_class] = printers;
}
// Check that, for the given printer class, the printers we have from the
// observation callback and the printers we have when we query the manager
// are both the same and have the passed ids.
void ExpectPrintersInClassAre(PrinterClass printer_class,
const std::vector<std::string>& ids) {
ExpectPrinterIdsAre(manager_->GetPrinters(printer_class), ids);
ExpectPrinterIdsAre(observed_printers_[printer_class], ids);
}
void UpdatePolicyValue(const char* name, bool value) {
auto value_ptr = std::make_unique<base::Value>(value);
// TestingPrefSyncableService assumes ownership of |value_ptr|.
pref_service_.SetManagedPref(name, std::move(value_ptr));
}
static PrintServer CreatePrintServer(std::string id,
std::string server_url,
std::string name) {
GURL url(server_url);
PrintServer print_server(id, url, name);
return print_server;
}
protected:
// Everything from PrintServersProvider must be called on Chrome_UIThread
// Note: MainThreadType::IO is strictly about requesting a specific
// MessagePumpType for the main thread. It has nothing to do with
// BrowserThread::UI or BrowserThread::IO which are named threads in the
// //content/browser code.
// See
// //docs/threading_and_tasks_testing.md#mainthreadtype-trait
content::BrowserTaskEnvironment task_environment_{
base::test::TaskEnvironment::MainThreadType::IO,
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
// Captured printer lists from observer callbacks.
base::flat_map<PrinterClass, std::vector<Printer>> observed_printers_;
// Backend fakes driving the CupsPrintersManager.
FakeSyncedPrintersManager synced_printers_manager_;
raw_ptr<FakeEnterprisePrintersProvider, DanglingUntriaged>
enterprise_printers_provider_; // Not owned.
raw_ptr<FakePrinterDetector, DanglingUntriaged> usb_detector_; // Not owned.
raw_ptr<FakePrinterDetector, DanglingUntriaged>
zeroconf_detector_; // Not owned.
raw_ptr<FakeUsbPrinterNotificationController,
DanglingUntriaged>
usb_notif_controller_; // Not owned.
raw_ptr<FakePrintServersManager, DanglingUntriaged>
print_servers_manager_; // Not owned.
scoped_refptr<FakePpdProvider> ppd_provider_;
FakeDlcserviceClient dlc_service_client_;
// This is unused, it's just here for memory ownership.
PrinterEventTracker event_tracker_;
// PrefService used to register the |UserPrintersAllowed| pref and
// change its value for testing.
sync_preferences::TestingPrefServiceSyncable pref_service_;
// The manager being tested. This must be declared after the fakes, as its
// initialization must come after that of the fakes.
std::unique_ptr<CupsPrintersManager> manager_;
// Manages active networks.
network_config::CrosNetworkConfigTestHelper cros_network_config_helper_;
base::test::ScopedFeatureList feature_list_;
};
// Pseudo-constructor for inline creation of a DetectedPrinter that should (in
// this test) be handled as a Discovered printer (because it has no make and
// model information, and that's now the FakePpdProvider is set up to
// determine whether or not something has a Ppd available).
PrinterDetector::DetectedPrinter MakeDiscoveredPrinter(const std::string& id,
const std::string& uri) {
PrinterDetector::DetectedPrinter ret;
ret.printer.set_id(id);
ret.printer.SetUri(uri);
return ret;
}
// Calls MakeDiscoveredPrinter with empty uri.
PrinterDetector::DetectedPrinter MakeDiscoveredPrinter(const std::string& id) {
return MakeDiscoveredPrinter(id, /*uri=*/"ipp://discovered.printer/" + id);
}
// Calls MakeDiscoveredPrinter with the USB protocol as the uri.
PrinterDetector::DetectedPrinter MakeUsbDiscoveredPrinter(
const std::string& id) {
return MakeDiscoveredPrinter(id, "usb://host/path");
}
// Pseudo-constructor for inline creation of a DetectedPrinter that should (in
// this test) be handled as an Automatic printer (because it has a make and
// model string).
PrinterDetector::DetectedPrinter MakeAutomaticPrinter(const std::string& id) {
PrinterDetector::DetectedPrinter ret;
ret.printer.set_id(id);
ret.printer.SetUri("ipp://automatic.printer/" + id);
ret.ppd_search_data.make_and_model.push_back("make and model string");
return ret;
}
PrinterSetupCallback CallQuitOnRunLoop(base::RunLoop* run_loop,
PrinterSetupResult* result = nullptr) {
if (result == nullptr) {
return base::IgnoreArgs<PrinterSetupResult>(run_loop->QuitClosure());
}
return base::BindLambdaForTesting([run_loop, result](PrinterSetupResult res) {
*result = res;
run_loop->Quit();
});
}
// Test that Enterprise printers from SyncedPrinterManager are
// surfaced appropriately.
TEST_F(CupsPrintersManagerTest, GetEnterprisePrinters) {
enterprise_printers_provider_->AddEnterprisePrinters(
{Printer("Foo"), Printer("Bar")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kEnterprise, {"Foo", "Bar"});
}
// Test that Saved printers from SyncedPrinterManager are
// surfaced appropriately.
TEST_F(CupsPrintersManagerTest, GetSavedPrinters) {
synced_printers_manager_.AddSavedPrinters({Printer("Foo"), Printer("Bar")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Foo", "Bar"});
}
// Test that USB printers from the usb detector are converted to 'Printer's
// and surfaced appropriately. One printer should be "automatic" because it
// has a findable Ppd, the other should be "discovered".
TEST_F(CupsPrintersManagerTest, GetUsbPrinters) {
usb_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
}
// Same as GetUsbPrinters, using debugd.
TEST_F(CupsPrintersManagerTest, GetUsbPrintersDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
usb_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
}
// Same as GetUsbPrinters, only for Zeroconf printers.
TEST_F(CupsPrintersManagerTest, GetZeroconfPrinters) {
zeroconf_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
synced_printers_manager_.AddSavedPrinters({Printer("Foo"), Printer("Bar")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
}
// Test that USB printers that prefer IPP-USB end up in the automatic class
// instead of the discovered class.
TEST_F(CupsPrintersManagerTest, GetIppUsbPrinters) {
PrinterDetector::DetectedPrinter printer;
printer.printer.set_id("IppUsbPrinter");
printer.printer.SetUri("usb://1234/5678");
printer.printer.set_make_and_model("EPSON WF-110 Series");
usb_detector_->AddDetections({printer});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"IppUsbPrinter"});
}
// Same as GetIppUsbPrinters, using debugd.
TEST_F(CupsPrintersManagerTest, GetIppUsbPrintersDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
PrinterDetector::DetectedPrinter printer;
printer.printer.set_id("IppUsbPrinter");
printer.printer.SetUri("usb://1234/5678");
printer.printer.set_make_and_model("EPSON WF-110 Series");
usb_detector_->AddDetections({printer});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"IppUsbPrinter"});
}
// Test that printers that appear in either a Saved or Enterprise set do
// *not* appear in Discovered or Automatic, even if they are detected as such.
TEST_F(CupsPrintersManagerTest, SyncedPrintersTrumpDetections) {
PrinterDetector::DetectedPrinter disc0 =
MakeDiscoveredPrinter("DiscoveredPrinter0");
PrinterDetector::DetectedPrinter disc1 =
MakeDiscoveredPrinter("DiscoveredPrinter1");
PrinterDetector::DetectedPrinter auto0 =
MakeAutomaticPrinter("AutomaticPrinter0");
PrinterDetector::DetectedPrinter auto1 =
MakeAutomaticPrinter("AutomaticPrinter1");
zeroconf_detector_->AddDetections({disc0, disc1, auto0, auto1});
task_environment_.RunUntilIdle();
// Before we muck with anything else, check that automatic and discovered
// classes are what we intended to set up.
ExpectPrintersInClassAre(PrinterClass::kDiscovered,
{"DiscoveredPrinter0", "DiscoveredPrinter1"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic,
{"AutomaticPrinter0", "AutomaticPrinter1"});
// Save both the Discovered and Automatic printers. This should put them
// into the Saved class and thus *remove* them from their previous
// classes.
base::RunLoop run_loop_1;
manager_->SetUpPrinter(disc0.printer,
/*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop_1));
run_loop_1.Run();
manager_->SavePrinter(disc0.printer);
base::RunLoop run_loop_2;
manager_->SetUpPrinter(auto0.printer,
/*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop_2));
run_loop_2.Run();
manager_->SavePrinter(auto0.printer);
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter1"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter1"});
ExpectPrintersInClassAre(PrinterClass::kSaved,
{"DiscoveredPrinter0", "AutomaticPrinter0"});
}
// Same as SyncedPrintersTrumpDetections, using debugd.
TEST_F(CupsPrintersManagerTest, SyncedPrintersTrumpDetectionsDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
PrinterDetector::DetectedPrinter disc0 =
MakeDiscoveredPrinter("DiscoveredPrinter0");
PrinterDetector::DetectedPrinter disc1 =
MakeDiscoveredPrinter("DiscoveredPrinter1");
PrinterDetector::DetectedPrinter auto0 =
MakeAutomaticPrinter("AutomaticPrinter0");
PrinterDetector::DetectedPrinter auto1 =
MakeAutomaticPrinter("AutomaticPrinter1");
zeroconf_detector_->AddDetections({disc0, disc1, auto0, auto1});
task_environment_.RunUntilIdle();
// Before we muck with anything else, check that automatic and discovered
// classes are what we intended to set up.
ExpectPrintersInClassAre(PrinterClass::kDiscovered,
{"DiscoveredPrinter0", "DiscoveredPrinter1"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic,
{"AutomaticPrinter0", "AutomaticPrinter1"});
// Save both the Discovered and Automatic printers. This should put them
// into the Saved class and thus *remove* them from their previous
// classes.
base::RunLoop run_loop_1;
manager_->SetUpPrinter(disc0.printer,
/*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop_1));
run_loop_1.Run();
manager_->SavePrinter(disc0.printer);
base::RunLoop run_loop_2;
manager_->SetUpPrinter(auto0.printer,
/*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop_2));
run_loop_2.Run();
manager_->SavePrinter(auto0.printer);
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter1"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter1"});
ExpectPrintersInClassAre(PrinterClass::kSaved,
{"DiscoveredPrinter0", "AutomaticPrinter0"});
}
// Test updates of saved printers. Updates of existing saved printers
// should propagate. Updates of printers in other classes should result in
// those printers becoming saved. Updates of unknown printers should
// result in a new saved printer.
TEST_F(CupsPrintersManagerTest, SavePrinter) {
// Start with a printer in each class named after the class it's in, except
// Enterprise which is not relevant to this test.
Printer existing_saved("Saved");
synced_printers_manager_.AddSavedPrinters({existing_saved});
usb_detector_->AddDetections({MakeDiscoveredPrinter("Discovered")});
zeroconf_detector_->AddDetections({MakeAutomaticPrinter("Automatic")});
task_environment_.RunUntilIdle();
// Sanity check that we do, indeed, have one printer in each class.
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"Automatic"});
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"Discovered"});
// Update the existing saved printer. Check that the new display name
// propagated.
existing_saved.set_display_name("New Display Name");
manager_->SavePrinter(existing_saved);
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
EXPECT_EQ(manager_->GetPrinters(PrinterClass::kSaved)[0].display_name(),
"New Display Name");
// Do the same thing for the Automatic and Discovered printers.
// Create a configuration for the zeroconf printer, which should shift it
// into the saved category.
manager_->SavePrinter(Printer("Automatic"));
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {});
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Automatic", "Saved"});
manager_->SavePrinter(Printer("Discovered"));
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {});
ExpectPrintersInClassAre(PrinterClass::kSaved,
{"Automatic", "Saved", "Discovered"});
// Save a printer we haven't seen before, which should just add it to
// kSaved.
manager_->SavePrinter(Printer("NewFangled"));
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kSaved,
{"Automatic", "Saved", "Discovered", "NewFangled"});
// Remove the automatic printer, make sure it ends up back in the automatic
// class after removal.
manager_->RemoveSavedPrinter("Automatic");
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kSaved,
{"Saved", "Discovered", "NewFangled"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"Automatic"});
}
// Test that GetPrinter() finds printers in any class, and returns null if
// a printer is not found.
TEST_F(CupsPrintersManagerTest, GetPrinter) {
synced_printers_manager_.AddSavedPrinters({Printer("Saved")});
enterprise_printers_provider_->AddEnterprisePrinters({Printer("Enterprise")});
usb_detector_->AddDetections({MakeDiscoveredPrinter("Discovered")});
zeroconf_detector_->AddDetections({MakeAutomaticPrinter("Automatic")});
task_environment_.RunUntilIdle();
for (const std::string& id :
{"Saved", "Enterprise", "Discovered", "Automatic"}) {
std::optional<Printer> printer = manager_->GetPrinter(id);
ASSERT_TRUE(printer);
EXPECT_EQ(printer->id(), id);
}
std::optional<Printer> printer = manager_->GetPrinter("Nope");
EXPECT_FALSE(printer);
}
// Test that if |UserPrintersAllowed| pref is set to false, then
// GetPrinters() will only return printers from
// |PrinterClass::kEnterprise|.
TEST_F(CupsPrintersManagerTest, GetPrintersUserNativePrintersDisabled) {
synced_printers_manager_.AddSavedPrinters({Printer("Saved")});
enterprise_printers_provider_->AddEnterprisePrinters({Printer("Enterprise")});
task_environment_.RunUntilIdle();
// Disable the use of non-enterprise printers.
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
// Verify that non-enterprise printers are not returned by GetPrinters()
std::vector<Printer> saved_printers =
manager_->GetPrinters(PrinterClass::kSaved);
ExpectPrinterIdsAre(saved_printers, {});
// Verify that enterprise printers are returned by GetPrinters()
std::vector<Printer> enterprise_printers =
manager_->GetPrinters(PrinterClass::kEnterprise);
ExpectPrinterIdsAre(enterprise_printers, {"Enterprise"});
}
// Test that if |UserPrintersAllowed| pref is set to false, then
// SavePrinter() will simply do nothing.
TEST_F(CupsPrintersManagerTest, SavePrinterUserNativePrintersDisabled) {
// Start by installing a saved printer to be used to test than any
// changes made to the printer will not be propagated.
Printer existing_saved("Saved");
synced_printers_manager_.AddSavedPrinters({existing_saved});
usb_detector_->AddDetections({MakeDiscoveredPrinter("Discovered")});
zeroconf_detector_->AddDetections({MakeAutomaticPrinter("Automatic")});
task_environment_.RunUntilIdle();
// Sanity check that we do, indeed, have one printer in each class.
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"Automatic"});
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"Discovered"});
// Disable the use of non-enterprise printers.
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
// Update the existing saved printer. Verify that the changes did not
// progogate.
existing_saved.set_display_name("New Display Name");
manager_->SavePrinter(existing_saved);
task_environment_.RunUntilIdle();
// Reenable user printers in order to do checking.
UpdatePolicyValue(prefs::kUserPrintersAllowed, true);
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
EXPECT_EQ(manager_->GetPrinters(PrinterClass::kSaved)[0].display_name(), "");
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
// Attempt to update the Automatic and Discovered printers. In both cases
// check that the printers do not move into the saved category.
manager_->SavePrinter(Printer("Automatic"));
task_environment_.RunUntilIdle();
UpdatePolicyValue(prefs::kUserPrintersAllowed, true);
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"Automatic"});
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
manager_->SavePrinter(Printer("Discovered"));
task_environment_.RunUntilIdle();
UpdatePolicyValue(prefs::kUserPrintersAllowed, true);
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"Discovered"});
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
// Attempt to update a printer that we haven't seen before, check that
// nothing changed.
manager_->SavePrinter(Printer("NewFangled"));
task_environment_.RunUntilIdle();
UpdatePolicyValue(prefs::kUserPrintersAllowed, true);
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
}
// Test that if |UserPrintersAllowed| pref is set to false GetPrinter only
// returns a printer when the given printer id corresponds to an enterprise
// printer. Otherwise, it returns nothing.
TEST_F(CupsPrintersManagerTest, GetPrinterUserNativePrintersDisabled) {
synced_printers_manager_.AddSavedPrinters({Printer("Saved")});
enterprise_printers_provider_->AddEnterprisePrinters({Printer("Enterprise")});
task_environment_.RunUntilIdle();
// Sanity check that the printers were added.
ExpectPrintersInClassAre(PrinterClass::kSaved, {"Saved"});
ExpectPrintersInClassAre(PrinterClass::kEnterprise, {"Enterprise"});
// Disable the use of non-enterprise printers.
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
std::optional<Printer> saved_printer = manager_->GetPrinter("Saved");
EXPECT_FALSE(saved_printer);
std::optional<Printer> enterprise_printer =
manager_->GetPrinter("Enterprise");
ASSERT_TRUE(enterprise_printer);
EXPECT_EQ(enterprise_printer->id(), "Enterprise");
}
TEST_F(CupsPrintersManagerTest, SetUsbManufacturer) {
const std::string& expected_manufacturer = "HP";
ppd_provider_->SetUsbManufacturer(expected_manufacturer);
usb_detector_->AddDetections({MakeUsbDiscoveredPrinter("DiscoveredPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
EXPECT_EQ(
expected_manufacturer,
manager_->GetPrinter("DiscoveredPrinter")->usb_printer_manufacturer());
}
TEST_F(CupsPrintersManagerTest, EmptyUsbManufacturer) {
usb_detector_->AddDetections({MakeUsbDiscoveredPrinter("DiscoveredPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
EXPECT_TRUE(manager_->GetPrinter("DiscoveredPrinter")
->usb_printer_manufacturer()
.empty());
}
TEST_F(CupsPrintersManagerTest, PrinterNotInstalled) {
Printer printer(kPrinterId);
EXPECT_FALSE(manager_->IsPrinterInstalled(printer));
}
TEST_F(CupsPrintersManagerTest, PrinterIsInstalled) {
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
}
// Same as PrinterIsInstalled, using debugd.
TEST_F(CupsPrintersManagerTest, PrinterIsInstalledDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
}
// Test that we detect that the configuration is stale when any of the
// relevant fields change.
TEST_F(CupsPrintersManagerTest, UpdatedPrinterConfiguration) {
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
Printer updated(printer);
updated.SetUri("ipp://different.value");
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->autoconf = true;
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->user_supplied_ppd_url = "different value";
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->effective_make_and_model = "different value";
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->autoconf = true;
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
// Sanity check, configuration for the original printers should still be
// current.
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
}
// Same as UpdatedPrinterConfiguration, using debugd.
TEST_F(CupsPrintersManagerTest, UpdatedPrinterConfigurationDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
Printer updated(printer);
updated.SetUri("ipp://different.value");
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->autoconf = true;
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->user_supplied_ppd_url = "different value";
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->effective_make_and_model = "different value";
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
updated = printer;
updated.mutable_ppd_reference()->autoconf = true;
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
// Sanity check, configuration for the original printers should still be
// current.
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
}
// Test that we can save non-discovered printers.
TEST_F(CupsPrintersManagerTest, SavePrinterSucceedsOnManualPrinter) {
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
manager_->SavePrinter(printer);
auto saved_printers = manager_->GetPrinters(PrinterClass::kSaved);
ASSERT_EQ(1u, saved_printers.size());
EXPECT_EQ(printer.uri(), saved_printers[0].uri());
}
// Test that installing a printer does not put it in the saved class.
TEST_F(CupsPrintersManagerTest, PrinterInstalledDoesNotSavePrinter) {
Printer printer(kPrinterId);
EXPECT_TRUE(printer.SetUri("ipp://abcde/ipp/print"));
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
auto saved_printers = manager_->GetPrinters(PrinterClass::kSaved);
EXPECT_EQ(0u, saved_printers.size());
}
// Same as PrinterInstalledDoesNotSavePrinter, using debugd.
TEST_F(CupsPrintersManagerTest, PrinterInstalledDoesNotSavePrinterDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
Printer printer(kPrinterId);
EXPECT_TRUE(printer.SetUri("ipp://abcde/ipp/print"));
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
auto saved_printers = manager_->GetPrinters(PrinterClass::kSaved);
EXPECT_EQ(0u, saved_printers.size());
}
// Test that calling SavePrinter() when printer configuration change updates
// the saved printer but does not install the updated printer.
TEST_F(CupsPrintersManagerTest, SavePrinterUpdatesPreviouslyInstalledPrinter) {
Printer printer(kPrinterId);
printer.SetUri("http://ble");
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
manager_->SavePrinter(printer);
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
Printer updated(printer);
updated.SetUri("ipps://different/value");
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
manager_->SavePrinter(updated);
auto saved_printers = manager_->GetPrinters(PrinterClass::kSaved);
ASSERT_EQ(1u, saved_printers.size());
EXPECT_EQ(updated.uri(), saved_printers[0].uri());
// Even though the updated printer was saved, it still needs to be marked as
// installed again.
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
}
// same as SavePrinterUpdatesPreviouslyInstalledPrinter, using debugd.
TEST_F(CupsPrintersManagerTest,
SavePrinterUpdatesPreviouslyInstalledPrinterDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
Printer printer(kPrinterId);
printer.SetUri("http://ble");
base::RunLoop run_loop;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop));
run_loop.Run();
manager_->SavePrinter(printer);
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
Printer updated(printer);
updated.SetUri("ipps://different/value");
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
manager_->SavePrinter(updated);
auto saved_printers = manager_->GetPrinters(PrinterClass::kSaved);
ASSERT_EQ(1u, saved_printers.size());
EXPECT_EQ(updated.uri(), saved_printers[0].uri());
// Even though the updated printer was saved, it still needs to be marked as
// installed again.
EXPECT_FALSE(manager_->IsPrinterInstalled(updated));
}
// Automatic USB Printer is configured automatically.
TEST_F(CupsPrintersManagerTest, AutomaticUsbPrinterIsInstalledAutomatically) {
auto automatic_printer = MakeAutomaticPrinter(kPrinterId);
automatic_printer.printer.SetUri("usb://host/path");
usb_detector_->AddDetections({automatic_printer});
task_environment_.RunUntilIdle();
std::optional<chromeos::Printer> printer =
manager_->GetPrinter(automatic_printer.printer.id());
ASSERT_TRUE(printer);
EXPECT_TRUE(manager_->IsPrinterInstalled(*printer));
}
// Same as AutomaticUsbPrinterIsInstalledAutomatically, using debugd.
TEST_F(CupsPrintersManagerTest,
AutomaticUsbPrinterIsInstalledAutomaticallyDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
auto automatic_printer = MakeAutomaticPrinter(kPrinterId);
automatic_printer.printer.SetUri("usb://host/path");
usb_detector_->AddDetections({automatic_printer});
task_environment_.RunUntilIdle();
std::optional<chromeos::Printer> printer =
manager_->GetPrinter(automatic_printer.printer.id());
ASSERT_TRUE(printer);
EXPECT_TRUE(manager_->IsPrinterInstalled(*printer));
}
// Can handle four different USB printers at the same time.
TEST_F(CupsPrintersManagerTest, CanHandleManyUsbPrinters) {
// Printer without PPD file and not supporting IPPUSB.
auto p1 = MakeUsbDiscoveredPrinter("id1");
// Printer with PPD file but not supporting IPPUSB.
auto p2 = MakeUsbDiscoveredPrinter("id2");
p2.ppd_search_data.make_and_model.push_back("make-and-model");
// Printer without PPD file but supporting IPPUSB.
auto p3 = MakeUsbDiscoveredPrinter("id3");
p3.printer.set_supports_ippusb(true);
// Printer with PPD file and supporting IPPUSB.
auto p4 = MakeUsbDiscoveredPrinter("id4");
p4.ppd_search_data.make_and_model.push_back("make-and-model");
p4.printer.set_supports_ippusb(true);
usb_detector_->AddDetections({p1, p2, p3, p4});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"id1"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"id2", "id3", "id4"});
EXPECT_FALSE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id1")));
EXPECT_TRUE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id2")));
EXPECT_TRUE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id3")));
EXPECT_TRUE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id4")));
}
// Same as CanHandleManyUsbPrinters, using debugd.
TEST_F(CupsPrintersManagerTest, CanHandleManyUsbPrintersDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
// Printer without PPD file and not supporting IPPUSB.
auto p1 = MakeUsbDiscoveredPrinter("id1");
// Printer with PPD file but not supporting IPPUSB.
auto p2 = MakeUsbDiscoveredPrinter("id2");
p2.ppd_search_data.make_and_model.push_back("make-and-model");
// Printer without PPD file but supporting IPPUSB.
auto p3 = MakeUsbDiscoveredPrinter("id3");
p3.printer.set_supports_ippusb(true);
// Printer with PPD file and supporting IPPUSB.
auto p4 = MakeUsbDiscoveredPrinter("id4");
p4.ppd_search_data.make_and_model.push_back("make-and-model");
p4.printer.set_supports_ippusb(true);
usb_detector_->AddDetections({p1, p2, p3, p4});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"id1"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"id2", "id3", "id4"});
EXPECT_FALSE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id1")));
EXPECT_TRUE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id2")));
EXPECT_TRUE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id3")));
EXPECT_TRUE(manager_->IsPrinterInstalled(*manager_->GetPrinter("id4")));
}
// Automatic Printer is *not* configured if |UserPrintersAllowed|
// pref is set to false.
TEST_F(CupsPrintersManagerTest, AutomaticPrinterNotInstalledAutomatically) {
// Disable the use of non-enterprise printers.
UpdatePolicyValue(prefs::kUserPrintersAllowed, false);
auto automatic_printer = MakeAutomaticPrinter(kPrinterId);
automatic_printer.printer.SetUri("usb://host/path");
zeroconf_detector_->AddDetections({automatic_printer});
task_environment_.RunUntilIdle();
EXPECT_FALSE(manager_->IsPrinterInstalled(automatic_printer.printer));
}
// Nearby printers that are not automatic & USB are not automatically
// installed.
TEST_F(CupsPrintersManagerTest, OtherNearbyPrintersNotInstalledAutomatically) {
auto discovered_printer = MakeDiscoveredPrinter("Discovered");
discovered_printer.printer.SetUri("usb://host/path");
auto automatic_printer = MakeAutomaticPrinter("Automatic");
usb_detector_->AddDetections({discovered_printer});
zeroconf_detector_->AddDetections({automatic_printer});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"Discovered"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"Automatic"});
EXPECT_FALSE(manager_->IsPrinterInstalled(discovered_printer.printer));
EXPECT_FALSE(manager_->IsPrinterInstalled(automatic_printer.printer));
}
TEST_F(CupsPrintersManagerTest, DetectedUsbPrinterConfigurationNotification) {
auto discovered_printer = MakeDiscoveredPrinter("Discovered");
discovered_printer.printer.SetUri("usb://host/path");
usb_detector_->AddDetections({discovered_printer});
task_environment_.RunUntilIdle();
EXPECT_TRUE(usb_notif_controller_->IsConfigurationNotification("Discovered"));
usb_detector_->RemoveDetections({"Discovered"});
EXPECT_FALSE(
usb_notif_controller_->IsConfigurationNotification("Discovered"));
}
TEST_F(CupsPrintersManagerTest,
DetectedZeroconfDiscoveredPrinterNoNotification) {
auto discovered_printer = MakeDiscoveredPrinter("Discovered");
discovered_printer.printer.SetUri("ipp://host");
zeroconf_detector_->AddDetections({discovered_printer});
task_environment_.RunUntilIdle();
EXPECT_FALSE(
usb_notif_controller_->IsConfigurationNotification("Discovered"));
}
// Test that RecordNearbyNetworkPrinterCounts logs the total number of
// detected network printers.
TEST_F(CupsPrintersManagerTest, RecordTotalNetworkPrinterCounts) {
base::HistogramTester histogram_tester;
manager_->SavePrinter(Printer("DiscoveredNetworkPrinter0"));
usb_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredUSBPrinter"),
MakeAutomaticPrinter("AutomaticUSBPrinter")});
task_environment_.FastForwardBy(kMetricsDelayTimerInterval);
histogram_tester.ExpectBucketCount("Printing.CUPS.TotalNetworkPrintersCount2",
0, 1);
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount(
"Printing.CUPS.TotalNetworkPrintersCount2.SettingsOpened", 0, 1);
zeroconf_detector_->AddDetections(
{MakeDiscoveredPrinter("DiscoveredNetworkPrinter0"),
MakeDiscoveredPrinter("DiscoveredNetworkPrinter1"),
MakeAutomaticPrinter("AutomaticNetworkPrinter0"),
MakeAutomaticPrinter("AutomaticNetworkPrinter1")});
task_environment_.FastForwardBy(kMetricsDelayTimerInterval);
histogram_tester.ExpectBucketCount("Printing.CUPS.TotalNetworkPrintersCount2",
4, 1);
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount(
"Printing.CUPS.TotalNetworkPrintersCount2.SettingsOpened", 4, 1);
}
// Same as RecordTotalNetworkPrinterCounts, using debgud.
TEST_F(CupsPrintersManagerTest, RecordTotalNetworkPrinterCountsDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
base::HistogramTester histogram_tester;
manager_->SavePrinter(Printer("DiscoveredNetworkPrinter0"));
usb_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredUSBPrinter"),
MakeAutomaticPrinter("AutomaticUSBPrinter")});
task_environment_.FastForwardBy(kMetricsDelayTimerInterval);
histogram_tester.ExpectBucketCount("Printing.CUPS.TotalNetworkPrintersCount2",
0, 1);
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount(
"Printing.CUPS.TotalNetworkPrintersCount2.SettingsOpened", 0, 1);
zeroconf_detector_->AddDetections(
{MakeDiscoveredPrinter("DiscoveredNetworkPrinter0"),
MakeDiscoveredPrinter("DiscoveredNetworkPrinter1"),
MakeAutomaticPrinter("AutomaticNetworkPrinter0"),
MakeAutomaticPrinter("AutomaticNetworkPrinter1")});
task_environment_.FastForwardBy(kMetricsDelayTimerInterval);
histogram_tester.ExpectBucketCount("Printing.CUPS.TotalNetworkPrintersCount2",
4, 1);
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount(
"Printing.CUPS.TotalNetworkPrintersCount2.SettingsOpened", 4, 1);
}
// Test that RecordNearbyNetworkPrinterCounts logs the number of
// all nearby (not already saved) detected network printers.
TEST_F(CupsPrintersManagerTest, RecordNearbyNetworkPrinterCounts) {
base::HistogramTester histogram_tester;
usb_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredUSBPrinter"),
MakeAutomaticPrinter("AutomaticUSBPrinter")});
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount("Printing.CUPS.NearbyNetworkPrintersCount",
0, 1);
manager_->SavePrinter(Printer("DiscoveredNetworkPrinter0"));
zeroconf_detector_->AddDetections(
{MakeDiscoveredPrinter("DiscoveredNetworkPrinter0"),
MakeDiscoveredPrinter("DiscoveredNetworkPrinter1"),
MakeAutomaticPrinter("AutomaticNetworkPrinter0"),
MakeAutomaticPrinter("AutomaticNetworkPrinter1")});
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount("Printing.CUPS.NearbyNetworkPrintersCount",
3, 1);
// Save one more network printer.
manager_->SavePrinter(Printer("AutomaticNetworkPrinter1"));
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount("Printing.CUPS.NearbyNetworkPrintersCount",
2, 1);
}
// Same as RecordNearbyNetworkPrinterCounts, using debugd.
TEST_F(CupsPrintersManagerTest, RecordNearbyNetworkPrinterCountsDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
base::HistogramTester histogram_tester;
usb_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredUSBPrinter"),
MakeAutomaticPrinter("AutomaticUSBPrinter")});
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount("Printing.CUPS.NearbyNetworkPrintersCount",
0, 1);
manager_->SavePrinter(Printer("DiscoveredNetworkPrinter0"));
zeroconf_detector_->AddDetections(
{MakeDiscoveredPrinter("DiscoveredNetworkPrinter0"),
MakeDiscoveredPrinter("DiscoveredNetworkPrinter1"),
MakeAutomaticPrinter("AutomaticNetworkPrinter0"),
MakeAutomaticPrinter("AutomaticNetworkPrinter1")});
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount("Printing.CUPS.NearbyNetworkPrintersCount",
3, 1);
// Save one more network printer.
manager_->SavePrinter(Printer("AutomaticNetworkPrinter1"));
manager_->RecordNearbyNetworkPrinterCounts();
task_environment_.RunUntilIdle();
histogram_tester.ExpectBucketCount("Printing.CUPS.NearbyNetworkPrintersCount",
2, 1);
}
TEST_F(CupsPrintersManagerTest, OnServerPrintersChanged) {
auto server_printer = MakeAutomaticPrinter("ServerPrinter");
server_printer.printer.mutable_ppd_reference()->autoconf = true;
print_servers_manager_->ServerPrintersChanged({server_printer});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"ServerPrinter"});
}
// Tests that when the active network is switched to a different network the
// list of nearby printers is cleared.
TEST_F(CupsPrintersManagerTest, ActiveNetworkSwitched) {
cros_network_config_helper_.network_state_helper().ConfigureService(
R"({"GUID": "Wifi1", "Type": "wifi", "State": "online"})");
zeroconf_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
cros_network_config_helper_.network_state_helper().ClearServices();
cros_network_config_helper_.network_state_helper().ConfigureService(
R"({"GUID": "Wifi2", "Type": "wifi", "State": "online"})");
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {});
}
// Tests that when the active network is disconnected the list of nearby
// printers is cleared.
TEST_F(CupsPrintersManagerTest, ActiveNetworkDisconnected) {
cros_network_config_helper_.network_state_helper().ConfigureService(
R"({"GUID": "Wifi1", "Type": "wifi", "State": "online"})");
zeroconf_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
cros_network_config_helper_.network_state_helper().ClearServices();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {});
}
// Tests that when the a new wifi network is detected, but the active network
// remains the same, the list of nearby printers stays the same.
TEST_F(CupsPrintersManagerTest, NewNetworkDetected) {
cros_network_config_helper_.network_state_helper().ConfigureService(
R"({"GUID": "Wifi1", "Type": "wifi", "State": "online"})");
zeroconf_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
cros_network_config_helper_.network_state_helper().ConfigureService(
R"({"GUID": "Wifi2", "Type": "wifi", "State": "online"})");
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
}
// Tests that when the signal strength of the active network changes, the list
// of nearby printers stays the same.
TEST_F(CupsPrintersManagerTest, ActiveNetworkStrengthChanged) {
const std::string service_path =
cros_network_config_helper_.network_state_helper().ConfigureService(
R"({"GUID": "Wifi1", "Type": "wifi", "State": "online"})");
zeroconf_detector_->AddDetections({MakeDiscoveredPrinter("DiscoveredPrinter"),
MakeAutomaticPrinter("AutomaticPrinter")});
task_environment_.RunUntilIdle();
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
cros_network_config_helper_.network_state_helper().SetServiceProperty(
service_path, shill::kSignalStrengthProperty, base::Value(50));
ExpectPrintersInClassAre(PrinterClass::kDiscovered, {"DiscoveredPrinter"});
ExpectPrintersInClassAre(PrinterClass::kAutomatic, {"AutomaticPrinter"});
}
// Tests that local printers observers are triggered when added.
TEST_F(CupsPrintersManagerTest, AddLocalPrintersObserver) {
// Add the same observer twice to verify it's only added once and triggered
// once.
FakeLocalPrintersObserver observer1;
manager_->AddLocalPrintersObserver(&observer1);
manager_->AddLocalPrintersObserver(&observer1);
EXPECT_EQ(1u, observer1.num_observer_calls());
// Add another observer and verify it's the only one that's triggered this
// time.
FakeLocalPrintersObserver observer2;
manager_->AddLocalPrintersObserver(&observer2);
EXPECT_EQ(1u, observer2.num_observer_calls());
EXPECT_EQ(1u, observer1.num_observer_calls());
}
// Tests that when a new local printer is detected the observer is triggered.
TEST_F(CupsPrintersManagerTest, LocalPrintersDetected) {
// The observer should fire when first registered.
FakeLocalPrintersObserver observer1;
manager_->AddLocalPrintersObserver(&observer1);
EXPECT_EQ(1u, observer1.num_observer_calls());
// The observer should fire for a new zeroconf printer detection.
const auto detected_printer = MakeDiscoveredPrinter("DiscoveredPrinter");
zeroconf_detector_->AddDetections({detected_printer});
task_environment_.RunUntilIdle();
EXPECT_EQ(2u, observer1.num_observer_calls());
// The observer shouldn't fire when the same printer is sent for detection so
// the call count should remain the same.
zeroconf_detector_->RunPrintersFoundCallback();
task_environment_.RunUntilIdle();
EXPECT_EQ(2u, observer1.num_observer_calls());
// The observer should fire again for a new USB printer detection.
const auto usb_detected_printer = MakeUsbDiscoveredPrinter("UsbPrinter");
usb_detector_->AddDetections({usb_detected_printer});
task_environment_.RunUntilIdle();
EXPECT_EQ(3u, observer1.num_observer_calls());
}
// Tests that the polling printer status requests trigger the local printers
// observer up until the max time allocated for polling statuses.
TEST_F(CupsPrintersManagerTest, PrinterStatusPolling) {
// Add `RecentPrinter` to the Print Preview sticky settings so it'll get
// polled for status. `OldPrinter` will not get queried.
::printing::PrintPreviewStickySettings* sticky_settings =
::printing::PrintPreviewStickySettings::GetInstance();
sticky_settings->StoreAppState(R"({
"recentDestinations": [
{
"id": "RecentPrinter"
}
]
})");
// Add a saved printer to be queried for status.
Printer saved_printer("SavedPrinter");
saved_printer.SetUri("ipp://discovered.printer/");
synced_printers_manager_.AddSavedPrinters({saved_printer});
zeroconf_detector_->AddDetections({MakeDiscoveredPrinter("RecentPrinter"),
MakeDiscoveredPrinter("OldPrinter")});
task_environment_.RunUntilIdle();
// Add the observer to capture the triggers from printer status queries.
FakeLocalPrintersObserver observer;
manager_->AddLocalPrintersObserver(&observer);
task_environment_.FastForwardUntilNoTasksRemain();
// 1 call when the observer is added + 2 calls for initial printer status
// queries to the Saved and Recent printer
EXPECT_EQ(3u, observer.num_observer_calls());
}
TEST_F(CupsPrintersManagerTest, PrinterWithHplipPluginLicenseDlcFails) {
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
printer.mutable_ppd_reference()->effective_make_and_model = "Make and model";
ppd_provider_->SetLicenseName("hplip-plugin");
base::RunLoop run_loop;
PrinterSetupResult result;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop, &result));
run_loop.Run();
EXPECT_EQ(result, PrinterSetupResult::kComponentUnavailable);
EXPECT_FALSE(manager_->IsPrinterInstalled(printer));
}
TEST_F(CupsPrintersManagerTest, PrinterWithHplipPluginLicenseDlcSucceeds) {
feature_list_.InitAndEnableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
printer.mutable_ppd_reference()->effective_make_and_model = "Make and model";
ppd_provider_->SetLicenseName("hplip-plugin");
ppd_provider_->SetPpdContent("*hpPrinterLanguage: lang\nsomething else\n");
dlc_service_client_.set_install_error(dlcservice::kErrorNone);
dlc_service_client_.set_install_root_path("/root/path");
base::RunLoop run_loop;
PrinterSetupResult result;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop, &result));
run_loop.Run();
EXPECT_EQ(result, PrinterSetupResult::kSuccess);
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
// Check if the PPD content was updated.
base::RunLoop run_loop_2;
std::string ppd_content;
printscanmgr::CupsRetrievePpdRequest request;
request.set_name(kPrinterId);
PrintscanmgrClient::Get()->CupsRetrievePrinterPpd(
request,
base::BindLambdaForTesting(
[&run_loop_2, &ppd_content](
std::optional<printscanmgr::CupsRetrievePpdResponse> response) {
if (response) {
ppd_content = response->ppd();
}
run_loop_2.Quit();
}),
base::BindLambdaForTesting([&run_loop_2]() { run_loop_2.Quit(); }));
run_loop_2.Run();
EXPECT_EQ(ppd_content,
"*hpPrinterLanguage: lang\n*chromeOSHplipPluginPath: "
"\"/root/path\"\nsomething else\n");
}
// Same as PrinterWithHplipPluginLicenseDlcSucceeds, using debugd.
TEST_F(CupsPrintersManagerTest,
PrinterWithHplipPluginLicenseDlcSucceedsDebugd) {
feature_list_.InitAndDisableFeature(
printing::features::kAddPrinterViaPrintscanmgr);
Printer printer(kPrinterId);
printer.SetUri("ipp://manual.uri");
printer.mutable_ppd_reference()->effective_make_and_model = "Make and model";
ppd_provider_->SetLicenseName("hplip-plugin");
dlc_service_client_.set_install_error(dlcservice::kErrorNone);
dlc_service_client_.set_install_root_path("/root/path");
base::RunLoop run_loop;
PrinterSetupResult result;
manager_->SetUpPrinter(printer, /*is_automatic_installation=*/true,
CallQuitOnRunLoop(&run_loop, &result));
run_loop.Run();
EXPECT_EQ(result, PrinterSetupResult::kSuccess);
EXPECT_TRUE(manager_->IsPrinterInstalled(printer));
}
} // namespace
} // namespace ash
|