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 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "dumpstate_test"
#include "DumpstateInternal.h"
#include "DumpstateService.h"
#include "android/os/BnDumpstate.h"
#include "dumpstate.h"
#include "DumpPool.h"
#include <gmock/gmock.h>
#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include <fcntl.h>
#include <libgen.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <thread>
#include <aidl/android/hardware/dumpstate/IDumpstateDevice.h>
#include <android-base/file.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <android/hardware/dumpstate/1.1/types.h>
#include <cutils/log.h>
#include <cutils/properties.h>
#include <ziparchive/zip_archive.h>
namespace android {
namespace os {
namespace dumpstate {
using DumpstateDeviceAidl = ::aidl::android::hardware::dumpstate::IDumpstateDevice;
using ::android::hardware::dumpstate::V1_1::DumpstateMode;
using ::testing::EndsWith;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::IsNull;
using ::testing::NotNull;
using ::testing::StartsWith;
using ::testing::StrEq;
using ::testing::Test;
using ::testing::internal::CaptureStderr;
using ::testing::internal::CaptureStdout;
using ::testing::internal::GetCapturedStderr;
using ::testing::internal::GetCapturedStdout;
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
class DumpstateListenerMock : public IDumpstateListener {
public:
MOCK_METHOD1(onProgress, binder::Status(int32_t progress));
MOCK_METHOD1(onError, binder::Status(int32_t error_code));
MOCK_METHOD0(onFinished, binder::Status());
MOCK_METHOD1(onScreenshotTaken, binder::Status(bool success));
MOCK_METHOD0(onUiIntensiveBugreportDumpsFinished, binder::Status());
protected:
MOCK_METHOD0(onAsBinder, IBinder*());
};
static int calls_;
// Base class for all tests in this file
class DumpstateBaseTest : public Test {
public:
virtual void SetUp() override {
calls_++;
SetDryRun(false);
}
void SetDryRun(bool dry_run) const {
PropertiesHelper::dry_run_ = dry_run;
}
void SetBuildType(const std::string& build_type) const {
PropertiesHelper::build_type_ = build_type;
}
void SetUnroot(bool unroot) const {
PropertiesHelper::unroot_ = unroot;
}
void SetParallelRun(bool parallel_run) const {
PropertiesHelper::parallel_run_ = parallel_run;
}
bool IsStandalone() const {
return calls_ == 1;
}
void DropRoot() const {
DropRootUser();
uid_t uid = getuid();
ASSERT_EQ(2000, (int)uid);
}
protected:
const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
const std::string kTestDataPath = kTestPath + "/tests/testdata/";
const std::string kSimpleCommand = kTestPath + "/dumpstate_test_fixture";
const std::string kEchoCommand = "/system/bin/echo";
/*
* Copies a text file fixture to a temporary file, returning it's path.
*
* Useful in cases where the test case changes the content of the tile.
*/
std::string CopyTextFileFixture(const std::string& relative_name) {
std::string from = kTestDataPath + relative_name;
// Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
// around for poking when the test fails.
std::string to = kTestDataPath + relative_name + ".tmp";
ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
android::base::RemoveFileIfExists(to);
CopyTextFile(from, to);
return to.c_str();
}
// Need functions that returns void to use assertions -
// https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
void ReadFileToString(const std::string& path, std::string* content) {
ASSERT_TRUE(android::base::ReadFileToString(path, content))
<< "could not read contents from " << path;
}
void WriteStringToFile(const std::string& content, const std::string& path) {
ASSERT_TRUE(android::base::WriteStringToFile(content, path))
<< "could not write contents to " << path;
}
private:
void CopyTextFile(const std::string& from, const std::string& to) {
std::string content;
ReadFileToString(from, &content);
WriteStringToFile(content, to);
}
};
class DumpOptionsTest : public Test {
public:
virtual ~DumpOptionsTest() {
}
virtual void SetUp() {
options_ = Dumpstate::DumpOptions();
}
void TearDown() {
}
Dumpstate::DumpOptions options_;
android::base::unique_fd fd;
};
TEST_F(DumpOptionsTest, InitializeNone) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstate")
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
EXPECT_EQ("", options_.out_dir);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeAdbBugreport) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstatez"),
const_cast<char*>("-S"),
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
EXPECT_TRUE(options_.progress_updates_to_socket);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeAdbShellBugreport) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstate"),
const_cast<char*>("-s"),
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
EXPECT_TRUE(options_.stream_to_socket);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeFullBugReport) {
options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_FULL, fd, fd, true);
EXPECT_TRUE(options_.do_screenshot);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeInteractiveBugReport) {
options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE, fd, fd, true);
EXPECT_TRUE(options_.do_progress_updates);
EXPECT_TRUE(options_.do_screenshot);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeRemoteBugReport) {
options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_REMOTE, fd, fd, false);
EXPECT_TRUE(options_.is_remote_mode);
EXPECT_FALSE(options_.do_vibrate);
EXPECT_FALSE(options_.do_screenshot);
// Other options retain default values
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeWearBugReport) {
options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WEAR, fd, fd, true);
EXPECT_TRUE(options_.do_screenshot);
EXPECT_TRUE(options_.do_progress_updates);
// Other options retain default values
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.do_vibrate);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeTelephonyBugReport) {
options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_TELEPHONY, fd, fd, false);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_TRUE(options_.telephony_only);
EXPECT_TRUE(options_.do_progress_updates);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeWifiBugReport) {
options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WIFI, fd, fd, false);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_TRUE(options_.wifi_only);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeLimitedOnlyBugreport) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstatez"),
const_cast<char*>("-S"),
const_cast<char*>("-q"),
const_cast<char*>("-L"),
const_cast<char*>("-o abc")
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
EXPECT_TRUE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.do_vibrate);
EXPECT_TRUE(options_.limited_only);
EXPECT_EQ(" abc", std::string(options_.out_dir));
// Other options retain default values
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
}
TEST_F(DumpOptionsTest, InitializeDefaultBugReport) {
// default: commandline options are not overridden
// clang-format off
char* argv[] = {
const_cast<char*>("bugreport"),
const_cast<char*>("-d"),
const_cast<char*>("-p"),
const_cast<char*>("-z"),
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
EXPECT_TRUE(options_.do_screenshot);
// Other options retain default values
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.wifi_only);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializePartial1) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstate"),
const_cast<char*>("-s"),
const_cast<char*>("-S"),
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
// TODO: Maybe we should trim the filename
EXPECT_TRUE(options_.stream_to_socket);
EXPECT_TRUE(options_.progress_updates_to_socket);
// Other options retain default values
EXPECT_FALSE(options_.show_header_only);
EXPECT_TRUE(options_.do_vibrate);
EXPECT_FALSE(options_.do_screenshot);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializePartial2) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstate"),
const_cast<char*>("-v"),
const_cast<char*>("-q"),
const_cast<char*>("-p"),
const_cast<char*>("-P"),
const_cast<char*>("-R"),
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
EXPECT_TRUE(options_.show_header_only);
EXPECT_FALSE(options_.do_vibrate);
EXPECT_TRUE(options_.do_screenshot);
EXPECT_TRUE(options_.do_progress_updates);
EXPECT_TRUE(options_.is_remote_mode);
// Other options retain default values
EXPECT_FALSE(options_.stream_to_socket);
EXPECT_FALSE(options_.progress_updates_to_socket);
EXPECT_FALSE(options_.limited_only);
}
TEST_F(DumpOptionsTest, InitializeHelp) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstate"),
const_cast<char*>("-h")
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
// -h is for help.
EXPECT_EQ(status, Dumpstate::RunStatus::HELP);
}
TEST_F(DumpOptionsTest, InitializeUnknown) {
// clang-format off
char* argv[] = {
const_cast<char*>("dumpstate"),
const_cast<char*>("-u") // unknown flag
};
// clang-format on
Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
// -u is unknown.
EXPECT_EQ(status, Dumpstate::RunStatus::INVALID_INPUT);
}
TEST_F(DumpOptionsTest, ValidateOptionsSocketUsage1) {
options_.progress_updates_to_socket = true;
options_.stream_to_socket = true;
EXPECT_FALSE(options_.ValidateOptions());
options_.stream_to_socket = false;
EXPECT_TRUE(options_.ValidateOptions());
}
TEST_F(DumpOptionsTest, ValidateOptionsSocketUsage2) {
options_.do_progress_updates = true;
// Writing to socket = !writing to file.
options_.stream_to_socket = true;
EXPECT_FALSE(options_.ValidateOptions());
options_.stream_to_socket = false;
EXPECT_TRUE(options_.ValidateOptions());
}
TEST_F(DumpOptionsTest, ValidateOptionsRemoteMode) {
options_.do_progress_updates = true;
options_.is_remote_mode = true;
EXPECT_FALSE(options_.ValidateOptions());
options_.do_progress_updates = false;
EXPECT_TRUE(options_.ValidateOptions());
}
class DumpstateTest : public DumpstateBaseTest {
public:
void SetUp() {
DumpstateBaseTest::SetUp();
SetDryRun(false);
SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
ds.progress_.reset(new Progress());
ds.options_.reset(new Dumpstate::DumpOptions());
}
void TearDown() {
ds.ShutdownDumpPool();
}
// Runs a command and capture `stdout` and `stderr`.
int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
const CommandOptions& options = CommandOptions::DEFAULT) {
CaptureStdout();
CaptureStderr();
int status = ds.RunCommand(title, full_command, options);
out = GetCapturedStdout();
err = GetCapturedStderr();
return status;
}
// Dumps a file and capture `stdout` and `stderr`.
int DumpFile(const std::string& title, const std::string& path) {
CaptureStdout();
CaptureStderr();
int status = ds.DumpFile(title, path);
out = GetCapturedStdout();
err = GetCapturedStderr();
return status;
}
void SetProgress(long progress, long initial_max) {
ds.last_reported_percent_progress_ = 0;
ds.options_->do_progress_updates = true;
ds.progress_.reset(new Progress(initial_max, progress, 1.2));
}
void EnableParallelRunIfNeeded() {
ds.EnableParallelRunIfNeeded();
}
std::string GetProgressMessage(int progress, int max,
int old_max = 0, bool update_progress = true) {
EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
bool max_increased = old_max > 0;
std::string message = "";
if (max_increased) {
message =
android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
}
if (update_progress) {
message += android::base::StringPrintf("Setting progress: %d/%d (%d%%)\n",
progress, max, (100 * progress / max));
}
return message;
}
// `stdout` and `stderr` from the last command ran.
std::string out, err;
Dumpstate& ds = Dumpstate::GetInstance();
};
TEST_F(DumpstateTest, RunCommandNoArgs) {
EXPECT_EQ(-1, RunCommand("", {}));
}
TEST_F(DumpstateTest, RunCommandNoTitle) {
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateTest, RunCommandWithTitle) {
EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
EXPECT_THAT(err, StrEq("stderr\n"));
// The duration may not get output, depending on how long it takes,
// so we just check the prefix.
EXPECT_THAT(out,
StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
}
TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
EXPECT_EQ(
0, RunCommand("", {kSimpleCommand},
CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
}
TEST_F(DumpstateTest, RunCommandRedirectStderr) {
EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
CommandOptions::WithTimeout(10).RedirectStderr().Build()));
EXPECT_THAT(out, IsEmpty());
EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
}
TEST_F(DumpstateTest, RunCommandWithOneArg) {
EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("one\n"));
}
TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("one is the loniest number\n"));
}
TEST_F(DumpstateTest, RunCommandDryRun) {
SetDryRun(true);
EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
// The duration may not get output, depending on how long it takes,
// so we just check the prefix.
EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
") ------\n\t(skipped on dry run)\n"));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
SetDryRun(true);
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
EXPECT_THAT(out, IsEmpty());
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateTest, RunCommandDryRunAlways) {
SetDryRun(true);
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateTest, RunCommandNotFound) {
EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
}
TEST_F(DumpstateTest, RunCommandFails) {
EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
" --exit 42' failed: exit code 42\n"));
EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
" --exit 42' failed: exit code 42\n"));
}
TEST_F(DumpstateTest, RunCommandCrashes) {
EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
// We don't know the exit code, so check just the prefix.
EXPECT_THAT(
out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
EXPECT_THAT(
err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
}
TEST_F(DumpstateTest, RunCommandTimesout) {
EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
CommandOptions::WithTimeout(1).Build()));
EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
" --sleep 2' timed out after 1"));
EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
" --sleep 2' timed out after 1"));
}
TEST_F(DumpstateTest, RunCommandIsKilled) {
CaptureStdout();
CaptureStderr();
std::thread t([=]() {
EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
CommandOptions::WithTimeout(100).Always().Build()));
});
// Capture pid and pre-sleep output.
sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
std::string err = GetCapturedStderr();
EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
std::string out = GetCapturedStdout();
std::vector<std::string> lines = android::base::Split(out, "\n");
ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
int pid = atoi(lines[0].c_str());
EXPECT_THAT(lines[1], StrEq("stdout line1"));
EXPECT_THAT(lines[2], IsEmpty()); // \n
// Then kill the process.
CaptureStdout();
CaptureStderr();
ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
t.join();
// Finally, check output after murder.
out = GetCapturedStdout();
err = GetCapturedStderr();
EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
" --pid --sleep 20' failed: killed by signal 15\n"));
EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
" --pid --sleep 20' failed: killed by signal 15\n"));
}
TEST_F(DumpstateTest, RunCommandProgress) {
sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
ds.listener_ = listener;
SetProgress(0, 30);
EXPECT_CALL(*listener, onProgress(66)); // 20/30 %
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
std::string progress_message = GetProgressMessage(20, 30);
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
EXPECT_CALL(*listener, onProgress(80)); // 24/30 %
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
progress_message = GetProgressMessage(24, 30);
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
// Make sure command ran while in dry_run is counted.
SetDryRun(true);
EXPECT_CALL(*listener, onProgress(90)); // 27/30 %
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
progress_message = GetProgressMessage(27, 30);
EXPECT_THAT(out, IsEmpty());
EXPECT_THAT(err, StrEq(progress_message));
SetDryRun(false);
EXPECT_CALL(*listener, onProgress(96)); // 29/30 %
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(2).Build()));
progress_message = GetProgressMessage(29, 30);
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
EXPECT_CALL(*listener, onProgress(100)); // 30/30 %
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
progress_message = GetProgressMessage(30, 30);
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
ds.listener_.clear();
}
TEST_F(DumpstateTest, RunCommandDropRoot) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
return;
}
// First check root case - only available when running with 'adb root'.
uid_t uid = getuid();
if (uid == 0) {
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
EXPECT_THAT(out, StrEq("0\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
return;
}
// Then run dropping root.
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).DropRoot().Build()));
EXPECT_THAT(out, StrEq("2000\nstdout\n"));
EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
}
TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
return;
}
if (!PropertiesHelper::IsUserBuild()) {
// Emulates user build if necessarily.
SetBuildType("user");
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
// We don't know the exact path of su, so we just check for the 'root ...' commands
EXPECT_THAT(out, StartsWith("Skipping"));
EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
return;
}
if (PropertiesHelper::IsUserBuild()) {
ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
return;
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRoot().Build()));
EXPECT_THAT(out, StrEq("0\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild_withUnroot) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE(
"Skipping DumpstateTest.RunCommandAsRootNonUserBuild_withUnroot() "
"on test suite\n")
return;
}
if (PropertiesHelper::IsUserBuild()) {
ALOGI("Skipping RunCommandAsRootNonUserBuild_withUnroot on user builds\n");
return;
}
// Same test as above, but with unroot property set, which will override su availability.
SetUnroot(true);
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRoot().Build()));
// AsRoot is ineffective.
EXPECT_THAT(out, StrEq("2000\nstdout\n"));
EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
}
TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnUserBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
return;
}
if (!PropertiesHelper::IsUserBuild()) {
// Emulates user build if necessarily.
SetBuildType("user");
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
EXPECT_THAT(out, StrEq("2000\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
return;
}
if (PropertiesHelper::IsUserBuild()) {
ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
return;
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
EXPECT_THAT(out, StrEq("0\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild_withUnroot) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE(
"Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild_withUnroot() "
"on test suite\n")
return;
}
if (PropertiesHelper::IsUserBuild()) {
ALOGI("Skipping RunCommandAsRootIfAvailableOnDebugBuild_withUnroot on user builds\n");
return;
}
// Same test as above, but with unroot property set, which will override su availability.
SetUnroot(true);
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
// It's a userdebug build, so "su root" should be available, but unroot=true overrides it.
EXPECT_THAT(out, StrEq("2000\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
EXPECT_THAT(out,
StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
EXPECT_THAT(err, IsEmpty());
// The duration may not get output, depending on how long it takes,
// so we just check the prefix.
EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
"such file or directory\n"));
}
TEST_F(DumpstateTest, DumpFileSingleLine) {
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
}
TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\n"));
}
TEST_F(DumpstateTest, DumpFileMultipleLines) {
EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
}
TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
}
TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
SetDryRun(true);
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, IsEmpty());
}
TEST_F(DumpstateTest, DumpFileOnDryRun) {
SetDryRun(true);
EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(
out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n"));
}
TEST_F(DumpstateTest, DumpFileUpdateProgress) {
sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
ds.listener_ = listener;
SetProgress(0, 30);
EXPECT_CALL(*listener, onProgress(16)); // 5/30 %
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
std::string progress_message = GetProgressMessage(5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
EXPECT_THAT(err, StrEq(progress_message));
EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
ds.listener_.clear();
}
TEST_F(DumpstateTest, DumpPool_withParallelRunEnabled_notNull) {
SetParallelRun(true);
EnableParallelRunIfNeeded();
EXPECT_TRUE(ds.zip_entry_tasks_);
EXPECT_TRUE(ds.dump_pool_);
}
TEST_F(DumpstateTest, DumpPool_withParallelRunDisabled_isNull) {
SetParallelRun(false);
EnableParallelRunIfNeeded();
EXPECT_FALSE(ds.zip_entry_tasks_);
EXPECT_FALSE(ds.dump_pool_);
}
class ZippedBugReportStreamTest : public DumpstateBaseTest {
public:
void SetUp() {
DumpstateBaseTest::SetUp();
ds_.options_.reset(new Dumpstate::DumpOptions());
}
void TearDown() {
CloseArchive(handle_);
}
// Set bugreport mode and options before here.
void GenerateBugreport() {
ds_.Initialize();
EXPECT_EQ(Dumpstate::RunStatus::OK, ds_.Run(/*calling_uid=*/-1, /*calling_package=*/""));
}
// Most bugreports droproot, ensure the file can be opened by shell to verify file content.
void CreateFd(const std::string& path, android::base::unique_fd* out_fd) {
out_fd->reset(TEMP_FAILURE_RETRY(open(path.c_str(),
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
ASSERT_GE(out_fd->get(), 0) << "could not create FD for path " << path;
}
void VerifyEntry(const ZipArchiveHandle archive, const std::string_view entry_name,
ZipEntry* data) {
int32_t e = FindEntry(archive, entry_name, data);
EXPECT_EQ(0, e) << ErrorCodeString(e) << " entry name: " << entry_name;
}
// While testing dumpstate in process, using STDOUT may get confused about
// the internal fd redirection. Redirect to a dedicate fd to save content.
void RedirectOutputToFd(android::base::unique_fd& ufd) {
ds_.open_socket_fn_ = [&](const char*) -> int { return ufd.release(); };
};
Dumpstate& ds_ = Dumpstate::GetInstance();
ZipArchiveHandle handle_;
};
// Generate a quick LimitedOnly report redirected to a file, open it and verify entry exist.
// TODO: broken test tracked in b/249983726
TEST_F(ZippedBugReportStreamTest, DISABLED_StreamLimitedOnlyReport) {
std::string out_path = kTestDataPath + "StreamLimitedOnlyReportOut.zip";
android::base::unique_fd out_fd;
CreateFd(out_path, &out_fd);
ds_.options_->limited_only = true;
ds_.options_->stream_to_socket = true;
RedirectOutputToFd(out_fd);
GenerateBugreport();
OpenArchive(out_path.c_str(), &handle_);
ZipEntry entry;
VerifyEntry(handle_, "main_entry.txt", &entry);
std::string bugreport_txt_name;
bugreport_txt_name.resize(entry.uncompressed_length);
ExtractToMemory(handle_, &entry, reinterpret_cast<uint8_t*>(bugreport_txt_name.data()),
entry.uncompressed_length);
EXPECT_THAT(bugreport_txt_name,
testing::ContainsRegex("(bugreport-.+(-[[:digit:]]+){6}\\.txt)"));
VerifyEntry(handle_, bugreport_txt_name, &entry);
}
class DumpstateServiceTest : public DumpstateBaseTest {
public:
DumpstateService dss;
};
class ProgressTest : public DumpstateBaseTest {
public:
Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
return Progress(max, growth_factor, path);
}
void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
std::string expected_content =
android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
std::string actual_content;
ReadFileToString(path, &actual_content);
ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
}
};
TEST_F(ProgressTest, SimpleTest) {
Progress progress;
EXPECT_EQ(0, progress.Get());
EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
bool max_increased = progress.Inc(1);
EXPECT_EQ(1, progress.Get());
EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
EXPECT_FALSE(max_increased);
// Ignore negative increase.
max_increased = progress.Inc(-1);
EXPECT_EQ(1, progress.Get());
EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
EXPECT_FALSE(max_increased);
}
TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
Progress progress = GetInstance(10, 1.2); // 20% growth factor
EXPECT_EQ(0, progress.Get());
EXPECT_EQ(10, progress.GetInitialMax());
EXPECT_EQ(10, progress.GetMax());
// No increase
bool max_increased = progress.Inc(10);
EXPECT_EQ(10, progress.Get());
EXPECT_EQ(10, progress.GetMax());
EXPECT_FALSE(max_increased);
// Increase, with new value < max*20%
max_increased = progress.Inc(1);
EXPECT_EQ(11, progress.Get());
EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
EXPECT_TRUE(max_increased);
}
TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
Progress progress = GetInstance(10, 1.2); // 20% growth factor
EXPECT_EQ(0, progress.Get());
EXPECT_EQ(10, progress.GetInitialMax());
EXPECT_EQ(10, progress.GetMax());
// No increase
bool max_increased = progress.Inc(10);
EXPECT_EQ(10, progress.Get());
EXPECT_EQ(10, progress.GetMax());
EXPECT_FALSE(max_increased);
// Increase, with new value > max*20%
max_increased = progress.Inc(5);
EXPECT_EQ(15, progress.Get());
EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
EXPECT_TRUE(max_increased);
}
TEST_F(ProgressTest, InvalidPath) {
Progress progress("/devil/null");
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, EmptyFile) {
Progress progress(CopyTextFileFixture("empty-file.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLineBothNAN) {
Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
}
// Tests stats are properly saved when the file does not exists.
TEST_F(ProgressTest, FirstTime) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it's failing when running as suite
MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
return;
}
std::string path = kTestDataPath + "FirstTime.txt";
android::base::RemoveFileIfExists(path);
Progress run1(path);
EXPECT_EQ(0, run1.Get());
EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
bool max_increased = run1.Inc(20);
EXPECT_EQ(20, run1.Get());
EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
EXPECT_FALSE(max_increased);
run1.Save();
AssertStats(path, 1, 20);
}
// Tests what happens when the persistent settings contains the average duration of 1 run.
// Data on file is 1 run and 109 average.
TEST_F(ProgressTest, SecondTime) {
std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
Progress run1 = GetInstance(-42, 1.2, path);
EXPECT_EQ(0, run1.Get());
EXPECT_EQ(10, run1.GetInitialMax());
EXPECT_EQ(10, run1.GetMax());
bool max_increased = run1.Inc(20);
EXPECT_EQ(20, run1.Get());
EXPECT_EQ(24, run1.GetMax());
EXPECT_TRUE(max_increased);
// Average now is 2 runs and (10 + 20)/ 2 = 15
run1.Save();
AssertStats(path, 2, 15);
Progress run2 = GetInstance(-42, 1.2, path);
EXPECT_EQ(0, run2.Get());
EXPECT_EQ(15, run2.GetInitialMax());
EXPECT_EQ(15, run2.GetMax());
max_increased = run2.Inc(25);
EXPECT_EQ(25, run2.Get());
EXPECT_EQ(30, run2.GetMax());
EXPECT_TRUE(max_increased);
// Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
run2.Save();
AssertStats(path, 3, 18);
Progress run3 = GetInstance(-42, 1.2, path);
EXPECT_EQ(0, run3.Get());
EXPECT_EQ(18, run3.GetInitialMax());
EXPECT_EQ(18, run3.GetMax());
// Make sure average decreases as well
max_increased = run3.Inc(5);
EXPECT_EQ(5, run3.Get());
EXPECT_EQ(18, run3.GetMax());
EXPECT_FALSE(max_increased);
// Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
run3.Save();
AssertStats(path, 4, 14);
}
// Tests what happens when the persistent settings contains the average duration of 2 runs.
// Data on file is 2 runs and 15 average.
TEST_F(ProgressTest, ThirdTime) {
std::string path = CopyTextFileFixture("stats-two-runs.txt");
AssertStats(path, 2, 15); // Sanity check
Progress run1 = GetInstance(-42, 1.2, path);
EXPECT_EQ(0, run1.Get());
EXPECT_EQ(15, run1.GetInitialMax());
EXPECT_EQ(15, run1.GetMax());
bool max_increased = run1.Inc(20);
EXPECT_EQ(20, run1.Get());
EXPECT_EQ(24, run1.GetMax());
EXPECT_TRUE(max_increased);
// Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
run1.Save();
AssertStats(path, 3, 16);
}
class DumpstateUtilTest : public DumpstateBaseTest {
public:
void SetUp() {
DumpstateBaseTest::SetUp();
SetDryRun(false);
}
void CaptureFdOut() {
ReadFileToString(path_, &out);
}
void CreateFd(const std::string& name) {
path_ = kTestDataPath + name;
MYLOGD("Creating fd for file %s\n", path_.c_str());
fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
}
// Runs a command into the `fd` and capture `stderr`.
int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
const CommandOptions& options = CommandOptions::DEFAULT) {
CaptureStderr();
int status = RunCommandToFd(fd, title, full_command, options);
close(fd);
CaptureFdOut();
err = GetCapturedStderr();
return status;
}
// Dumps a file and into the `fd` and `stderr`.
int DumpFile(const std::string& title, const std::string& path) {
CaptureStderr();
int status = DumpFileToFd(fd, title, path);
close(fd);
CaptureFdOut();
err = GetCapturedStderr();
return status;
}
int fd;
// 'fd` output and `stderr` from the last command ran.
std::string out, err;
private:
std::string path_;
};
TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
CreateFd("RunCommandNoArgs.txt");
EXPECT_EQ(-1, RunCommand("", {}));
}
TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
CreateFd("RunCommandWithNoArgs.txt");
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
CreateFd("RunCommandWithNoArgs.txt");
EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
CreateFd("RunCommandWithOneArg.txt");
EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("one\n"));
}
TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
CreateFd("RunCommandWithMultipleArgs.txt");
EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("one is the loniest number\n"));
}
TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
CreateFd("RunCommandWithLoggingMessage.txt");
EXPECT_EQ(
0, RunCommand("", {kSimpleCommand},
CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
CreateFd("RunCommandRedirectStderr.txt");
EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
CommandOptions::WithTimeout(10).RedirectStderr().Build()));
EXPECT_THAT(out, IsEmpty());
EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandDryRun) {
CreateFd("RunCommandDryRun.txt");
SetDryRun(true);
EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
EXPECT_THAT(out, StrEq(android::base::StringPrintf(
"------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
kSimpleCommand.c_str())));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
CreateFd("RunCommandDryRun.txt");
SetDryRun(true);
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
EXPECT_THAT(
out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
CreateFd("RunCommandDryRunAlways.txt");
SetDryRun(true);
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
EXPECT_THAT(out, StrEq("stdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandNotFound) {
CreateFd("RunCommandNotFound.txt");
EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
}
TEST_F(DumpstateUtilTest, RunCommandFails) {
CreateFd("RunCommandFails.txt");
EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
" --exit 42' failed: exit code 42\n"));
EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
" --exit 42' failed: exit code 42\n"));
}
TEST_F(DumpstateUtilTest, RunCommandCrashes) {
CreateFd("RunCommandCrashes.txt");
EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
// We don't know the exit code, so check just the prefix.
EXPECT_THAT(
out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
EXPECT_THAT(
err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
}
TEST_F(DumpstateUtilTest, RunCommandTimesoutWithSec) {
CreateFd("RunCommandTimesout.txt");
EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
CommandOptions::WithTimeout(1).Build()));
EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
" --sleep 2' timed out after 1"));
EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
" --sleep 2' timed out after 1"));
}
TEST_F(DumpstateUtilTest, RunCommandTimesoutWithMsec) {
CreateFd("RunCommandTimesout.txt");
EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
CommandOptions::WithTimeoutInMs(1000).Build()));
EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
" --sleep 2' timed out after 1"));
EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
" --sleep 2' timed out after 1"));
}
TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
CreateFd("RunCommandIsKilled.txt");
CaptureStderr();
std::thread t([=]() {
EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
CommandOptions::WithTimeout(100).Always().Build()));
});
// Capture pid and pre-sleep output.
sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
std::string err = GetCapturedStderr();
EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
CaptureFdOut();
std::vector<std::string> lines = android::base::Split(out, "\n");
ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
int pid = atoi(lines[0].c_str());
EXPECT_THAT(lines[1], StrEq("stdout line1"));
EXPECT_THAT(lines[2], IsEmpty()); // \n
// Then kill the process.
CaptureFdOut();
CaptureStderr();
ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
t.join();
// Finally, check output after murder.
CaptureFdOut();
err = GetCapturedStderr();
// out starts with the pid, which is an unknown
EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
" --pid --sleep 20' failed: killed by signal 15\n"));
EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
" --pid --sleep 20' failed: killed by signal 15\n"));
}
TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
return;
}
CreateFd("RunCommandAsRootUserBuild.txt");
if (!PropertiesHelper::IsUserBuild()) {
// Emulates user build if necessarily.
SetBuildType("user");
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
// We don't know the exact path of su, so we just check for the 'root ...' commands
EXPECT_THAT(out, StartsWith("Skipping"));
EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
return;
}
CreateFd("RunCommandAsRootNonUserBuild.txt");
if (PropertiesHelper::IsUserBuild()) {
ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
return;
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRoot().Build()));
EXPECT_THAT(out, StrEq("0\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnUserBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
return;
}
CreateFd("RunCommandAsRootIfAvailableOnUserBuild.txt");
if (!PropertiesHelper::IsUserBuild()) {
// Emulates user build if necessarily.
SetBuildType("user");
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
EXPECT_THAT(out, StrEq("2000\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnDebugBuild) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
return;
}
CreateFd("RunCommandAsRootIfAvailableOnDebugBuild.txt");
if (PropertiesHelper::IsUserBuild()) {
ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
return;
}
DropRoot();
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
EXPECT_THAT(out, StrEq("0\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
}
TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
if (!IsStandalone()) {
// TODO: temporarily disabled because it might cause other tests to fail after dropping
// to Shell - need to refactor tests to avoid this problem)
MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
return;
}
CreateFd("RunCommandDropRoot.txt");
// First check root case - only available when running with 'adb root'.
uid_t uid = getuid();
if (uid == 0) {
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
EXPECT_THAT(out, StrEq("0\nstdout\n"));
EXPECT_THAT(err, StrEq("stderr\n"));
return;
}
// Then run dropping root.
EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
CommandOptions::WithTimeout(1).DropRoot().Build()));
EXPECT_THAT(out, StrEq("2000\nstdout\n"));
EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
}
TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
CreateFd("DumpFileNotFound.txt");
EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
EXPECT_THAT(out,
StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
CreateFd("DumpFileNotFound.txt");
EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
"file or directory\n"));
EXPECT_THAT(err, IsEmpty());
}
TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
CreateFd("DumpFileSingleLine.txt");
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
}
TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
CreateFd("DumpFileSingleLineWithNewLine.txt");
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\n"));
}
TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
CreateFd("DumpFileMultipleLines.txt");
EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
}
TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
CreateFd("DumpFileMultipleLinesWithNewLine.txt");
EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
}
TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
CreateFd("DumpFileOnDryRun.txt");
SetDryRun(true);
std::string path = kTestDataPath + "single-line.txt";
EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
}
TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
CreateFd("DumpFileOnDryRun.txt");
SetDryRun(true);
std::string path = kTestDataPath + "single-line.txt";
EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
EXPECT_THAT(err, IsEmpty());
EXPECT_THAT(
out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
}
class DumpPoolTest : public DumpstateBaseTest {
public:
void SetUp() {
dump_pool_ = std::make_unique<DumpPool>(kTestDataPath);
DumpstateBaseTest::SetUp();
CreateOutputFile();
}
void CreateOutputFile() {
out_path_ = kTestDataPath + "out.txt";
out_fd_.reset(TEMP_FAILURE_RETRY(open(out_path_.c_str(),
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
ASSERT_GE(out_fd_.get(), 0) << "could not create FD for path "
<< out_path_;
}
int getTempFileCounts(const std::string& folder) {
int count = 0;
std::unique_ptr<DIR, decltype(&closedir)> dir_ptr(opendir(folder.c_str()),
&closedir);
if (!dir_ptr) {
return -1;
}
int dir_fd = dirfd(dir_ptr.get());
if (dir_fd < 0) {
return -1;
}
struct dirent* de;
while ((de = readdir(dir_ptr.get()))) {
if (de->d_type != DT_REG) {
continue;
}
std::string file_name(de->d_name);
if (file_name.find(DumpPool::PREFIX_TMPFILE_NAME) != 0) {
continue;
}
count++;
}
return count;
}
void setLogDuration(bool log_duration) {
dump_pool_->setLogDuration(log_duration);
}
std::unique_ptr<DumpPool> dump_pool_;
android::base::unique_fd out_fd_;
std::string out_path_;
};
TEST_F(DumpPoolTest, EnqueueTaskWithFd) {
auto dump_func_1 = [](int out_fd) {
dprintf(out_fd, "A");
};
auto dump_func_2 = [](int out_fd) {
dprintf(out_fd, "B");
sleep(1);
};
auto dump_func_3 = [](int out_fd) {
dprintf(out_fd, "C");
};
setLogDuration(/* log_duration = */false);
auto t1 = dump_pool_->enqueueTaskWithFd("", dump_func_1, std::placeholders::_1);
auto t2 = dump_pool_->enqueueTaskWithFd("", dump_func_2, std::placeholders::_1);
auto t3 = dump_pool_->enqueueTaskWithFd("", dump_func_3, std::placeholders::_1);
WaitForTask(std::move(t1), "", out_fd_.get());
WaitForTask(std::move(t2), "", out_fd_.get());
WaitForTask(std::move(t3), "", out_fd_.get());
std::string result;
ReadFileToString(out_path_, &result);
EXPECT_THAT(result, StrEq("A\nB\nC\n"));
EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
}
TEST_F(DumpPoolTest, EnqueueTask_withDurationLog) {
bool run_1 = false;
auto dump_func_1 = [&]() {
run_1 = true;
};
auto t1 = dump_pool_->enqueueTask(/* duration_title = */"1", dump_func_1);
WaitForTask(std::move(t1), "", out_fd_.get());
std::string result;
ReadFileToString(out_path_, &result);
EXPECT_TRUE(run_1);
EXPECT_THAT(result, StrEq("------ 0.000s was the duration of '1' ------\n"));
EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
}
class TaskQueueTest : public DumpstateBaseTest {
public:
void SetUp() {
DumpstateBaseTest::SetUp();
}
TaskQueue task_queue_;
};
TEST_F(TaskQueueTest, runTask) {
bool is_task1_run = false;
bool is_task2_run = false;
auto task_1 = [&](bool task_cancelled) {
if (task_cancelled) {
return;
}
is_task1_run = true;
};
auto task_2 = [&](bool task_cancelled) {
if (task_cancelled) {
return;
}
is_task2_run = true;
};
task_queue_.add(task_1, std::placeholders::_1);
task_queue_.add(task_2, std::placeholders::_1);
task_queue_.run(/* do_cancel = */false);
EXPECT_TRUE(is_task1_run);
EXPECT_TRUE(is_task2_run);
}
TEST_F(TaskQueueTest, runTask_withCancelled) {
bool is_task1_cancelled = false;
bool is_task2_cancelled = false;
auto task_1 = [&](bool task_cancelled) {
is_task1_cancelled = task_cancelled;
};
auto task_2 = [&](bool task_cancelled) {
is_task2_cancelled = task_cancelled;
};
task_queue_.add(task_1, std::placeholders::_1);
task_queue_.add(task_2, std::placeholders::_1);
task_queue_.run(/* do_cancel = */true);
EXPECT_TRUE(is_task1_cancelled);
EXPECT_TRUE(is_task2_cancelled);
}
} // namespace dumpstate
} // namespace os
} // namespace android
|