blob: 93d8cdfb8325b6aa2793ea1aa52c7c592b7eca0b [file] [log] [blame]
Felipe Leme4c2d6632016-09-28 14:32:00 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dieter Hsu105ad0c2020-09-29 15:23:33 +080017#define LOG_TAG "dumpstate_test"
Felipe Leme75876a22016-10-27 16:31:27 -070018
Felipe Lemef0292972016-11-22 13:57:05 -080019#include "DumpstateInternal.h"
Felipe Leme75876a22016-10-27 16:31:27 -070020#include "DumpstateService.h"
21#include "android/os/BnDumpstate.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070022#include "dumpstate.h"
Rhed Jao27077b12020-07-14 18:38:08 +080023#include "DumpPool.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070024
25#include <gmock/gmock.h>
Dieter Hsu105ad0c2020-09-29 15:23:33 +080026#include <gmock/gmock-matchers.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070027#include <gtest/gtest.h>
28
Felipe Leme46b85da2016-11-21 17:40:45 -080029#include <fcntl.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070030#include <libgen.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070031#include <signal.h>
32#include <sys/types.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070033#include <unistd.h>
Kean Mariotti306633e2022-09-05 16:30:47 +000034#include <filesystem>
Felipe Lemefd8affa2016-09-30 17:38:57 -070035#include <thread>
Felipe Leme4c2d6632016-09-28 14:32:00 -070036
Kedar Chitnis9fd8c052021-11-16 09:09:22 +000037#include <aidl/android/hardware/dumpstate/IDumpstateDevice.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070038#include <android-base/file.h>
Felipe Lemed80e6b62016-10-03 13:08:14 -070039#include <android-base/properties.h>
40#include <android-base/stringprintf.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070041#include <android-base/strings.h>
Abhijeet Kaure370d682019-10-01 16:49:30 +010042#include <android-base/unique_fd.h>
Hunter Knepshield8540faf2020-02-04 19:47:20 -080043#include <android/hardware/dumpstate/1.1/types.h>
Dieter Hsu105ad0c2020-09-29 15:23:33 +080044#include <cutils/log.h>
Hunter Knepshield8540faf2020-02-04 19:47:20 -080045#include <cutils/properties.h>
Dieter Hsu105ad0c2020-09-29 15:23:33 +080046#include <ziparchive/zip_archive.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070047
Felipe Leme47e9be22016-12-21 15:37:07 -080048namespace android {
49namespace os {
50namespace dumpstate {
Felipe Lemed80e6b62016-10-03 13:08:14 -070051
Kedar Chitnis9fd8c052021-11-16 09:09:22 +000052using DumpstateDeviceAidl = ::aidl::android::hardware::dumpstate::IDumpstateDevice;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080053using ::android::hardware::dumpstate::V1_1::DumpstateMode;
Felipe Leme4c2d6632016-09-28 14:32:00 -070054using ::testing::EndsWith;
Rhed Jao27077b12020-07-14 18:38:08 +080055using ::testing::Eq;
Felipe Leme46b85da2016-11-21 17:40:45 -080056using ::testing::HasSubstr;
Felipe Leme4c2d6632016-09-28 14:32:00 -070057using ::testing::IsEmpty;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080058using ::testing::IsNull;
Felipe Leme009ecbb2016-11-07 10:18:44 -080059using ::testing::NotNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070060using ::testing::StartsWith;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080061using ::testing::StrEq;
Felipe Leme4c2d6632016-09-28 14:32:00 -070062using ::testing::Test;
63using ::testing::internal::CaptureStderr;
64using ::testing::internal::CaptureStdout;
65using ::testing::internal::GetCapturedStderr;
66using ::testing::internal::GetCapturedStdout;
67
Nandana Dutt3f8c7172018-09-25 12:01:54 +010068#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
69
Felipe Leme75876a22016-10-27 16:31:27 -070070class DumpstateListenerMock : public IDumpstateListener {
71 public:
Nandana Dutta6a28bd2019-01-14 16:54:38 +000072 MOCK_METHOD1(onProgress, binder::Status(int32_t progress));
73 MOCK_METHOD1(onError, binder::Status(int32_t error_code));
Gavin Corkerya44686c2022-11-23 18:16:51 +000074 MOCK_METHOD1(onFinished, binder::Status(const std::string& bugreport_file));
Paul Chang0d2aad72020-02-13 20:04:03 +080075 MOCK_METHOD1(onScreenshotTaken, binder::Status(bool success));
Paul Chang5702b482020-05-28 22:05:47 +080076 MOCK_METHOD0(onUiIntensiveBugreportDumpsFinished, binder::Status());
Felipe Leme75876a22016-10-27 16:31:27 -070077
78 protected:
79 MOCK_METHOD0(onAsBinder, IBinder*());
80};
81
Felipe Leme46b85da2016-11-21 17:40:45 -080082static int calls_;
83
Felipe Leme7447d7c2016-11-03 18:12:22 -070084// Base class for all tests in this file
85class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080086 public:
87 virtual void SetUp() override {
88 calls_++;
Felipe Lemef0292972016-11-22 13:57:05 -080089 SetDryRun(false);
Felipe Leme46b85da2016-11-21 17:40:45 -080090 }
91
Felipe Lemef0292972016-11-22 13:57:05 -080092 void SetDryRun(bool dry_run) const {
93 PropertiesHelper::dry_run_ = dry_run;
94 }
95
96 void SetBuildType(const std::string& build_type) const {
97 PropertiesHelper::build_type_ = build_type;
98 }
99
Nandana Dutt4b392be2018-11-02 16:17:05 +0000100 void SetUnroot(bool unroot) const {
101 PropertiesHelper::unroot_ = unroot;
102 }
103
Rhed Jao1c855122020-07-16 17:37:39 +0800104 void SetParallelRun(bool parallel_run) const {
105 PropertiesHelper::parallel_run_ = parallel_run;
106 }
107
Felipe Lemef0292972016-11-22 13:57:05 -0800108 bool IsStandalone() const {
Felipe Leme46b85da2016-11-21 17:40:45 -0800109 return calls_ == 1;
110 }
111
Felipe Lemef0292972016-11-22 13:57:05 -0800112 void DropRoot() const {
113 DropRootUser();
Felipe Leme46b85da2016-11-21 17:40:45 -0800114 uid_t uid = getuid();
115 ASSERT_EQ(2000, (int)uid);
116 }
117
Felipe Leme7447d7c2016-11-03 18:12:22 -0700118 protected:
119 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
Dan Shie177e8e2019-06-20 11:08:14 -0700120 const std::string kTestDataPath = kTestPath + "/tests/testdata/";
121 const std::string kSimpleCommand = kTestPath + "/dumpstate_test_fixture";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700122 const std::string kEchoCommand = "/system/bin/echo";
123
124 /*
125 * Copies a text file fixture to a temporary file, returning it's path.
126 *
127 * Useful in cases where the test case changes the content of the tile.
128 */
129 std::string CopyTextFileFixture(const std::string& relative_name) {
130 std::string from = kTestDataPath + relative_name;
131 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
132 // around for poking when the test fails.
133 std::string to = kTestDataPath + relative_name + ".tmp";
134 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
135 android::base::RemoveFileIfExists(to);
136 CopyTextFile(from, to);
137 return to.c_str();
138 }
139
Felipe Leme46b85da2016-11-21 17:40:45 -0800140 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700141 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800142 void ReadFileToString(const std::string& path, std::string* content) {
143 ASSERT_TRUE(android::base::ReadFileToString(path, content))
144 << "could not read contents from " << path;
145 }
146 void WriteStringToFile(const std::string& content, const std::string& path) {
147 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
148 << "could not write contents to " << path;
149 }
150
151 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700152 void CopyTextFile(const std::string& from, const std::string& to) {
153 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800154 ReadFileToString(from, &content);
155 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700156 }
157};
158
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100159class DumpOptionsTest : public Test {
160 public:
161 virtual ~DumpOptionsTest() {
162 }
163 virtual void SetUp() {
164 options_ = Dumpstate::DumpOptions();
165 }
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000166 void TearDown() {
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000167 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100168 Dumpstate::DumpOptions options_;
Abhijeet Kaure370d682019-10-01 16:49:30 +0100169 android::base::unique_fd fd;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100170};
171
172TEST_F(DumpOptionsTest, InitializeNone) {
173 // clang-format off
174 char* argv[] = {
175 const_cast<char*>("dumpstate")
176 };
177 // clang-format on
178
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100179 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
180
181 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Nandana Dutt58d72e22018-11-16 10:30:48 +0000182
mhasank3a4cfb42020-06-15 18:06:43 -0700183 EXPECT_EQ("", options_.out_dir);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800184 EXPECT_FALSE(options_.stream_to_socket);
185 EXPECT_FALSE(options_.progress_updates_to_socket);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100186 EXPECT_FALSE(options_.show_header_only);
187 EXPECT_TRUE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800188 EXPECT_FALSE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100189 EXPECT_FALSE(options_.do_progress_updates);
190 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700191 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000192}
193
194TEST_F(DumpOptionsTest, InitializeAdbBugreport) {
195 // clang-format off
196 char* argv[] = {
197 const_cast<char*>("dumpstatez"),
198 const_cast<char*>("-S"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000199 };
200 // clang-format on
201
202 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
203
204 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800205 EXPECT_TRUE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000206
207 // Other options retain default values
208 EXPECT_TRUE(options_.do_vibrate);
209 EXPECT_FALSE(options_.show_header_only);
Paul Chang0d2aad72020-02-13 20:04:03 +0800210 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000211 EXPECT_FALSE(options_.do_progress_updates);
212 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800213 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700214 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000215}
216
217TEST_F(DumpOptionsTest, InitializeAdbShellBugreport) {
218 // clang-format off
219 char* argv[] = {
220 const_cast<char*>("dumpstate"),
221 const_cast<char*>("-s"),
222 };
223 // clang-format on
224
225 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
226
227 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800228 EXPECT_TRUE(options_.stream_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000229
230 // Other options retain default values
231 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800232 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000233 EXPECT_FALSE(options_.show_header_only);
Paul Chang0d2aad72020-02-13 20:04:03 +0800234 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000235 EXPECT_FALSE(options_.do_progress_updates);
236 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700237 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000238}
239
240TEST_F(DumpOptionsTest, InitializeFullBugReport) {
Kean Mariotti306633e2022-09-05 16:30:47 +0000241 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_FULL, 0, fd, fd, true);
Paul Chang0d2aad72020-02-13 20:04:03 +0800242 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000243
244 // Other options retain default values
245 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800246 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000247 EXPECT_FALSE(options_.show_header_only);
248 EXPECT_FALSE(options_.do_progress_updates);
249 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800250 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700251 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000252}
253
254TEST_F(DumpOptionsTest, InitializeInteractiveBugReport) {
Kean Mariotti306633e2022-09-05 16:30:47 +0000255 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE, 0, fd, fd, true);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000256 EXPECT_TRUE(options_.do_progress_updates);
Paul Chang0d2aad72020-02-13 20:04:03 +0800257 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000258
259 // Other options retain default values
260 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800261 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000262 EXPECT_FALSE(options_.show_header_only);
263 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800264 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700265 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000266}
267
268TEST_F(DumpOptionsTest, InitializeRemoteBugReport) {
Kean Mariotti306633e2022-09-05 16:30:47 +0000269 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_REMOTE, 0, fd, fd, false);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000270 EXPECT_TRUE(options_.is_remote_mode);
271 EXPECT_FALSE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800272 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000273
274 // Other options retain default values
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800275 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000276 EXPECT_FALSE(options_.show_header_only);
277 EXPECT_FALSE(options_.do_progress_updates);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800278 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700279 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000280}
281
282TEST_F(DumpOptionsTest, InitializeWearBugReport) {
Kean Mariotti306633e2022-09-05 16:30:47 +0000283 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WEAR, 0, fd, fd, true);
Paul Chang0d2aad72020-02-13 20:04:03 +0800284 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000285 EXPECT_TRUE(options_.do_progress_updates);
Kedar Chitnis9fd8c052021-11-16 09:09:22 +0000286
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000287
288 // Other options retain default values
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800289 EXPECT_FALSE(options_.progress_updates_to_socket);
Robert Gindada7d6702023-04-03 22:53:20 +0000290 EXPECT_FALSE(options_.do_vibrate);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000291 EXPECT_FALSE(options_.show_header_only);
292 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800293 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700294 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000295}
296
297TEST_F(DumpOptionsTest, InitializeTelephonyBugReport) {
Kean Mariotti306633e2022-09-05 16:30:47 +0000298 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_TELEPHONY, 0, fd, fd, false);
Paul Chang0d2aad72020-02-13 20:04:03 +0800299 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000300 EXPECT_TRUE(options_.telephony_only);
Hunter Knepshield820f9bc2020-02-05 20:10:53 -0800301 EXPECT_TRUE(options_.do_progress_updates);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000302
303 // Other options retain default values
304 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800305 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000306 EXPECT_FALSE(options_.show_header_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000307 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800308 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700309 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000310}
311
312TEST_F(DumpOptionsTest, InitializeWifiBugReport) {
Kean Mariotti306633e2022-09-05 16:30:47 +0000313 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WIFI, 0, fd, fd, false);
Paul Chang0d2aad72020-02-13 20:04:03 +0800314 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000315 EXPECT_TRUE(options_.wifi_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000316
317 // Other options retain default values
318 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800319 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000320 EXPECT_FALSE(options_.show_header_only);
321 EXPECT_FALSE(options_.do_progress_updates);
322 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800323 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700324 EXPECT_FALSE(options_.limited_only);
325}
326
327TEST_F(DumpOptionsTest, InitializeLimitedOnlyBugreport) {
328 // clang-format off
329 char* argv[] = {
330 const_cast<char*>("dumpstatez"),
331 const_cast<char*>("-S"),
mhasankd451a472020-05-26 18:02:39 -0700332 const_cast<char*>("-q"),
mhasank2d75c442020-06-11 15:05:25 -0700333 const_cast<char*>("-L"),
334 const_cast<char*>("-o abc")
mhasankd451a472020-05-26 18:02:39 -0700335 };
336 // clang-format on
337
338 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
339
340 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800341 EXPECT_TRUE(options_.progress_updates_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700342 EXPECT_FALSE(options_.do_vibrate);
343 EXPECT_TRUE(options_.limited_only);
mhasank3a4cfb42020-06-15 18:06:43 -0700344 EXPECT_EQ(" abc", std::string(options_.out_dir));
mhasankd451a472020-05-26 18:02:39 -0700345
346 // Other options retain default values
347 EXPECT_FALSE(options_.show_header_only);
348 EXPECT_FALSE(options_.do_screenshot);
349 EXPECT_FALSE(options_.do_progress_updates);
350 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800351 EXPECT_FALSE(options_.stream_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000352}
353
354TEST_F(DumpOptionsTest, InitializeDefaultBugReport) {
355 // default: commandline options are not overridden
356 // clang-format off
357 char* argv[] = {
358 const_cast<char*>("bugreport"),
359 const_cast<char*>("-d"),
360 const_cast<char*>("-p"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000361 const_cast<char*>("-z"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000362 };
363 // clang-format on
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000364 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
365
366 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Paul Chang0d2aad72020-02-13 20:04:03 +0800367 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000368
369 // Other options retain default values
370 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800371 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000372 EXPECT_FALSE(options_.show_header_only);
373 EXPECT_FALSE(options_.do_progress_updates);
374 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800375 EXPECT_FALSE(options_.stream_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000376 EXPECT_FALSE(options_.wifi_only);
mhasankd451a472020-05-26 18:02:39 -0700377 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100378}
379
380TEST_F(DumpOptionsTest, InitializePartial1) {
381 // clang-format off
382 char* argv[] = {
383 const_cast<char*>("dumpstate"),
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100384 const_cast<char*>("-s"),
385 const_cast<char*>("-S"),
386
387 };
388 // clang-format on
389
390 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
391
392 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100393 // TODO: Maybe we should trim the filename
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800394 EXPECT_TRUE(options_.stream_to_socket);
395 EXPECT_TRUE(options_.progress_updates_to_socket);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100396
397 // Other options retain default values
398 EXPECT_FALSE(options_.show_header_only);
399 EXPECT_TRUE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800400 EXPECT_FALSE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100401 EXPECT_FALSE(options_.do_progress_updates);
402 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700403 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100404}
405
406TEST_F(DumpOptionsTest, InitializePartial2) {
407 // clang-format off
408 char* argv[] = {
409 const_cast<char*>("dumpstate"),
410 const_cast<char*>("-v"),
411 const_cast<char*>("-q"),
412 const_cast<char*>("-p"),
413 const_cast<char*>("-P"),
414 const_cast<char*>("-R"),
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100415 };
416 // clang-format on
417
418 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
419
420 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
421 EXPECT_TRUE(options_.show_header_only);
422 EXPECT_FALSE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800423 EXPECT_TRUE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100424 EXPECT_TRUE(options_.do_progress_updates);
425 EXPECT_TRUE(options_.is_remote_mode);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100426
427 // Other options retain default values
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800428 EXPECT_FALSE(options_.stream_to_socket);
429 EXPECT_FALSE(options_.progress_updates_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700430 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100431}
432
433TEST_F(DumpOptionsTest, InitializeHelp) {
434 // clang-format off
435 char* argv[] = {
436 const_cast<char*>("dumpstate"),
437 const_cast<char*>("-h")
438 };
439 // clang-format on
440
441 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
442
443 // -h is for help.
444 EXPECT_EQ(status, Dumpstate::RunStatus::HELP);
445}
446
447TEST_F(DumpOptionsTest, InitializeUnknown) {
448 // clang-format off
449 char* argv[] = {
450 const_cast<char*>("dumpstate"),
451 const_cast<char*>("-u") // unknown flag
452 };
453 // clang-format on
454
455 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
456
457 // -u is unknown.
458 EXPECT_EQ(status, Dumpstate::RunStatus::INVALID_INPUT);
459}
460
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800461TEST_F(DumpOptionsTest, ValidateOptionsSocketUsage1) {
462 options_.progress_updates_to_socket = true;
463 options_.stream_to_socket = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100464 EXPECT_FALSE(options_.ValidateOptions());
Nandana Dutt9a76d202019-01-21 15:56:48 +0000465
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800466 options_.stream_to_socket = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100467 EXPECT_TRUE(options_.ValidateOptions());
468}
469
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800470TEST_F(DumpOptionsTest, ValidateOptionsSocketUsage2) {
Abhijeet Kaure370d682019-10-01 16:49:30 +0100471 options_.do_progress_updates = true;
Nandana Dutt9a76d202019-01-21 15:56:48 +0000472 // Writing to socket = !writing to file.
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800473 options_.stream_to_socket = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100474 EXPECT_FALSE(options_.ValidateOptions());
Nandana Dutt9a76d202019-01-21 15:56:48 +0000475
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800476 options_.stream_to_socket = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100477 EXPECT_TRUE(options_.ValidateOptions());
478}
479
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100480TEST_F(DumpOptionsTest, ValidateOptionsRemoteMode) {
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800481 options_.do_progress_updates = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100482 options_.is_remote_mode = true;
483 EXPECT_FALSE(options_.ValidateOptions());
484
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800485 options_.do_progress_updates = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100486 EXPECT_TRUE(options_.ValidateOptions());
487}
488
Gavin Corkerya44686c2022-11-23 18:16:51 +0000489TEST_F(DumpOptionsTest, InitializeBugreportFlags) {
490 int flags = Dumpstate::BugreportFlag::BUGREPORT_USE_PREDUMPED_UI_DATA |
491 Dumpstate::BugreportFlag::BUGREPORT_FLAG_DEFER_CONSENT;
492 options_.Initialize(
493 Dumpstate::BugreportMode::BUGREPORT_FULL, flags, fd, fd, true);
494 EXPECT_TRUE(options_.is_consent_deferred);
495 EXPECT_TRUE(options_.use_predumped_ui_data);
496
497 options_.Initialize(
498 Dumpstate::BugreportMode::BUGREPORT_FULL, 0, fd, fd, true);
499 EXPECT_FALSE(options_.is_consent_deferred);
500 EXPECT_FALSE(options_.use_predumped_ui_data);
501}
502
Felipe Leme7447d7c2016-11-03 18:12:22 -0700503class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700504 public:
505 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800506 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700507 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700508 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700509 ds.progress_.reset(new Progress());
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100510 ds.options_.reset(new Dumpstate::DumpOptions());
Felipe Leme4c2d6632016-09-28 14:32:00 -0700511 }
512
Rhed Jao1c855122020-07-16 17:37:39 +0800513 void TearDown() {
514 ds.ShutdownDumpPool();
515 }
516
Felipe Leme4c2d6632016-09-28 14:32:00 -0700517 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700518 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700519 const CommandOptions& options = CommandOptions::DEFAULT) {
520 CaptureStdout();
521 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700522 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700523 out = GetCapturedStdout();
524 err = GetCapturedStderr();
525 return status;
526 }
527
Felipe Lemecef02982016-10-03 17:22:22 -0700528 // Dumps a file and capture `stdout` and `stderr`.
529 int DumpFile(const std::string& title, const std::string& path) {
530 CaptureStdout();
531 CaptureStderr();
532 int status = ds.DumpFile(title, path);
533 out = GetCapturedStdout();
534 err = GetCapturedStderr();
535 return status;
536 }
537
Nandana Dutt402a8392019-06-14 14:25:13 +0100538 void SetProgress(long progress, long initial_max) {
539 ds.last_reported_percent_progress_ = 0;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100540 ds.options_->do_progress_updates = true;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700541 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
542 }
543
Rhed Jao1c855122020-07-16 17:37:39 +0800544 void EnableParallelRunIfNeeded() {
545 ds.EnableParallelRunIfNeeded();
546 }
547
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100548 std::string GetProgressMessage(int progress, int max,
549 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700550 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
551 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700552
Felipe Leme7447d7c2016-11-03 18:12:22 -0700553 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700554
Felipe Leme009ecbb2016-11-07 10:18:44 -0800555 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700556 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800557 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700558 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700559 }
560
Felipe Leme009ecbb2016-11-07 10:18:44 -0800561 if (update_progress) {
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100562 message += android::base::StringPrintf("Setting progress: %d/%d (%d%%)\n",
563 progress, max, (100 * progress / max));
Felipe Leme009ecbb2016-11-07 10:18:44 -0800564 }
565
566 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700567 }
568
Felipe Leme4c2d6632016-09-28 14:32:00 -0700569 // `stdout` and `stderr` from the last command ran.
570 std::string out, err;
571
Felipe Lemefd8affa2016-09-30 17:38:57 -0700572 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700573};
574
575TEST_F(DumpstateTest, RunCommandNoArgs) {
576 EXPECT_EQ(-1, RunCommand("", {}));
577}
578
579TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700580 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700581 EXPECT_THAT(out, StrEq("stdout\n"));
582 EXPECT_THAT(err, StrEq("stderr\n"));
583}
584
585TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700586 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700587 EXPECT_THAT(err, StrEq("stderr\n"));
Greg Kaiser3a811c12019-05-21 12:48:59 -0700588 // The duration may not get output, depending on how long it takes,
589 // so we just check the prefix.
Felipe Lemefd8affa2016-09-30 17:38:57 -0700590 EXPECT_THAT(out,
Nandana Dutt47527b52019-03-29 15:34:36 +0000591 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700592}
593
Felipe Lemefd8affa2016-09-30 17:38:57 -0700594TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700595 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700596 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700597 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
598 EXPECT_THAT(out, StrEq("stdout\n"));
599 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
600}
601
602TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700603 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700604 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700605 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700606 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700607}
608
609TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700610 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700611 EXPECT_THAT(err, IsEmpty());
612 EXPECT_THAT(out, StrEq("one\n"));
613}
614
Felipe Lemefd8affa2016-09-30 17:38:57 -0700615TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700616 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700617 EXPECT_THAT(err, IsEmpty());
618 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
619}
620
621TEST_F(DumpstateTest, RunCommandDryRun) {
622 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700623 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Greg Kaiser3a811c12019-05-21 12:48:59 -0700624 // The duration may not get output, depending on how long it takes,
625 // so we just check the prefix.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700626 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Nandana Dutt47527b52019-03-29 15:34:36 +0000627 ") ------\n\t(skipped on dry run)\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700628 EXPECT_THAT(err, IsEmpty());
629}
630
631TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
632 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700633 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700634 EXPECT_THAT(out, IsEmpty());
635 EXPECT_THAT(err, IsEmpty());
636}
637
638TEST_F(DumpstateTest, RunCommandDryRunAlways) {
639 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700640 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700641 EXPECT_THAT(out, StrEq("stdout\n"));
642 EXPECT_THAT(err, StrEq("stderr\n"));
643}
644
Felipe Lemefd8affa2016-09-30 17:38:57 -0700645TEST_F(DumpstateTest, RunCommandNotFound) {
646 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
647 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
648 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
649}
650
651TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700652 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
653 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700654 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700655 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700656 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700657}
658
659TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700660 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700661 // We don't know the exit code, so check just the prefix.
662 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700663 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700664 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700665 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700666}
667
668TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700669 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700670 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700671 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700672 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700673 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700674 " --sleep 2' timed out after 1"));
675}
676
677TEST_F(DumpstateTest, RunCommandIsKilled) {
678 CaptureStdout();
679 CaptureStderr();
680
681 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700682 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700683 CommandOptions::WithTimeout(100).Always().Build()));
684 });
685
686 // Capture pid and pre-sleep output.
687 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
688 std::string err = GetCapturedStderr();
689 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
690
691 std::string out = GetCapturedStdout();
692 std::vector<std::string> lines = android::base::Split(out, "\n");
693 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
694
695 int pid = atoi(lines[0].c_str());
696 EXPECT_THAT(lines[1], StrEq("stdout line1"));
697 EXPECT_THAT(lines[2], IsEmpty()); // \n
698
699 // Then kill the process.
700 CaptureStdout();
701 CaptureStderr();
702 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
703 t.join();
704
705 // Finally, check output after murder.
706 out = GetCapturedStdout();
707 err = GetCapturedStderr();
708
Felipe Leme7447d7c2016-11-03 18:12:22 -0700709 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700710 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700711 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700712 " --pid --sleep 20' failed: killed by signal 15\n"));
713}
714
Felipe Leme75876a22016-10-27 16:31:27 -0700715TEST_F(DumpstateTest, RunCommandProgress) {
716 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
717 ds.listener_ = listener;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700718 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700719
Nandana Duttbabf6c72019-01-15 14:11:12 +0000720 EXPECT_CALL(*listener, onProgress(66)); // 20/30 %
Felipe Leme7447d7c2016-11-03 18:12:22 -0700721 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100722 std::string progress_message = GetProgressMessage(20, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700723 EXPECT_THAT(out, StrEq("stdout\n"));
724 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
725
Nandana Dutt402a8392019-06-14 14:25:13 +0100726 EXPECT_CALL(*listener, onProgress(80)); // 24/30 %
727 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100728 progress_message = GetProgressMessage(24, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700729 EXPECT_THAT(out, StrEq("stdout\n"));
730 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
731
732 // Make sure command ran while in dry_run is counted.
733 SetDryRun(true);
Nandana Dutt402a8392019-06-14 14:25:13 +0100734 EXPECT_CALL(*listener, onProgress(90)); // 27/30 %
735 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100736 progress_message = GetProgressMessage(27, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700737 EXPECT_THAT(out, IsEmpty());
738 EXPECT_THAT(err, StrEq(progress_message));
739
Nandana Dutt402a8392019-06-14 14:25:13 +0100740 SetDryRun(false);
741 EXPECT_CALL(*listener, onProgress(96)); // 29/30 %
742 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(2).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100743 progress_message = GetProgressMessage(29, 30);
Felipe Leme009ecbb2016-11-07 10:18:44 -0800744 EXPECT_THAT(out, StrEq("stdout\n"));
745 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
746
Nandana Dutt402a8392019-06-14 14:25:13 +0100747 EXPECT_CALL(*listener, onProgress(100)); // 30/30 %
Felipe Leme009ecbb2016-11-07 10:18:44 -0800748 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100749 progress_message = GetProgressMessage(30, 30);
Felipe Leme009ecbb2016-11-07 10:18:44 -0800750 EXPECT_THAT(out, StrEq("stdout\n"));
751 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
752
753 ds.listener_.clear();
754}
755
Felipe Lemed80e6b62016-10-03 13:08:14 -0700756TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800757 if (!IsStandalone()) {
758 // TODO: temporarily disabled because it might cause other tests to fail after dropping
759 // to Shell - need to refactor tests to avoid this problem)
760 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
761 return;
762 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700763 // First check root case - only available when running with 'adb root'.
764 uid_t uid = getuid();
765 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700766 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700767 EXPECT_THAT(out, StrEq("0\nstdout\n"));
768 EXPECT_THAT(err, StrEq("stderr\n"));
769 return;
770 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700771 // Then run dropping root.
772 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700773 CommandOptions::WithTimeout(1).DropRoot().Build()));
774 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700775 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700776}
777
778TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800779 if (!IsStandalone()) {
780 // TODO: temporarily disabled because it might cause other tests to fail after dropping
781 // to Shell - need to refactor tests to avoid this problem)
782 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
783 return;
784 }
Felipe Lemef0292972016-11-22 13:57:05 -0800785 if (!PropertiesHelper::IsUserBuild()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700786 // Emulates user build if necessarily.
787 SetBuildType("user");
788 }
789
790 DropRoot();
791
Felipe Leme7447d7c2016-11-03 18:12:22 -0700792 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700793
794 // We don't know the exact path of su, so we just check for the 'root ...' commands
795 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700796 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700797 EXPECT_THAT(err, IsEmpty());
798}
799
Felipe Leme46b85da2016-11-21 17:40:45 -0800800TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
801 if (!IsStandalone()) {
802 // TODO: temporarily disabled because it might cause other tests to fail after dropping
803 // to Shell - need to refactor tests to avoid this problem)
804 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
805 return;
806 }
Felipe Lemef0292972016-11-22 13:57:05 -0800807 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800808 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
809 return;
810 }
811
812 DropRoot();
813
814 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
815 CommandOptions::WithTimeout(1).AsRoot().Build()));
816
817 EXPECT_THAT(out, StrEq("0\nstdout\n"));
818 EXPECT_THAT(err, StrEq("stderr\n"));
819}
820
Nandana Dutt4b392be2018-11-02 16:17:05 +0000821TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild_withUnroot) {
822 if (!IsStandalone()) {
823 // TODO: temporarily disabled because it might cause other tests to fail after dropping
824 // to Shell - need to refactor tests to avoid this problem)
825 MYLOGE(
826 "Skipping DumpstateTest.RunCommandAsRootNonUserBuild_withUnroot() "
827 "on test suite\n")
828 return;
829 }
830 if (PropertiesHelper::IsUserBuild()) {
831 ALOGI("Skipping RunCommandAsRootNonUserBuild_withUnroot on user builds\n");
832 return;
833 }
834
835 // Same test as above, but with unroot property set, which will override su availability.
836 SetUnroot(true);
837 DropRoot();
838
839 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
840 CommandOptions::WithTimeout(1).AsRoot().Build()));
841
842 // AsRoot is ineffective.
843 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
844 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
845}
846
Yifan Hong48e83a12017-10-03 14:10:07 -0700847TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnUserBuild) {
848 if (!IsStandalone()) {
849 // TODO: temporarily disabled because it might cause other tests to fail after dropping
850 // to Shell - need to refactor tests to avoid this problem)
851 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
852 return;
853 }
854 if (!PropertiesHelper::IsUserBuild()) {
855 // Emulates user build if necessarily.
856 SetBuildType("user");
857 }
858
859 DropRoot();
860
861 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
862 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
863
864 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
865 EXPECT_THAT(err, StrEq("stderr\n"));
866}
867
868TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild) {
869 if (!IsStandalone()) {
870 // TODO: temporarily disabled because it might cause other tests to fail after dropping
871 // to Shell - need to refactor tests to avoid this problem)
872 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
873 return;
874 }
875 if (PropertiesHelper::IsUserBuild()) {
876 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
877 return;
878 }
879
880 DropRoot();
881
882 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
883 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
884
885 EXPECT_THAT(out, StrEq("0\nstdout\n"));
886 EXPECT_THAT(err, StrEq("stderr\n"));
887}
888
Nandana Dutt4b392be2018-11-02 16:17:05 +0000889TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild_withUnroot) {
890 if (!IsStandalone()) {
891 // TODO: temporarily disabled because it might cause other tests to fail after dropping
892 // to Shell - need to refactor tests to avoid this problem)
893 MYLOGE(
894 "Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild_withUnroot() "
895 "on test suite\n")
896 return;
897 }
898 if (PropertiesHelper::IsUserBuild()) {
899 ALOGI("Skipping RunCommandAsRootIfAvailableOnDebugBuild_withUnroot on user builds\n");
900 return;
901 }
902 // Same test as above, but with unroot property set, which will override su availability.
903 SetUnroot(true);
904
905 DropRoot();
906
907 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
908 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
909
910 // It's a userdebug build, so "su root" should be available, but unroot=true overrides it.
911 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
912 EXPECT_THAT(err, StrEq("stderr\n"));
913}
914
Felipe Lemecef02982016-10-03 17:22:22 -0700915TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
916 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
917 EXPECT_THAT(out,
918 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
919 EXPECT_THAT(err, IsEmpty());
920}
921
922TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
923 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
924 EXPECT_THAT(err, IsEmpty());
Greg Kaiser3a811c12019-05-21 12:48:59 -0700925 // The duration may not get output, depending on how long it takes,
926 // so we just check the prefix.
Felipe Lemecef02982016-10-03 17:22:22 -0700927 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
928 "such file or directory\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700929}
930
931TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700932 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700933 EXPECT_THAT(err, IsEmpty());
934 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
935}
936
937TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700938 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700939 EXPECT_THAT(err, IsEmpty());
940 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
941}
942
943TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700944 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700945 EXPECT_THAT(err, IsEmpty());
946 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
947}
948
949TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700950 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700951 EXPECT_THAT(err, IsEmpty());
952 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
953}
954
955TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
956 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700957 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700958 EXPECT_THAT(err, IsEmpty());
959 EXPECT_THAT(out, IsEmpty());
960}
961
962TEST_F(DumpstateTest, DumpFileOnDryRun) {
963 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700964 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700965 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -0800966 EXPECT_THAT(
967 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
Nandana Dutt47527b52019-03-29 15:34:36 +0000968 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700969}
970
Felipe Leme75876a22016-10-27 16:31:27 -0700971TEST_F(DumpstateTest, DumpFileUpdateProgress) {
972 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
973 ds.listener_ = listener;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700974 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700975
Nandana Duttbabf6c72019-01-15 14:11:12 +0000976 EXPECT_CALL(*listener, onProgress(16)); // 5/30 %
Felipe Leme7447d7c2016-11-03 18:12:22 -0700977 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -0700978
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100979 std::string progress_message = GetProgressMessage(5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
Felipe Leme75876a22016-10-27 16:31:27 -0700980 EXPECT_THAT(err, StrEq(progress_message));
981 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
982
983 ds.listener_.clear();
984}
985
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800986TEST_F(DumpstateTest, DumpPool_withParallelRunEnabled_notNull) {
Rhed Jao1c855122020-07-16 17:37:39 +0800987 SetParallelRun(true);
988 EnableParallelRunIfNeeded();
Rhed Jao4875aa62020-07-20 17:46:29 +0800989 EXPECT_TRUE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +0800990 EXPECT_TRUE(ds.dump_pool_);
991}
992
Rhed Jao1c855122020-07-16 17:37:39 +0800993TEST_F(DumpstateTest, DumpPool_withParallelRunDisabled_isNull) {
994 SetParallelRun(false);
995 EnableParallelRunIfNeeded();
Rhed Jao4875aa62020-07-20 17:46:29 +0800996 EXPECT_FALSE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +0800997 EXPECT_FALSE(ds.dump_pool_);
998}
999
Kean Mariotti306633e2022-09-05 16:30:47 +00001000TEST_F(DumpstateBaseTest, PreDumpUiData) {
1001 // SurfaceFlinger's transactions trace is always enabled, i.e. it is always pre-dumped
1002 static const auto kTransactionsTrace =
1003 std::filesystem::path {"/data/misc/wmtrace/transactions_trace.winscope"};
1004
1005 std::system(("rm " + kTransactionsTrace.string()).c_str());
1006 EXPECT_FALSE(std::filesystem::exists(kTransactionsTrace));
1007
1008 Dumpstate& ds_ = Dumpstate::GetInstance();
1009 ds_.PreDumpUiData();
1010 EXPECT_TRUE(std::filesystem::exists(kTransactionsTrace));
1011}
1012
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001013class ZippedBugReportStreamTest : public DumpstateBaseTest {
1014 public:
1015 void SetUp() {
1016 DumpstateBaseTest::SetUp();
1017 ds_.options_.reset(new Dumpstate::DumpOptions());
1018 }
1019 void TearDown() {
1020 CloseArchive(handle_);
1021 }
1022
1023 // Set bugreport mode and options before here.
1024 void GenerateBugreport() {
1025 ds_.Initialize();
1026 EXPECT_EQ(Dumpstate::RunStatus::OK, ds_.Run(/*calling_uid=*/-1, /*calling_package=*/""));
1027 }
1028
1029 // Most bugreports droproot, ensure the file can be opened by shell to verify file content.
1030 void CreateFd(const std::string& path, android::base::unique_fd* out_fd) {
1031 out_fd->reset(TEMP_FAILURE_RETRY(open(path.c_str(),
1032 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1033 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1034 ASSERT_GE(out_fd->get(), 0) << "could not create FD for path " << path;
1035 }
1036
1037 void VerifyEntry(const ZipArchiveHandle archive, const std::string_view entry_name,
1038 ZipEntry* data) {
1039 int32_t e = FindEntry(archive, entry_name, data);
1040 EXPECT_EQ(0, e) << ErrorCodeString(e) << " entry name: " << entry_name;
1041 }
1042
1043 // While testing dumpstate in process, using STDOUT may get confused about
1044 // the internal fd redirection. Redirect to a dedicate fd to save content.
1045 void RedirectOutputToFd(android::base::unique_fd& ufd) {
1046 ds_.open_socket_fn_ = [&](const char*) -> int { return ufd.release(); };
1047 };
1048
1049 Dumpstate& ds_ = Dumpstate::GetInstance();
1050 ZipArchiveHandle handle_;
1051};
1052
Rhed Jaob8b56172021-04-08 20:14:27 +08001053// Generate a quick LimitedOnly report redirected to a file, open it and verify entry exist.
Jeff Sharkey9df29d52023-02-06 14:26:30 -07001054// TODO: broken test tracked in b/249983726
1055TEST_F(ZippedBugReportStreamTest, DISABLED_StreamLimitedOnlyReport) {
Rhed Jaob8b56172021-04-08 20:14:27 +08001056 std::string out_path = kTestDataPath + "StreamLimitedOnlyReportOut.zip";
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001057 android::base::unique_fd out_fd;
1058 CreateFd(out_path, &out_fd);
Rhed Jaob8b56172021-04-08 20:14:27 +08001059 ds_.options_->limited_only = true;
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001060 ds_.options_->stream_to_socket = true;
1061 RedirectOutputToFd(out_fd);
1062
1063 GenerateBugreport();
1064 OpenArchive(out_path.c_str(), &handle_);
1065
1066 ZipEntry entry;
1067 VerifyEntry(handle_, "main_entry.txt", &entry);
1068 std::string bugreport_txt_name;
1069 bugreport_txt_name.resize(entry.uncompressed_length);
1070 ExtractToMemory(handle_, &entry, reinterpret_cast<uint8_t*>(bugreport_txt_name.data()),
1071 entry.uncompressed_length);
1072 EXPECT_THAT(bugreport_txt_name,
Rhed Jaob8b56172021-04-08 20:14:27 +08001073 testing::ContainsRegex("(bugreport-.+(-[[:digit:]]+){6}\\.txt)"));
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001074 VerifyEntry(handle_, bugreport_txt_name, &entry);
1075}
1076
Felipe Leme7447d7c2016-11-03 18:12:22 -07001077class ProgressTest : public DumpstateBaseTest {
1078 public:
1079 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
1080 return Progress(max, growth_factor, path);
1081 }
1082
1083 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
1084 std::string expected_content =
1085 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
1086 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -08001087 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001088 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
1089 }
1090};
1091
1092TEST_F(ProgressTest, SimpleTest) {
1093 Progress progress;
1094 EXPECT_EQ(0, progress.Get());
1095 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1096 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1097
1098 bool max_increased = progress.Inc(1);
1099 EXPECT_EQ(1, progress.Get());
1100 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1101 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1102 EXPECT_FALSE(max_increased);
1103
1104 // Ignore negative increase.
1105 max_increased = progress.Inc(-1);
1106 EXPECT_EQ(1, progress.Get());
1107 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1108 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1109 EXPECT_FALSE(max_increased);
1110}
1111
1112TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
1113 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1114 EXPECT_EQ(0, progress.Get());
1115 EXPECT_EQ(10, progress.GetInitialMax());
1116 EXPECT_EQ(10, progress.GetMax());
1117
1118 // No increase
1119 bool max_increased = progress.Inc(10);
1120 EXPECT_EQ(10, progress.Get());
1121 EXPECT_EQ(10, progress.GetMax());
1122 EXPECT_FALSE(max_increased);
1123
1124 // Increase, with new value < max*20%
1125 max_increased = progress.Inc(1);
1126 EXPECT_EQ(11, progress.Get());
1127 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
1128 EXPECT_TRUE(max_increased);
1129}
1130
1131TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
1132 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1133 EXPECT_EQ(0, progress.Get());
1134 EXPECT_EQ(10, progress.GetInitialMax());
1135 EXPECT_EQ(10, progress.GetMax());
1136
1137 // No increase
1138 bool max_increased = progress.Inc(10);
1139 EXPECT_EQ(10, progress.Get());
1140 EXPECT_EQ(10, progress.GetMax());
1141 EXPECT_FALSE(max_increased);
1142
1143 // Increase, with new value > max*20%
1144 max_increased = progress.Inc(5);
1145 EXPECT_EQ(15, progress.Get());
1146 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
1147 EXPECT_TRUE(max_increased);
1148}
1149
1150TEST_F(ProgressTest, InvalidPath) {
1151 Progress progress("/devil/null");
1152 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1153}
1154
1155TEST_F(ProgressTest, EmptyFile) {
1156 Progress progress(CopyTextFileFixture("empty-file.txt"));
1157 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1158}
1159
1160TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
1161 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
1162 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1163}
1164
1165TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
1166 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
1167 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1168}
1169
1170TEST_F(ProgressTest, InvalidLineBothNAN) {
1171 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
1172 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1173}
1174
1175TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
1176 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
1177 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1178}
1179
1180TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
1181 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
1182 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1183}
1184
1185TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
1186 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
1187 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1188}
1189
1190TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
1191 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
1192 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1193}
1194
1195// Tests stats are properly saved when the file does not exists.
1196TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001197 if (!IsStandalone()) {
1198 // TODO: temporarily disabled because it's failing when running as suite
1199 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
1200 return;
1201 }
1202
Felipe Leme7447d7c2016-11-03 18:12:22 -07001203 std::string path = kTestDataPath + "FirstTime.txt";
1204 android::base::RemoveFileIfExists(path);
1205
1206 Progress run1(path);
1207 EXPECT_EQ(0, run1.Get());
1208 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
1209 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1210
1211 bool max_increased = run1.Inc(20);
1212 EXPECT_EQ(20, run1.Get());
1213 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1214 EXPECT_FALSE(max_increased);
1215
1216 run1.Save();
1217 AssertStats(path, 1, 20);
1218}
1219
1220// Tests what happens when the persistent settings contains the average duration of 1 run.
1221// Data on file is 1 run and 109 average.
1222TEST_F(ProgressTest, SecondTime) {
1223 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
1224
1225 Progress run1 = GetInstance(-42, 1.2, path);
1226 EXPECT_EQ(0, run1.Get());
1227 EXPECT_EQ(10, run1.GetInitialMax());
1228 EXPECT_EQ(10, run1.GetMax());
1229
1230 bool max_increased = run1.Inc(20);
1231 EXPECT_EQ(20, run1.Get());
1232 EXPECT_EQ(24, run1.GetMax());
1233 EXPECT_TRUE(max_increased);
1234
1235 // Average now is 2 runs and (10 + 20)/ 2 = 15
1236 run1.Save();
1237 AssertStats(path, 2, 15);
1238
1239 Progress run2 = GetInstance(-42, 1.2, path);
1240 EXPECT_EQ(0, run2.Get());
1241 EXPECT_EQ(15, run2.GetInitialMax());
1242 EXPECT_EQ(15, run2.GetMax());
1243
1244 max_increased = run2.Inc(25);
1245 EXPECT_EQ(25, run2.Get());
1246 EXPECT_EQ(30, run2.GetMax());
1247 EXPECT_TRUE(max_increased);
1248
1249 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
1250 run2.Save();
1251 AssertStats(path, 3, 18);
1252
1253 Progress run3 = GetInstance(-42, 1.2, path);
1254 EXPECT_EQ(0, run3.Get());
1255 EXPECT_EQ(18, run3.GetInitialMax());
1256 EXPECT_EQ(18, run3.GetMax());
1257
1258 // Make sure average decreases as well
1259 max_increased = run3.Inc(5);
1260 EXPECT_EQ(5, run3.Get());
1261 EXPECT_EQ(18, run3.GetMax());
1262 EXPECT_FALSE(max_increased);
1263
1264 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
1265 run3.Save();
1266 AssertStats(path, 4, 14);
1267}
1268
1269// Tests what happens when the persistent settings contains the average duration of 2 runs.
1270// Data on file is 2 runs and 15 average.
1271TEST_F(ProgressTest, ThirdTime) {
1272 std::string path = CopyTextFileFixture("stats-two-runs.txt");
1273 AssertStats(path, 2, 15); // Sanity check
1274
1275 Progress run1 = GetInstance(-42, 1.2, path);
1276 EXPECT_EQ(0, run1.Get());
1277 EXPECT_EQ(15, run1.GetInitialMax());
1278 EXPECT_EQ(15, run1.GetMax());
1279
1280 bool max_increased = run1.Inc(20);
1281 EXPECT_EQ(20, run1.Get());
1282 EXPECT_EQ(24, run1.GetMax());
1283 EXPECT_TRUE(max_increased);
1284
1285 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
1286 run1.Save();
1287 AssertStats(path, 3, 16);
1288}
1289
Felipe Leme46b85da2016-11-21 17:40:45 -08001290class DumpstateUtilTest : public DumpstateBaseTest {
1291 public:
1292 void SetUp() {
1293 DumpstateBaseTest::SetUp();
1294 SetDryRun(false);
1295 }
1296
Felipe Leme46b85da2016-11-21 17:40:45 -08001297 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -08001298 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -08001299 }
1300
1301 void CreateFd(const std::string& name) {
1302 path_ = kTestDataPath + name;
1303 MYLOGD("Creating fd for file %s\n", path_.c_str());
1304
1305 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
1306 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1307 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
1308 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
1309 }
1310
1311 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001312 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -08001313 const CommandOptions& options = CommandOptions::DEFAULT) {
1314 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001315 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -08001316 close(fd);
1317
1318 CaptureFdOut();
1319 err = GetCapturedStderr();
1320 return status;
1321 }
1322
1323 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001324 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001325 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001326 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -08001327 close(fd);
1328
1329 CaptureFdOut();
1330 err = GetCapturedStderr();
1331 return status;
1332 }
1333
1334 int fd;
1335
1336 // 'fd` output and `stderr` from the last command ran.
1337 std::string out, err;
1338
1339 private:
1340 std::string path_;
1341};
1342
1343TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -08001344 CreateFd("RunCommandNoArgs.txt");
1345 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001346}
1347
Felipe Lemef0292972016-11-22 13:57:05 -08001348TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001349 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001350 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001351 EXPECT_THAT(out, StrEq("stdout\n"));
1352 EXPECT_THAT(err, StrEq("stderr\n"));
1353}
1354
Felipe Lemef0292972016-11-22 13:57:05 -08001355TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
1356 CreateFd("RunCommandWithNoArgs.txt");
1357 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1358 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
1359 EXPECT_THAT(err, StrEq("stderr\n"));
1360}
1361
Felipe Leme46b85da2016-11-21 17:40:45 -08001362TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
1363 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001364 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001365 EXPECT_THAT(err, IsEmpty());
1366 EXPECT_THAT(out, StrEq("one\n"));
1367}
1368
1369TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
1370 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001371 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001372 EXPECT_THAT(err, IsEmpty());
1373 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
1374}
1375
1376TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
1377 CreateFd("RunCommandWithLoggingMessage.txt");
1378 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -08001379 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -08001380 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
1381 EXPECT_THAT(out, StrEq("stdout\n"));
1382 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
1383}
1384
1385TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
1386 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001387 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
1388 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001389 EXPECT_THAT(out, IsEmpty());
1390 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
1391}
1392
1393TEST_F(DumpstateUtilTest, RunCommandDryRun) {
1394 CreateFd("RunCommandDryRun.txt");
1395 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001396 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1397 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
1398 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
1399 kSimpleCommand.c_str())));
1400 EXPECT_THAT(err, IsEmpty());
1401}
1402
1403TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
1404 CreateFd("RunCommandDryRun.txt");
1405 SetDryRun(true);
1406 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001407 EXPECT_THAT(
1408 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
1409 EXPECT_THAT(err, IsEmpty());
1410}
1411
1412TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
1413 CreateFd("RunCommandDryRunAlways.txt");
1414 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001415 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001416 EXPECT_THAT(out, StrEq("stdout\n"));
1417 EXPECT_THAT(err, StrEq("stderr\n"));
1418}
1419
1420TEST_F(DumpstateUtilTest, RunCommandNotFound) {
1421 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001422 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001423 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
1424 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
1425}
1426
1427TEST_F(DumpstateUtilTest, RunCommandFails) {
1428 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001429 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001430 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
1431 " --exit 42' failed: exit code 42\n"));
1432 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
1433 " --exit 42' failed: exit code 42\n"));
1434}
1435
1436TEST_F(DumpstateUtilTest, RunCommandCrashes) {
1437 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001438 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001439 // We don't know the exit code, so check just the prefix.
1440 EXPECT_THAT(
1441 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1442 EXPECT_THAT(
1443 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1444}
1445
Vishnu Nair6921f802017-11-22 09:17:23 -08001446TEST_F(DumpstateUtilTest, RunCommandTimesoutWithSec) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001447 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001448 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1449 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001450 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1451 " --sleep 2' timed out after 1"));
1452 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1453 " --sleep 2' timed out after 1"));
1454}
1455
Vishnu Nair6921f802017-11-22 09:17:23 -08001456TEST_F(DumpstateUtilTest, RunCommandTimesoutWithMsec) {
1457 CreateFd("RunCommandTimesout.txt");
1458 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1459 CommandOptions::WithTimeoutInMs(1000).Build()));
1460 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1461 " --sleep 2' timed out after 1"));
1462 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1463 " --sleep 2' timed out after 1"));
1464}
1465
1466
Felipe Leme46b85da2016-11-21 17:40:45 -08001467TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
1468 CreateFd("RunCommandIsKilled.txt");
1469 CaptureStderr();
1470
1471 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -08001472 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001473 CommandOptions::WithTimeout(100).Always().Build()));
1474 });
1475
1476 // Capture pid and pre-sleep output.
1477 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
1478 std::string err = GetCapturedStderr();
1479 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
1480
1481 CaptureFdOut();
1482 std::vector<std::string> lines = android::base::Split(out, "\n");
1483 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
1484
1485 int pid = atoi(lines[0].c_str());
1486 EXPECT_THAT(lines[1], StrEq("stdout line1"));
1487 EXPECT_THAT(lines[2], IsEmpty()); // \n
1488
1489 // Then kill the process.
1490 CaptureFdOut();
1491 CaptureStderr();
1492 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1493 t.join();
1494
1495 // Finally, check output after murder.
1496 CaptureFdOut();
1497 err = GetCapturedStderr();
1498
1499 // out starts with the pid, which is an unknown
1500 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1501 " --pid --sleep 20' failed: killed by signal 15\n"));
1502 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1503 " --pid --sleep 20' failed: killed by signal 15\n"));
1504}
1505
1506TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1507 if (!IsStandalone()) {
1508 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1509 // to Shell - need to refactor tests to avoid this problem)
1510 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1511 return;
1512 }
1513 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001514 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001515 // Emulates user build if necessarily.
1516 SetBuildType("user");
1517 }
1518
1519 DropRoot();
1520
Felipe Lemef0292972016-11-22 13:57:05 -08001521 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001522
1523 // We don't know the exact path of su, so we just check for the 'root ...' commands
1524 EXPECT_THAT(out, StartsWith("Skipping"));
1525 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1526 EXPECT_THAT(err, IsEmpty());
1527}
1528
1529TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1530 if (!IsStandalone()) {
1531 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1532 // to Shell - need to refactor tests to avoid this problem)
1533 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1534 return;
1535 }
1536 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001537 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001538 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1539 return;
1540 }
1541
1542 DropRoot();
1543
Felipe Lemef0292972016-11-22 13:57:05 -08001544 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1545 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001546
1547 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1548 EXPECT_THAT(err, StrEq("stderr\n"));
1549}
Felipe Leme46b85da2016-11-21 17:40:45 -08001550
Yifan Hong48e83a12017-10-03 14:10:07 -07001551
1552TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnUserBuild) {
1553 if (!IsStandalone()) {
1554 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1555 // to Shell - need to refactor tests to avoid this problem)
1556 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
1557 return;
1558 }
1559 CreateFd("RunCommandAsRootIfAvailableOnUserBuild.txt");
1560 if (!PropertiesHelper::IsUserBuild()) {
1561 // Emulates user build if necessarily.
1562 SetBuildType("user");
1563 }
1564
1565 DropRoot();
1566
1567 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1568 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1569
1570 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1571 EXPECT_THAT(err, StrEq("stderr\n"));
1572}
1573
1574TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnDebugBuild) {
1575 if (!IsStandalone()) {
1576 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1577 // to Shell - need to refactor tests to avoid this problem)
1578 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
1579 return;
1580 }
1581 CreateFd("RunCommandAsRootIfAvailableOnDebugBuild.txt");
1582 if (PropertiesHelper::IsUserBuild()) {
1583 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1584 return;
1585 }
1586
1587 DropRoot();
1588
1589 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1590 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1591
1592 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1593 EXPECT_THAT(err, StrEq("stderr\n"));
1594}
1595
Felipe Leme46b85da2016-11-21 17:40:45 -08001596TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1597 if (!IsStandalone()) {
1598 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1599 // to Shell - need to refactor tests to avoid this problem)
1600 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1601 return;
1602 }
1603 CreateFd("RunCommandDropRoot.txt");
1604 // First check root case - only available when running with 'adb root'.
1605 uid_t uid = getuid();
1606 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001607 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001608 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1609 EXPECT_THAT(err, StrEq("stderr\n"));
1610 return;
1611 }
1612 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001613 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001614 CommandOptions::WithTimeout(1).DropRoot().Build()));
1615 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1616 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1617}
1618
Felipe Lemef0292972016-11-22 13:57:05 -08001619TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001620 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001621 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001622 EXPECT_THAT(out,
1623 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1624 EXPECT_THAT(err, IsEmpty());
1625}
1626
Felipe Lemef0292972016-11-22 13:57:05 -08001627TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1628 CreateFd("DumpFileNotFound.txt");
1629 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1630 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1631 "file or directory\n"));
1632 EXPECT_THAT(err, IsEmpty());
1633}
1634
Felipe Leme46b85da2016-11-21 17:40:45 -08001635TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1636 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001637 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001638 EXPECT_THAT(err, IsEmpty());
1639 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1640}
1641
1642TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1643 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001644 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001645 EXPECT_THAT(err, IsEmpty());
1646 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1647}
1648
1649TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1650 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001651 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001652 EXPECT_THAT(err, IsEmpty());
1653 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1654}
1655
1656TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1657 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001658 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001659 EXPECT_THAT(err, IsEmpty());
1660 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1661}
1662
Felipe Lemef0292972016-11-22 13:57:05 -08001663TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1664 CreateFd("DumpFileOnDryRun.txt");
1665 SetDryRun(true);
1666 std::string path = kTestDataPath + "single-line.txt";
1667 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1668 EXPECT_THAT(err, IsEmpty());
1669 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1670}
1671
Felipe Leme46b85da2016-11-21 17:40:45 -08001672TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1673 CreateFd("DumpFileOnDryRun.txt");
1674 SetDryRun(true);
1675 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001676 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001677 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001678 EXPECT_THAT(
1679 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1680 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001681}
Ecco Park61ffcf72016-10-27 15:46:26 -07001682
Rhed Jao27077b12020-07-14 18:38:08 +08001683class DumpPoolTest : public DumpstateBaseTest {
1684 public:
1685 void SetUp() {
Rhed Jao1c855122020-07-16 17:37:39 +08001686 dump_pool_ = std::make_unique<DumpPool>(kTestDataPath);
Rhed Jao27077b12020-07-14 18:38:08 +08001687 DumpstateBaseTest::SetUp();
1688 CreateOutputFile();
1689 }
1690
1691 void CreateOutputFile() {
1692 out_path_ = kTestDataPath + "out.txt";
1693 out_fd_.reset(TEMP_FAILURE_RETRY(open(out_path_.c_str(),
1694 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1695 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1696 ASSERT_GE(out_fd_.get(), 0) << "could not create FD for path "
1697 << out_path_;
1698 }
1699
1700 int getTempFileCounts(const std::string& folder) {
1701 int count = 0;
1702 std::unique_ptr<DIR, decltype(&closedir)> dir_ptr(opendir(folder.c_str()),
1703 &closedir);
1704 if (!dir_ptr) {
1705 return -1;
1706 }
1707 int dir_fd = dirfd(dir_ptr.get());
1708 if (dir_fd < 0) {
1709 return -1;
1710 }
1711
1712 struct dirent* de;
1713 while ((de = readdir(dir_ptr.get()))) {
1714 if (de->d_type != DT_REG) {
1715 continue;
1716 }
1717 std::string file_name(de->d_name);
1718 if (file_name.find(DumpPool::PREFIX_TMPFILE_NAME) != 0) {
1719 continue;
1720 }
1721 count++;
1722 }
1723 return count;
1724 }
1725
Rhed Jao1c855122020-07-16 17:37:39 +08001726 void setLogDuration(bool log_duration) {
1727 dump_pool_->setLogDuration(log_duration);
1728 }
1729
1730 std::unique_ptr<DumpPool> dump_pool_;
Rhed Jao27077b12020-07-14 18:38:08 +08001731 android::base::unique_fd out_fd_;
1732 std::string out_path_;
1733};
1734
Rhed Jao1c855122020-07-16 17:37:39 +08001735TEST_F(DumpPoolTest, EnqueueTaskWithFd) {
Rhed Jao27077b12020-07-14 18:38:08 +08001736 auto dump_func_1 = [](int out_fd) {
1737 dprintf(out_fd, "A");
1738 };
1739 auto dump_func_2 = [](int out_fd) {
1740 dprintf(out_fd, "B");
1741 sleep(1);
1742 };
1743 auto dump_func_3 = [](int out_fd) {
1744 dprintf(out_fd, "C");
1745 };
Rhed Jao1c855122020-07-16 17:37:39 +08001746 setLogDuration(/* log_duration = */false);
Chris Morinbc223142022-02-04 14:17:11 -08001747 auto t1 = dump_pool_->enqueueTaskWithFd("", dump_func_1, std::placeholders::_1);
1748 auto t2 = dump_pool_->enqueueTaskWithFd("", dump_func_2, std::placeholders::_1);
1749 auto t3 = dump_pool_->enqueueTaskWithFd("", dump_func_3, std::placeholders::_1);
Rhed Jao27077b12020-07-14 18:38:08 +08001750
Chris Morinbc223142022-02-04 14:17:11 -08001751 WaitForTask(std::move(t1), "", out_fd_.get());
1752 WaitForTask(std::move(t2), "", out_fd_.get());
1753 WaitForTask(std::move(t3), "", out_fd_.get());
Rhed Jao27077b12020-07-14 18:38:08 +08001754
1755 std::string result;
1756 ReadFileToString(out_path_, &result);
1757 EXPECT_THAT(result, StrEq("A\nB\nC\n"));
1758 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao1c855122020-07-16 17:37:39 +08001759}
1760
1761TEST_F(DumpPoolTest, EnqueueTask_withDurationLog) {
1762 bool run_1 = false;
1763 auto dump_func_1 = [&]() {
1764 run_1 = true;
1765 };
1766
Chris Morinbc223142022-02-04 14:17:11 -08001767 auto t1 = dump_pool_->enqueueTask(/* duration_title = */"1", dump_func_1);
1768 WaitForTask(std::move(t1), "", out_fd_.get());
Rhed Jao1c855122020-07-16 17:37:39 +08001769
1770 std::string result;
1771 ReadFileToString(out_path_, &result);
1772 EXPECT_TRUE(run_1);
1773 EXPECT_THAT(result, StrEq("------ 0.000s was the duration of '1' ------\n"));
1774 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao27077b12020-07-14 18:38:08 +08001775}
1776
Rhed Jao4875aa62020-07-20 17:46:29 +08001777class TaskQueueTest : public DumpstateBaseTest {
1778public:
1779 void SetUp() {
1780 DumpstateBaseTest::SetUp();
1781 }
1782
1783 TaskQueue task_queue_;
1784};
1785
1786TEST_F(TaskQueueTest, runTask) {
1787 bool is_task1_run = false;
1788 bool is_task2_run = false;
1789 auto task_1 = [&](bool task_cancelled) {
1790 if (task_cancelled) {
1791 return;
1792 }
1793 is_task1_run = true;
1794 };
1795 auto task_2 = [&](bool task_cancelled) {
1796 if (task_cancelled) {
1797 return;
1798 }
1799 is_task2_run = true;
1800 };
1801 task_queue_.add(task_1, std::placeholders::_1);
1802 task_queue_.add(task_2, std::placeholders::_1);
1803
1804 task_queue_.run(/* do_cancel = */false);
1805
1806 EXPECT_TRUE(is_task1_run);
1807 EXPECT_TRUE(is_task2_run);
1808}
1809
1810TEST_F(TaskQueueTest, runTask_withCancelled) {
1811 bool is_task1_cancelled = false;
1812 bool is_task2_cancelled = false;
1813 auto task_1 = [&](bool task_cancelled) {
1814 is_task1_cancelled = task_cancelled;
1815 };
1816 auto task_2 = [&](bool task_cancelled) {
1817 is_task2_cancelled = task_cancelled;
1818 };
1819 task_queue_.add(task_1, std::placeholders::_1);
1820 task_queue_.add(task_2, std::placeholders::_1);
1821
1822 task_queue_.run(/* do_cancel = */true);
1823
1824 EXPECT_TRUE(is_task1_cancelled);
1825 EXPECT_TRUE(is_task2_cancelled);
1826}
1827
Rhed Jao27077b12020-07-14 18:38:08 +08001828
Felipe Leme47e9be22016-12-21 15:37:07 -08001829} // namespace dumpstate
1830} // namespace os
1831} // namespace android