blob: 65d6b9bc726d60e8c05655a0d66ad0822631286b [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
Felipe Leme75876a22016-10-27 16:31:27 -070017#define LOG_TAG "dumpstate"
18#include <cutils/log.h>
19
Felipe Lemef0292972016-11-22 13:57:05 -080020#include "DumpstateInternal.h"
Felipe Leme75876a22016-10-27 16:31:27 -070021#include "DumpstateService.h"
22#include "android/os/BnDumpstate.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070023#include "dumpstate.h"
Rhed Jao27077b12020-07-14 18:38:08 +080024#include "DumpPool.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070025
26#include <gmock/gmock.h>
27#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>
Felipe Lemefd8affa2016-09-30 17:38:57 -070034#include <thread>
Felipe Leme4c2d6632016-09-28 14:32:00 -070035
36#include <android-base/file.h>
Felipe Lemed80e6b62016-10-03 13:08:14 -070037#include <android-base/properties.h>
38#include <android-base/stringprintf.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070039#include <android-base/strings.h>
Abhijeet Kaure370d682019-10-01 16:49:30 +010040#include <android-base/unique_fd.h>
Hunter Knepshield8540faf2020-02-04 19:47:20 -080041#include <android/hardware/dumpstate/1.1/types.h>
42#include <cutils/properties.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070043
Felipe Leme47e9be22016-12-21 15:37:07 -080044namespace android {
45namespace os {
46namespace dumpstate {
Felipe Lemed80e6b62016-10-03 13:08:14 -070047
Hunter Knepshield8540faf2020-02-04 19:47:20 -080048using ::android::hardware::dumpstate::V1_1::DumpstateMode;
Felipe Leme4c2d6632016-09-28 14:32:00 -070049using ::testing::EndsWith;
Rhed Jao27077b12020-07-14 18:38:08 +080050using ::testing::Eq;
Felipe Leme46b85da2016-11-21 17:40:45 -080051using ::testing::HasSubstr;
Felipe Leme4c2d6632016-09-28 14:32:00 -070052using ::testing::IsEmpty;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080053using ::testing::IsNull;
Felipe Leme009ecbb2016-11-07 10:18:44 -080054using ::testing::NotNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070055using ::testing::StartsWith;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080056using ::testing::StrEq;
Felipe Leme4c2d6632016-09-28 14:32:00 -070057using ::testing::Test;
58using ::testing::internal::CaptureStderr;
59using ::testing::internal::CaptureStdout;
60using ::testing::internal::GetCapturedStderr;
61using ::testing::internal::GetCapturedStdout;
62
Nandana Dutt3f8c7172018-09-25 12:01:54 +010063#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
Felipe Leme75876a22016-10-27 16:31:27 -070065class DumpstateListenerMock : public IDumpstateListener {
66 public:
Nandana Dutta6a28bd2019-01-14 16:54:38 +000067 MOCK_METHOD1(onProgress, binder::Status(int32_t progress));
68 MOCK_METHOD1(onError, binder::Status(int32_t error_code));
Nandana Duttcc4ead82019-01-23 08:29:23 +000069 MOCK_METHOD0(onFinished, binder::Status());
Paul Chang0d2aad72020-02-13 20:04:03 +080070 MOCK_METHOD1(onScreenshotTaken, binder::Status(bool success));
Paul Changc490e662020-04-11 18:14:09 +080071 MOCK_METHOD1(onUiIntensiveBugreportDumpsFinished,
72 binder::Status(const android::String16& callingpackage));
Felipe Leme75876a22016-10-27 16:31:27 -070073
74 protected:
75 MOCK_METHOD0(onAsBinder, IBinder*());
76};
77
Felipe Leme46b85da2016-11-21 17:40:45 -080078static int calls_;
79
Felipe Leme7447d7c2016-11-03 18:12:22 -070080// Base class for all tests in this file
81class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080082 public:
83 virtual void SetUp() override {
84 calls_++;
Felipe Lemef0292972016-11-22 13:57:05 -080085 SetDryRun(false);
Felipe Leme46b85da2016-11-21 17:40:45 -080086 }
87
Felipe Lemef0292972016-11-22 13:57:05 -080088 void SetDryRun(bool dry_run) const {
89 PropertiesHelper::dry_run_ = dry_run;
90 }
91
92 void SetBuildType(const std::string& build_type) const {
93 PropertiesHelper::build_type_ = build_type;
94 }
95
Nandana Dutt4b392be2018-11-02 16:17:05 +000096 void SetUnroot(bool unroot) const {
97 PropertiesHelper::unroot_ = unroot;
98 }
99
Rhed Jao1c855122020-07-16 17:37:39 +0800100 void SetParallelRun(bool parallel_run) const {
101 PropertiesHelper::parallel_run_ = parallel_run;
102 }
103
Felipe Lemef0292972016-11-22 13:57:05 -0800104 bool IsStandalone() const {
Felipe Leme46b85da2016-11-21 17:40:45 -0800105 return calls_ == 1;
106 }
107
Felipe Lemef0292972016-11-22 13:57:05 -0800108 void DropRoot() const {
109 DropRootUser();
Felipe Leme46b85da2016-11-21 17:40:45 -0800110 uid_t uid = getuid();
111 ASSERT_EQ(2000, (int)uid);
112 }
113
Felipe Leme7447d7c2016-11-03 18:12:22 -0700114 protected:
115 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
Dan Shie177e8e2019-06-20 11:08:14 -0700116 const std::string kTestDataPath = kTestPath + "/tests/testdata/";
117 const std::string kSimpleCommand = kTestPath + "/dumpstate_test_fixture";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700118 const std::string kEchoCommand = "/system/bin/echo";
119
120 /*
121 * Copies a text file fixture to a temporary file, returning it's path.
122 *
123 * Useful in cases where the test case changes the content of the tile.
124 */
125 std::string CopyTextFileFixture(const std::string& relative_name) {
126 std::string from = kTestDataPath + relative_name;
127 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
128 // around for poking when the test fails.
129 std::string to = kTestDataPath + relative_name + ".tmp";
130 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
131 android::base::RemoveFileIfExists(to);
132 CopyTextFile(from, to);
133 return to.c_str();
134 }
135
Felipe Leme46b85da2016-11-21 17:40:45 -0800136 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700137 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800138 void ReadFileToString(const std::string& path, std::string* content) {
139 ASSERT_TRUE(android::base::ReadFileToString(path, content))
140 << "could not read contents from " << path;
141 }
142 void WriteStringToFile(const std::string& content, const std::string& path) {
143 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
144 << "could not write contents to " << path;
145 }
146
147 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700148 void CopyTextFile(const std::string& from, const std::string& to) {
149 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800150 ReadFileToString(from, &content);
151 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700152 }
153};
154
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100155class DumpOptionsTest : public Test {
156 public:
157 virtual ~DumpOptionsTest() {
158 }
159 virtual void SetUp() {
160 options_ = Dumpstate::DumpOptions();
161 }
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000162 void TearDown() {
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000163 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100164 Dumpstate::DumpOptions options_;
Abhijeet Kaure370d682019-10-01 16:49:30 +0100165 android::base::unique_fd fd;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100166};
167
168TEST_F(DumpOptionsTest, InitializeNone) {
169 // clang-format off
170 char* argv[] = {
171 const_cast<char*>("dumpstate")
172 };
173 // clang-format on
174
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100175 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
176
177 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Nandana Dutt58d72e22018-11-16 10:30:48 +0000178
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100179 EXPECT_FALSE(options_.do_add_date);
180 EXPECT_FALSE(options_.do_zip_file);
mhasank3a4cfb42020-06-15 18:06:43 -0700181 EXPECT_EQ("", options_.out_dir);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100182 EXPECT_FALSE(options_.use_socket);
183 EXPECT_FALSE(options_.use_control_socket);
184 EXPECT_FALSE(options_.show_header_only);
185 EXPECT_TRUE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800186 EXPECT_FALSE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100187 EXPECT_FALSE(options_.do_progress_updates);
188 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700189 EXPECT_FALSE(options_.limited_only);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800190 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000191}
192
193TEST_F(DumpOptionsTest, InitializeAdbBugreport) {
194 // clang-format off
195 char* argv[] = {
196 const_cast<char*>("dumpstatez"),
197 const_cast<char*>("-S"),
198 const_cast<char*>("-d"),
199 const_cast<char*>("-z"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000200 };
201 // clang-format on
202
203 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
204
205 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
206 EXPECT_TRUE(options_.do_add_date);
207 EXPECT_TRUE(options_.do_zip_file);
208 EXPECT_TRUE(options_.use_control_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000209
210 // Other options retain default values
211 EXPECT_TRUE(options_.do_vibrate);
212 EXPECT_FALSE(options_.show_header_only);
Paul Chang0d2aad72020-02-13 20:04:03 +0800213 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000214 EXPECT_FALSE(options_.do_progress_updates);
215 EXPECT_FALSE(options_.is_remote_mode);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000216 EXPECT_FALSE(options_.use_socket);
mhasankd451a472020-05-26 18:02:39 -0700217 EXPECT_FALSE(options_.limited_only);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800218 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000219}
220
221TEST_F(DumpOptionsTest, InitializeAdbShellBugreport) {
222 // clang-format off
223 char* argv[] = {
224 const_cast<char*>("dumpstate"),
225 const_cast<char*>("-s"),
226 };
227 // clang-format on
228
229 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
230
231 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
232 EXPECT_TRUE(options_.use_socket);
233
234 // Other options retain default values
235 EXPECT_TRUE(options_.do_vibrate);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000236 EXPECT_FALSE(options_.do_add_date);
237 EXPECT_FALSE(options_.do_zip_file);
238 EXPECT_FALSE(options_.use_control_socket);
239 EXPECT_FALSE(options_.show_header_only);
Paul Chang0d2aad72020-02-13 20:04:03 +0800240 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000241 EXPECT_FALSE(options_.do_progress_updates);
242 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700243 EXPECT_FALSE(options_.limited_only);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800244 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000245}
246
247TEST_F(DumpOptionsTest, InitializeFullBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800248 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_FULL, fd, fd, true);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000249 EXPECT_TRUE(options_.do_add_date);
Paul Chang0d2aad72020-02-13 20:04:03 +0800250 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000251 EXPECT_TRUE(options_.do_zip_file);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800252 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::FULL);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000253
254 // Other options retain default values
255 EXPECT_TRUE(options_.do_vibrate);
256 EXPECT_FALSE(options_.use_control_socket);
257 EXPECT_FALSE(options_.show_header_only);
258 EXPECT_FALSE(options_.do_progress_updates);
259 EXPECT_FALSE(options_.is_remote_mode);
260 EXPECT_FALSE(options_.use_socket);
261 EXPECT_FALSE(options_.do_start_service);
mhasankd451a472020-05-26 18:02:39 -0700262 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000263}
264
265TEST_F(DumpOptionsTest, InitializeInteractiveBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800266 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE, fd, fd, true);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000267 EXPECT_TRUE(options_.do_add_date);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000268 EXPECT_TRUE(options_.do_zip_file);
269 EXPECT_TRUE(options_.do_progress_updates);
270 EXPECT_TRUE(options_.do_start_service);
Paul Chang0d2aad72020-02-13 20:04:03 +0800271 EXPECT_TRUE(options_.do_screenshot);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800272 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::INTERACTIVE);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000273
274 // Other options retain default values
275 EXPECT_TRUE(options_.do_vibrate);
276 EXPECT_FALSE(options_.use_control_socket);
277 EXPECT_FALSE(options_.show_header_only);
278 EXPECT_FALSE(options_.is_remote_mode);
279 EXPECT_FALSE(options_.use_socket);
mhasankd451a472020-05-26 18:02:39 -0700280 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000281}
282
283TEST_F(DumpOptionsTest, InitializeRemoteBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800284 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_REMOTE, fd, fd, false);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000285 EXPECT_TRUE(options_.do_add_date);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000286 EXPECT_TRUE(options_.do_zip_file);
287 EXPECT_TRUE(options_.is_remote_mode);
288 EXPECT_FALSE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800289 EXPECT_FALSE(options_.do_screenshot);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800290 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::REMOTE);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000291
292 // Other options retain default values
293 EXPECT_FALSE(options_.use_control_socket);
294 EXPECT_FALSE(options_.show_header_only);
295 EXPECT_FALSE(options_.do_progress_updates);
296 EXPECT_FALSE(options_.use_socket);
mhasankd451a472020-05-26 18:02:39 -0700297 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000298}
299
300TEST_F(DumpOptionsTest, InitializeWearBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800301 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WEAR, fd, fd, true);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000302 EXPECT_TRUE(options_.do_add_date);
Paul Chang0d2aad72020-02-13 20:04:03 +0800303 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000304 EXPECT_TRUE(options_.do_zip_file);
305 EXPECT_TRUE(options_.do_progress_updates);
306 EXPECT_TRUE(options_.do_start_service);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800307 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::WEAR);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000308
309 // Other options retain default values
310 EXPECT_TRUE(options_.do_vibrate);
311 EXPECT_FALSE(options_.use_control_socket);
312 EXPECT_FALSE(options_.show_header_only);
313 EXPECT_FALSE(options_.is_remote_mode);
314 EXPECT_FALSE(options_.use_socket);
mhasankd451a472020-05-26 18:02:39 -0700315 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000316}
317
318TEST_F(DumpOptionsTest, InitializeTelephonyBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800319 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_TELEPHONY, fd, fd, false);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000320 EXPECT_TRUE(options_.do_add_date);
Paul Chang0d2aad72020-02-13 20:04:03 +0800321 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000322 EXPECT_TRUE(options_.do_zip_file);
323 EXPECT_TRUE(options_.telephony_only);
Hunter Knepshield820f9bc2020-02-05 20:10:53 -0800324 EXPECT_TRUE(options_.do_progress_updates);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800325 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::CONNECTIVITY);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000326
327 // Other options retain default values
328 EXPECT_TRUE(options_.do_vibrate);
329 EXPECT_FALSE(options_.use_control_socket);
330 EXPECT_FALSE(options_.show_header_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000331 EXPECT_FALSE(options_.is_remote_mode);
332 EXPECT_FALSE(options_.use_socket);
mhasankd451a472020-05-26 18:02:39 -0700333 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000334}
335
336TEST_F(DumpOptionsTest, InitializeWifiBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800337 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WIFI, fd, fd, false);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000338 EXPECT_TRUE(options_.do_add_date);
Paul Chang0d2aad72020-02-13 20:04:03 +0800339 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000340 EXPECT_TRUE(options_.do_zip_file);
341 EXPECT_TRUE(options_.wifi_only);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800342 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::WIFI);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000343
344 // Other options retain default values
345 EXPECT_TRUE(options_.do_vibrate);
346 EXPECT_FALSE(options_.use_control_socket);
347 EXPECT_FALSE(options_.show_header_only);
348 EXPECT_FALSE(options_.do_progress_updates);
349 EXPECT_FALSE(options_.is_remote_mode);
350 EXPECT_FALSE(options_.use_socket);
mhasankd451a472020-05-26 18:02:39 -0700351 EXPECT_FALSE(options_.limited_only);
352}
353
354TEST_F(DumpOptionsTest, InitializeLimitedOnlyBugreport) {
355 // clang-format off
356 char* argv[] = {
357 const_cast<char*>("dumpstatez"),
358 const_cast<char*>("-S"),
359 const_cast<char*>("-d"),
360 const_cast<char*>("-z"),
361 const_cast<char*>("-q"),
mhasank2d75c442020-06-11 15:05:25 -0700362 const_cast<char*>("-L"),
363 const_cast<char*>("-o abc")
mhasankd451a472020-05-26 18:02:39 -0700364 };
365 // clang-format on
366
367 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
368
369 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
370 EXPECT_TRUE(options_.do_add_date);
371 EXPECT_TRUE(options_.do_zip_file);
372 EXPECT_TRUE(options_.use_control_socket);
373 EXPECT_FALSE(options_.do_vibrate);
374 EXPECT_TRUE(options_.limited_only);
mhasank3a4cfb42020-06-15 18:06:43 -0700375 EXPECT_EQ(" abc", std::string(options_.out_dir));
mhasankd451a472020-05-26 18:02:39 -0700376
377 // Other options retain default values
378 EXPECT_FALSE(options_.show_header_only);
379 EXPECT_FALSE(options_.do_screenshot);
380 EXPECT_FALSE(options_.do_progress_updates);
381 EXPECT_FALSE(options_.is_remote_mode);
382 EXPECT_FALSE(options_.use_socket);
383 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000384}
385
386TEST_F(DumpOptionsTest, InitializeDefaultBugReport) {
387 // default: commandline options are not overridden
388 // clang-format off
389 char* argv[] = {
390 const_cast<char*>("bugreport"),
391 const_cast<char*>("-d"),
392 const_cast<char*>("-p"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000393 const_cast<char*>("-z"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000394 };
395 // clang-format on
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000396 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
397
398 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
399 EXPECT_TRUE(options_.do_add_date);
Paul Chang0d2aad72020-02-13 20:04:03 +0800400 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000401 EXPECT_TRUE(options_.do_zip_file);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800402 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000403
404 // Other options retain default values
405 EXPECT_TRUE(options_.do_vibrate);
406 EXPECT_FALSE(options_.use_control_socket);
407 EXPECT_FALSE(options_.show_header_only);
408 EXPECT_FALSE(options_.do_progress_updates);
409 EXPECT_FALSE(options_.is_remote_mode);
410 EXPECT_FALSE(options_.use_socket);
411 EXPECT_FALSE(options_.wifi_only);
mhasankd451a472020-05-26 18:02:39 -0700412 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100413}
414
415TEST_F(DumpOptionsTest, InitializePartial1) {
416 // clang-format off
417 char* argv[] = {
418 const_cast<char*>("dumpstate"),
419 const_cast<char*>("-d"),
420 const_cast<char*>("-z"),
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100421 const_cast<char*>("-s"),
422 const_cast<char*>("-S"),
423
424 };
425 // clang-format on
426
427 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
428
429 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
430 EXPECT_TRUE(options_.do_add_date);
431 EXPECT_TRUE(options_.do_zip_file);
432 // TODO: Maybe we should trim the filename
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100433 EXPECT_TRUE(options_.use_socket);
434 EXPECT_TRUE(options_.use_control_socket);
435
436 // Other options retain default values
437 EXPECT_FALSE(options_.show_header_only);
438 EXPECT_TRUE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800439 EXPECT_FALSE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100440 EXPECT_FALSE(options_.do_progress_updates);
441 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700442 EXPECT_FALSE(options_.limited_only);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800443 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100444}
445
446TEST_F(DumpOptionsTest, InitializePartial2) {
447 // clang-format off
448 char* argv[] = {
449 const_cast<char*>("dumpstate"),
450 const_cast<char*>("-v"),
451 const_cast<char*>("-q"),
452 const_cast<char*>("-p"),
453 const_cast<char*>("-P"),
454 const_cast<char*>("-R"),
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100455 };
456 // clang-format on
457
458 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
459
460 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
461 EXPECT_TRUE(options_.show_header_only);
462 EXPECT_FALSE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800463 EXPECT_TRUE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100464 EXPECT_TRUE(options_.do_progress_updates);
465 EXPECT_TRUE(options_.is_remote_mode);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100466
467 // Other options retain default values
468 EXPECT_FALSE(options_.do_add_date);
469 EXPECT_FALSE(options_.do_zip_file);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100470 EXPECT_FALSE(options_.use_socket);
471 EXPECT_FALSE(options_.use_control_socket);
mhasankd451a472020-05-26 18:02:39 -0700472 EXPECT_FALSE(options_.limited_only);
Hunter Knepshield8540faf2020-02-04 19:47:20 -0800473 EXPECT_EQ(options_.dumpstate_hal_mode, DumpstateMode::DEFAULT);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100474}
475
476TEST_F(DumpOptionsTest, InitializeHelp) {
477 // clang-format off
478 char* argv[] = {
479 const_cast<char*>("dumpstate"),
480 const_cast<char*>("-h")
481 };
482 // clang-format on
483
484 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
485
486 // -h is for help.
487 EXPECT_EQ(status, Dumpstate::RunStatus::HELP);
488}
489
490TEST_F(DumpOptionsTest, InitializeUnknown) {
491 // clang-format off
492 char* argv[] = {
493 const_cast<char*>("dumpstate"),
494 const_cast<char*>("-u") // unknown flag
495 };
496 // clang-format on
497
498 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
499
500 // -u is unknown.
501 EXPECT_EQ(status, Dumpstate::RunStatus::INVALID_INPUT);
502}
503
504TEST_F(DumpOptionsTest, ValidateOptionsNeedOutfile1) {
505 options_.do_zip_file = true;
Nandana Dutt9a76d202019-01-21 15:56:48 +0000506 // Writing to socket = !writing to file.
507 options_.use_socket = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100508 EXPECT_FALSE(options_.ValidateOptions());
Nandana Dutt9a76d202019-01-21 15:56:48 +0000509
510 options_.use_socket = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100511 EXPECT_TRUE(options_.ValidateOptions());
512}
513
514TEST_F(DumpOptionsTest, ValidateOptionsNeedOutfile2) {
Abhijeet Kaure370d682019-10-01 16:49:30 +0100515 options_.do_progress_updates = true;
Nandana Dutt9a76d202019-01-21 15:56:48 +0000516 // Writing to socket = !writing to file.
517 options_.use_socket = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100518 EXPECT_FALSE(options_.ValidateOptions());
Nandana Dutt9a76d202019-01-21 15:56:48 +0000519
520 options_.use_socket = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100521 EXPECT_TRUE(options_.ValidateOptions());
522}
523
524TEST_F(DumpOptionsTest, ValidateOptionsNeedZipfile) {
525 options_.use_control_socket = true;
526 EXPECT_FALSE(options_.ValidateOptions());
527
528 options_.do_zip_file = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100529 EXPECT_TRUE(options_.ValidateOptions());
530}
531
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100532TEST_F(DumpOptionsTest, ValidateOptionsRemoteMode) {
533 options_.is_remote_mode = true;
534 EXPECT_FALSE(options_.ValidateOptions());
535
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100536 options_.do_zip_file = true;
537 options_.do_add_date = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100538 EXPECT_TRUE(options_.ValidateOptions());
539}
540
Felipe Leme7447d7c2016-11-03 18:12:22 -0700541class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700542 public:
543 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800544 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700545 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700546 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700547 ds.progress_.reset(new Progress());
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100548 ds.options_.reset(new Dumpstate::DumpOptions());
Felipe Leme4c2d6632016-09-28 14:32:00 -0700549 }
550
Rhed Jao1c855122020-07-16 17:37:39 +0800551 void TearDown() {
552 ds.ShutdownDumpPool();
553 }
554
Felipe Leme4c2d6632016-09-28 14:32:00 -0700555 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700556 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700557 const CommandOptions& options = CommandOptions::DEFAULT) {
558 CaptureStdout();
559 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700560 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700561 out = GetCapturedStdout();
562 err = GetCapturedStderr();
563 return status;
564 }
565
Felipe Lemecef02982016-10-03 17:22:22 -0700566 // Dumps a file and capture `stdout` and `stderr`.
567 int DumpFile(const std::string& title, const std::string& path) {
568 CaptureStdout();
569 CaptureStderr();
570 int status = ds.DumpFile(title, path);
571 out = GetCapturedStdout();
572 err = GetCapturedStderr();
573 return status;
574 }
575
Nandana Dutt402a8392019-06-14 14:25:13 +0100576 void SetProgress(long progress, long initial_max) {
577 ds.last_reported_percent_progress_ = 0;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100578 ds.options_->do_progress_updates = true;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700579 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
580 }
581
Rhed Jao1c855122020-07-16 17:37:39 +0800582 void EnableParallelRunIfNeeded() {
583 ds.EnableParallelRunIfNeeded();
584 }
585
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100586 std::string GetProgressMessage(int progress, int max,
587 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700588 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
589 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700590
Felipe Leme7447d7c2016-11-03 18:12:22 -0700591 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700592
Felipe Leme009ecbb2016-11-07 10:18:44 -0800593 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700594 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800595 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700596 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700597 }
598
Felipe Leme009ecbb2016-11-07 10:18:44 -0800599 if (update_progress) {
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100600 message += android::base::StringPrintf("Setting progress: %d/%d (%d%%)\n",
601 progress, max, (100 * progress / max));
Felipe Leme009ecbb2016-11-07 10:18:44 -0800602 }
603
604 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700605 }
606
Felipe Leme4c2d6632016-09-28 14:32:00 -0700607 // `stdout` and `stderr` from the last command ran.
608 std::string out, err;
609
Felipe Lemefd8affa2016-09-30 17:38:57 -0700610 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700611};
612
613TEST_F(DumpstateTest, RunCommandNoArgs) {
614 EXPECT_EQ(-1, RunCommand("", {}));
615}
616
617TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700618 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700619 EXPECT_THAT(out, StrEq("stdout\n"));
620 EXPECT_THAT(err, StrEq("stderr\n"));
621}
622
623TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700624 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700625 EXPECT_THAT(err, StrEq("stderr\n"));
Greg Kaiser3a811c12019-05-21 12:48:59 -0700626 // The duration may not get output, depending on how long it takes,
627 // so we just check the prefix.
Felipe Lemefd8affa2016-09-30 17:38:57 -0700628 EXPECT_THAT(out,
Nandana Dutt47527b52019-03-29 15:34:36 +0000629 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700630}
631
Felipe Lemefd8affa2016-09-30 17:38:57 -0700632TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700633 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700634 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700635 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
636 EXPECT_THAT(out, StrEq("stdout\n"));
637 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
638}
639
640TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700641 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700642 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700643 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700644 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700645}
646
647TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700648 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700649 EXPECT_THAT(err, IsEmpty());
650 EXPECT_THAT(out, StrEq("one\n"));
651}
652
Felipe Lemefd8affa2016-09-30 17:38:57 -0700653TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700654 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700655 EXPECT_THAT(err, IsEmpty());
656 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
657}
658
659TEST_F(DumpstateTest, RunCommandDryRun) {
660 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700661 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Greg Kaiser3a811c12019-05-21 12:48:59 -0700662 // The duration may not get output, depending on how long it takes,
663 // so we just check the prefix.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700664 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Nandana Dutt47527b52019-03-29 15:34:36 +0000665 ") ------\n\t(skipped on dry run)\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700666 EXPECT_THAT(err, IsEmpty());
667}
668
669TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
670 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700671 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700672 EXPECT_THAT(out, IsEmpty());
673 EXPECT_THAT(err, IsEmpty());
674}
675
676TEST_F(DumpstateTest, RunCommandDryRunAlways) {
677 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700678 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700679 EXPECT_THAT(out, StrEq("stdout\n"));
680 EXPECT_THAT(err, StrEq("stderr\n"));
681}
682
Felipe Lemefd8affa2016-09-30 17:38:57 -0700683TEST_F(DumpstateTest, RunCommandNotFound) {
684 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
685 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
686 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
687}
688
689TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700690 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
691 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700692 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700693 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700694 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700695}
696
697TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700698 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700699 // We don't know the exit code, so check just the prefix.
700 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700701 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700702 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700703 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700704}
705
706TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700707 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700708 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700709 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700710 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700711 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700712 " --sleep 2' timed out after 1"));
713}
714
715TEST_F(DumpstateTest, RunCommandIsKilled) {
716 CaptureStdout();
717 CaptureStderr();
718
719 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700720 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700721 CommandOptions::WithTimeout(100).Always().Build()));
722 });
723
724 // Capture pid and pre-sleep output.
725 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
726 std::string err = GetCapturedStderr();
727 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
728
729 std::string out = GetCapturedStdout();
730 std::vector<std::string> lines = android::base::Split(out, "\n");
731 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
732
733 int pid = atoi(lines[0].c_str());
734 EXPECT_THAT(lines[1], StrEq("stdout line1"));
735 EXPECT_THAT(lines[2], IsEmpty()); // \n
736
737 // Then kill the process.
738 CaptureStdout();
739 CaptureStderr();
740 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
741 t.join();
742
743 // Finally, check output after murder.
744 out = GetCapturedStdout();
745 err = GetCapturedStderr();
746
Felipe Leme7447d7c2016-11-03 18:12:22 -0700747 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700748 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700749 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700750 " --pid --sleep 20' failed: killed by signal 15\n"));
751}
752
Felipe Leme75876a22016-10-27 16:31:27 -0700753TEST_F(DumpstateTest, RunCommandProgress) {
754 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
755 ds.listener_ = listener;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700756 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700757
Nandana Duttbabf6c72019-01-15 14:11:12 +0000758 EXPECT_CALL(*listener, onProgress(66)); // 20/30 %
Felipe Leme7447d7c2016-11-03 18:12:22 -0700759 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100760 std::string progress_message = GetProgressMessage(20, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700761 EXPECT_THAT(out, StrEq("stdout\n"));
762 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
763
Nandana Dutt402a8392019-06-14 14:25:13 +0100764 EXPECT_CALL(*listener, onProgress(80)); // 24/30 %
765 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100766 progress_message = GetProgressMessage(24, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700767 EXPECT_THAT(out, StrEq("stdout\n"));
768 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
769
770 // Make sure command ran while in dry_run is counted.
771 SetDryRun(true);
Nandana Dutt402a8392019-06-14 14:25:13 +0100772 EXPECT_CALL(*listener, onProgress(90)); // 27/30 %
773 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100774 progress_message = GetProgressMessage(27, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700775 EXPECT_THAT(out, IsEmpty());
776 EXPECT_THAT(err, StrEq(progress_message));
777
Nandana Dutt402a8392019-06-14 14:25:13 +0100778 SetDryRun(false);
779 EXPECT_CALL(*listener, onProgress(96)); // 29/30 %
780 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(2).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100781 progress_message = GetProgressMessage(29, 30);
Felipe Leme009ecbb2016-11-07 10:18:44 -0800782 EXPECT_THAT(out, StrEq("stdout\n"));
783 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
784
Nandana Dutt402a8392019-06-14 14:25:13 +0100785 EXPECT_CALL(*listener, onProgress(100)); // 30/30 %
Felipe Leme009ecbb2016-11-07 10:18:44 -0800786 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100787 progress_message = GetProgressMessage(30, 30);
Felipe Leme009ecbb2016-11-07 10:18:44 -0800788 EXPECT_THAT(out, StrEq("stdout\n"));
789 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
790
791 ds.listener_.clear();
792}
793
Felipe Lemed80e6b62016-10-03 13:08:14 -0700794TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800795 if (!IsStandalone()) {
796 // TODO: temporarily disabled because it might cause other tests to fail after dropping
797 // to Shell - need to refactor tests to avoid this problem)
798 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
799 return;
800 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700801 // First check root case - only available when running with 'adb root'.
802 uid_t uid = getuid();
803 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700804 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700805 EXPECT_THAT(out, StrEq("0\nstdout\n"));
806 EXPECT_THAT(err, StrEq("stderr\n"));
807 return;
808 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700809 // Then run dropping root.
810 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700811 CommandOptions::WithTimeout(1).DropRoot().Build()));
812 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700813 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700814}
815
816TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800817 if (!IsStandalone()) {
818 // TODO: temporarily disabled because it might cause other tests to fail after dropping
819 // to Shell - need to refactor tests to avoid this problem)
820 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
821 return;
822 }
Felipe Lemef0292972016-11-22 13:57:05 -0800823 if (!PropertiesHelper::IsUserBuild()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700824 // Emulates user build if necessarily.
825 SetBuildType("user");
826 }
827
828 DropRoot();
829
Felipe Leme7447d7c2016-11-03 18:12:22 -0700830 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700831
832 // We don't know the exact path of su, so we just check for the 'root ...' commands
833 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700834 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700835 EXPECT_THAT(err, IsEmpty());
836}
837
Felipe Leme46b85da2016-11-21 17:40:45 -0800838TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
839 if (!IsStandalone()) {
840 // TODO: temporarily disabled because it might cause other tests to fail after dropping
841 // to Shell - need to refactor tests to avoid this problem)
842 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
843 return;
844 }
Felipe Lemef0292972016-11-22 13:57:05 -0800845 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800846 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
847 return;
848 }
849
850 DropRoot();
851
852 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
853 CommandOptions::WithTimeout(1).AsRoot().Build()));
854
855 EXPECT_THAT(out, StrEq("0\nstdout\n"));
856 EXPECT_THAT(err, StrEq("stderr\n"));
857}
858
Nandana Dutt4b392be2018-11-02 16:17:05 +0000859TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild_withUnroot) {
860 if (!IsStandalone()) {
861 // TODO: temporarily disabled because it might cause other tests to fail after dropping
862 // to Shell - need to refactor tests to avoid this problem)
863 MYLOGE(
864 "Skipping DumpstateTest.RunCommandAsRootNonUserBuild_withUnroot() "
865 "on test suite\n")
866 return;
867 }
868 if (PropertiesHelper::IsUserBuild()) {
869 ALOGI("Skipping RunCommandAsRootNonUserBuild_withUnroot on user builds\n");
870 return;
871 }
872
873 // Same test as above, but with unroot property set, which will override su availability.
874 SetUnroot(true);
875 DropRoot();
876
877 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
878 CommandOptions::WithTimeout(1).AsRoot().Build()));
879
880 // AsRoot is ineffective.
881 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
882 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
883}
884
Yifan Hong48e83a12017-10-03 14:10:07 -0700885TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnUserBuild) {
886 if (!IsStandalone()) {
887 // TODO: temporarily disabled because it might cause other tests to fail after dropping
888 // to Shell - need to refactor tests to avoid this problem)
889 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
890 return;
891 }
892 if (!PropertiesHelper::IsUserBuild()) {
893 // Emulates user build if necessarily.
894 SetBuildType("user");
895 }
896
897 DropRoot();
898
899 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
900 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
901
902 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
903 EXPECT_THAT(err, StrEq("stderr\n"));
904}
905
906TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild) {
907 if (!IsStandalone()) {
908 // TODO: temporarily disabled because it might cause other tests to fail after dropping
909 // to Shell - need to refactor tests to avoid this problem)
910 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
911 return;
912 }
913 if (PropertiesHelper::IsUserBuild()) {
914 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
915 return;
916 }
917
918 DropRoot();
919
920 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
921 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
922
923 EXPECT_THAT(out, StrEq("0\nstdout\n"));
924 EXPECT_THAT(err, StrEq("stderr\n"));
925}
926
Nandana Dutt4b392be2018-11-02 16:17:05 +0000927TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild_withUnroot) {
928 if (!IsStandalone()) {
929 // TODO: temporarily disabled because it might cause other tests to fail after dropping
930 // to Shell - need to refactor tests to avoid this problem)
931 MYLOGE(
932 "Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild_withUnroot() "
933 "on test suite\n")
934 return;
935 }
936 if (PropertiesHelper::IsUserBuild()) {
937 ALOGI("Skipping RunCommandAsRootIfAvailableOnDebugBuild_withUnroot on user builds\n");
938 return;
939 }
940 // Same test as above, but with unroot property set, which will override su availability.
941 SetUnroot(true);
942
943 DropRoot();
944
945 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
946 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
947
948 // It's a userdebug build, so "su root" should be available, but unroot=true overrides it.
949 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
950 EXPECT_THAT(err, StrEq("stderr\n"));
951}
952
Felipe Lemecef02982016-10-03 17:22:22 -0700953TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
954 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
955 EXPECT_THAT(out,
956 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
957 EXPECT_THAT(err, IsEmpty());
958}
959
960TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
961 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
962 EXPECT_THAT(err, IsEmpty());
Greg Kaiser3a811c12019-05-21 12:48:59 -0700963 // The duration may not get output, depending on how long it takes,
964 // so we just check the prefix.
Felipe Lemecef02982016-10-03 17:22:22 -0700965 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
966 "such file or directory\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700967}
968
969TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700970 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700971 EXPECT_THAT(err, IsEmpty());
972 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
973}
974
975TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700976 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700977 EXPECT_THAT(err, IsEmpty());
978 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
979}
980
981TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700982 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700983 EXPECT_THAT(err, IsEmpty());
984 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
985}
986
987TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700988 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700989 EXPECT_THAT(err, IsEmpty());
990 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
991}
992
993TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
994 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700995 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700996 EXPECT_THAT(err, IsEmpty());
997 EXPECT_THAT(out, IsEmpty());
998}
999
1000TEST_F(DumpstateTest, DumpFileOnDryRun) {
1001 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001002 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -07001003 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -08001004 EXPECT_THAT(
1005 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
Nandana Dutt47527b52019-03-29 15:34:36 +00001006 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n"));
Felipe Lemecef02982016-10-03 17:22:22 -07001007}
1008
Felipe Leme75876a22016-10-27 16:31:27 -07001009TEST_F(DumpstateTest, DumpFileUpdateProgress) {
1010 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
1011 ds.listener_ = listener;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001012 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -07001013
Nandana Duttbabf6c72019-01-15 14:11:12 +00001014 EXPECT_CALL(*listener, onProgress(16)); // 5/30 %
Felipe Leme7447d7c2016-11-03 18:12:22 -07001015 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -07001016
Abhijeet Kaured5d6a62019-10-07 15:02:05 +01001017 std::string progress_message = GetProgressMessage(5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
Felipe Leme75876a22016-10-27 16:31:27 -07001018 EXPECT_THAT(err, StrEq(progress_message));
1019 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1020
1021 ds.listener_.clear();
1022}
1023
Rhed Jao1c855122020-07-16 17:37:39 +08001024TEST_F(DumpstateTest, DumpPool_withOutputToFileAndParallelRunEnabled_notNull) {
1025 ds.options_->use_socket = false;
1026 SetParallelRun(true);
1027 EnableParallelRunIfNeeded();
1028 EXPECT_TRUE(ds.options_->OutputToFile());
Rhed Jao4875aa62020-07-20 17:46:29 +08001029 EXPECT_TRUE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +08001030 EXPECT_TRUE(ds.dump_pool_);
1031}
1032
1033TEST_F(DumpstateTest, DumpPool_withNotOutputToFile_isNull) {
1034 ds.options_->use_socket = true;
1035 EnableParallelRunIfNeeded();
1036 EXPECT_FALSE(ds.options_->OutputToFile());
Rhed Jao4875aa62020-07-20 17:46:29 +08001037 EXPECT_FALSE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +08001038 EXPECT_FALSE(ds.dump_pool_);
1039}
1040
1041TEST_F(DumpstateTest, DumpPool_withParallelRunDisabled_isNull) {
1042 SetParallelRun(false);
1043 EnableParallelRunIfNeeded();
Rhed Jao4875aa62020-07-20 17:46:29 +08001044 EXPECT_FALSE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +08001045 EXPECT_FALSE(ds.dump_pool_);
1046}
1047
Felipe Leme7447d7c2016-11-03 18:12:22 -07001048class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -07001049 public:
1050 DumpstateService dss;
1051};
1052
Felipe Leme7447d7c2016-11-03 18:12:22 -07001053class ProgressTest : public DumpstateBaseTest {
1054 public:
1055 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
1056 return Progress(max, growth_factor, path);
1057 }
1058
1059 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
1060 std::string expected_content =
1061 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
1062 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -08001063 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001064 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
1065 }
1066};
1067
1068TEST_F(ProgressTest, SimpleTest) {
1069 Progress progress;
1070 EXPECT_EQ(0, progress.Get());
1071 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1072 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1073
1074 bool max_increased = progress.Inc(1);
1075 EXPECT_EQ(1, progress.Get());
1076 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1077 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1078 EXPECT_FALSE(max_increased);
1079
1080 // Ignore negative increase.
1081 max_increased = progress.Inc(-1);
1082 EXPECT_EQ(1, progress.Get());
1083 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1084 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1085 EXPECT_FALSE(max_increased);
1086}
1087
1088TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
1089 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1090 EXPECT_EQ(0, progress.Get());
1091 EXPECT_EQ(10, progress.GetInitialMax());
1092 EXPECT_EQ(10, progress.GetMax());
1093
1094 // No increase
1095 bool max_increased = progress.Inc(10);
1096 EXPECT_EQ(10, progress.Get());
1097 EXPECT_EQ(10, progress.GetMax());
1098 EXPECT_FALSE(max_increased);
1099
1100 // Increase, with new value < max*20%
1101 max_increased = progress.Inc(1);
1102 EXPECT_EQ(11, progress.Get());
1103 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
1104 EXPECT_TRUE(max_increased);
1105}
1106
1107TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
1108 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1109 EXPECT_EQ(0, progress.Get());
1110 EXPECT_EQ(10, progress.GetInitialMax());
1111 EXPECT_EQ(10, progress.GetMax());
1112
1113 // No increase
1114 bool max_increased = progress.Inc(10);
1115 EXPECT_EQ(10, progress.Get());
1116 EXPECT_EQ(10, progress.GetMax());
1117 EXPECT_FALSE(max_increased);
1118
1119 // Increase, with new value > max*20%
1120 max_increased = progress.Inc(5);
1121 EXPECT_EQ(15, progress.Get());
1122 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
1123 EXPECT_TRUE(max_increased);
1124}
1125
1126TEST_F(ProgressTest, InvalidPath) {
1127 Progress progress("/devil/null");
1128 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1129}
1130
1131TEST_F(ProgressTest, EmptyFile) {
1132 Progress progress(CopyTextFileFixture("empty-file.txt"));
1133 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1134}
1135
1136TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
1137 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
1138 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1139}
1140
1141TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
1142 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
1143 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1144}
1145
1146TEST_F(ProgressTest, InvalidLineBothNAN) {
1147 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
1148 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1149}
1150
1151TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
1152 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
1153 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1154}
1155
1156TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
1157 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
1158 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1159}
1160
1161TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
1162 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
1163 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1164}
1165
1166TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
1167 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
1168 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1169}
1170
1171// Tests stats are properly saved when the file does not exists.
1172TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001173 if (!IsStandalone()) {
1174 // TODO: temporarily disabled because it's failing when running as suite
1175 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
1176 return;
1177 }
1178
Felipe Leme7447d7c2016-11-03 18:12:22 -07001179 std::string path = kTestDataPath + "FirstTime.txt";
1180 android::base::RemoveFileIfExists(path);
1181
1182 Progress run1(path);
1183 EXPECT_EQ(0, run1.Get());
1184 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
1185 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1186
1187 bool max_increased = run1.Inc(20);
1188 EXPECT_EQ(20, run1.Get());
1189 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1190 EXPECT_FALSE(max_increased);
1191
1192 run1.Save();
1193 AssertStats(path, 1, 20);
1194}
1195
1196// Tests what happens when the persistent settings contains the average duration of 1 run.
1197// Data on file is 1 run and 109 average.
1198TEST_F(ProgressTest, SecondTime) {
1199 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
1200
1201 Progress run1 = GetInstance(-42, 1.2, path);
1202 EXPECT_EQ(0, run1.Get());
1203 EXPECT_EQ(10, run1.GetInitialMax());
1204 EXPECT_EQ(10, run1.GetMax());
1205
1206 bool max_increased = run1.Inc(20);
1207 EXPECT_EQ(20, run1.Get());
1208 EXPECT_EQ(24, run1.GetMax());
1209 EXPECT_TRUE(max_increased);
1210
1211 // Average now is 2 runs and (10 + 20)/ 2 = 15
1212 run1.Save();
1213 AssertStats(path, 2, 15);
1214
1215 Progress run2 = GetInstance(-42, 1.2, path);
1216 EXPECT_EQ(0, run2.Get());
1217 EXPECT_EQ(15, run2.GetInitialMax());
1218 EXPECT_EQ(15, run2.GetMax());
1219
1220 max_increased = run2.Inc(25);
1221 EXPECT_EQ(25, run2.Get());
1222 EXPECT_EQ(30, run2.GetMax());
1223 EXPECT_TRUE(max_increased);
1224
1225 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
1226 run2.Save();
1227 AssertStats(path, 3, 18);
1228
1229 Progress run3 = GetInstance(-42, 1.2, path);
1230 EXPECT_EQ(0, run3.Get());
1231 EXPECT_EQ(18, run3.GetInitialMax());
1232 EXPECT_EQ(18, run3.GetMax());
1233
1234 // Make sure average decreases as well
1235 max_increased = run3.Inc(5);
1236 EXPECT_EQ(5, run3.Get());
1237 EXPECT_EQ(18, run3.GetMax());
1238 EXPECT_FALSE(max_increased);
1239
1240 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
1241 run3.Save();
1242 AssertStats(path, 4, 14);
1243}
1244
1245// Tests what happens when the persistent settings contains the average duration of 2 runs.
1246// Data on file is 2 runs and 15 average.
1247TEST_F(ProgressTest, ThirdTime) {
1248 std::string path = CopyTextFileFixture("stats-two-runs.txt");
1249 AssertStats(path, 2, 15); // Sanity check
1250
1251 Progress run1 = GetInstance(-42, 1.2, path);
1252 EXPECT_EQ(0, run1.Get());
1253 EXPECT_EQ(15, run1.GetInitialMax());
1254 EXPECT_EQ(15, run1.GetMax());
1255
1256 bool max_increased = run1.Inc(20);
1257 EXPECT_EQ(20, run1.Get());
1258 EXPECT_EQ(24, run1.GetMax());
1259 EXPECT_TRUE(max_increased);
1260
1261 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
1262 run1.Save();
1263 AssertStats(path, 3, 16);
1264}
1265
Felipe Leme46b85da2016-11-21 17:40:45 -08001266class DumpstateUtilTest : public DumpstateBaseTest {
1267 public:
1268 void SetUp() {
1269 DumpstateBaseTest::SetUp();
1270 SetDryRun(false);
1271 }
1272
Felipe Leme46b85da2016-11-21 17:40:45 -08001273 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -08001274 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -08001275 }
1276
1277 void CreateFd(const std::string& name) {
1278 path_ = kTestDataPath + name;
1279 MYLOGD("Creating fd for file %s\n", path_.c_str());
1280
1281 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
1282 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1283 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
1284 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
1285 }
1286
1287 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001288 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -08001289 const CommandOptions& options = CommandOptions::DEFAULT) {
1290 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001291 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -08001292 close(fd);
1293
1294 CaptureFdOut();
1295 err = GetCapturedStderr();
1296 return status;
1297 }
1298
1299 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001300 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001301 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001302 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -08001303 close(fd);
1304
1305 CaptureFdOut();
1306 err = GetCapturedStderr();
1307 return status;
1308 }
1309
1310 int fd;
1311
1312 // 'fd` output and `stderr` from the last command ran.
1313 std::string out, err;
1314
1315 private:
1316 std::string path_;
1317};
1318
1319TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -08001320 CreateFd("RunCommandNoArgs.txt");
1321 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001322}
1323
Felipe Lemef0292972016-11-22 13:57:05 -08001324TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001325 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001326 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001327 EXPECT_THAT(out, StrEq("stdout\n"));
1328 EXPECT_THAT(err, StrEq("stderr\n"));
1329}
1330
Felipe Lemef0292972016-11-22 13:57:05 -08001331TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
1332 CreateFd("RunCommandWithNoArgs.txt");
1333 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1334 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
1335 EXPECT_THAT(err, StrEq("stderr\n"));
1336}
1337
Felipe Leme46b85da2016-11-21 17:40:45 -08001338TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
1339 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001340 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001341 EXPECT_THAT(err, IsEmpty());
1342 EXPECT_THAT(out, StrEq("one\n"));
1343}
1344
1345TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
1346 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001347 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001348 EXPECT_THAT(err, IsEmpty());
1349 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
1350}
1351
1352TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
1353 CreateFd("RunCommandWithLoggingMessage.txt");
1354 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -08001355 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -08001356 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
1357 EXPECT_THAT(out, StrEq("stdout\n"));
1358 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
1359}
1360
1361TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
1362 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001363 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
1364 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001365 EXPECT_THAT(out, IsEmpty());
1366 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
1367}
1368
1369TEST_F(DumpstateUtilTest, RunCommandDryRun) {
1370 CreateFd("RunCommandDryRun.txt");
1371 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001372 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1373 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
1374 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
1375 kSimpleCommand.c_str())));
1376 EXPECT_THAT(err, IsEmpty());
1377}
1378
1379TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
1380 CreateFd("RunCommandDryRun.txt");
1381 SetDryRun(true);
1382 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001383 EXPECT_THAT(
1384 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
1385 EXPECT_THAT(err, IsEmpty());
1386}
1387
1388TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
1389 CreateFd("RunCommandDryRunAlways.txt");
1390 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001391 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001392 EXPECT_THAT(out, StrEq("stdout\n"));
1393 EXPECT_THAT(err, StrEq("stderr\n"));
1394}
1395
1396TEST_F(DumpstateUtilTest, RunCommandNotFound) {
1397 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001398 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001399 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
1400 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
1401}
1402
1403TEST_F(DumpstateUtilTest, RunCommandFails) {
1404 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001405 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001406 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
1407 " --exit 42' failed: exit code 42\n"));
1408 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
1409 " --exit 42' failed: exit code 42\n"));
1410}
1411
1412TEST_F(DumpstateUtilTest, RunCommandCrashes) {
1413 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001414 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001415 // We don't know the exit code, so check just the prefix.
1416 EXPECT_THAT(
1417 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1418 EXPECT_THAT(
1419 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1420}
1421
Vishnu Nair6921f802017-11-22 09:17:23 -08001422TEST_F(DumpstateUtilTest, RunCommandTimesoutWithSec) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001423 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001424 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1425 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001426 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1427 " --sleep 2' timed out after 1"));
1428 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1429 " --sleep 2' timed out after 1"));
1430}
1431
Vishnu Nair6921f802017-11-22 09:17:23 -08001432TEST_F(DumpstateUtilTest, RunCommandTimesoutWithMsec) {
1433 CreateFd("RunCommandTimesout.txt");
1434 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1435 CommandOptions::WithTimeoutInMs(1000).Build()));
1436 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1437 " --sleep 2' timed out after 1"));
1438 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1439 " --sleep 2' timed out after 1"));
1440}
1441
1442
Felipe Leme46b85da2016-11-21 17:40:45 -08001443TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
1444 CreateFd("RunCommandIsKilled.txt");
1445 CaptureStderr();
1446
1447 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -08001448 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001449 CommandOptions::WithTimeout(100).Always().Build()));
1450 });
1451
1452 // Capture pid and pre-sleep output.
1453 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
1454 std::string err = GetCapturedStderr();
1455 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
1456
1457 CaptureFdOut();
1458 std::vector<std::string> lines = android::base::Split(out, "\n");
1459 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
1460
1461 int pid = atoi(lines[0].c_str());
1462 EXPECT_THAT(lines[1], StrEq("stdout line1"));
1463 EXPECT_THAT(lines[2], IsEmpty()); // \n
1464
1465 // Then kill the process.
1466 CaptureFdOut();
1467 CaptureStderr();
1468 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1469 t.join();
1470
1471 // Finally, check output after murder.
1472 CaptureFdOut();
1473 err = GetCapturedStderr();
1474
1475 // out starts with the pid, which is an unknown
1476 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1477 " --pid --sleep 20' failed: killed by signal 15\n"));
1478 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1479 " --pid --sleep 20' failed: killed by signal 15\n"));
1480}
1481
1482TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1483 if (!IsStandalone()) {
1484 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1485 // to Shell - need to refactor tests to avoid this problem)
1486 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1487 return;
1488 }
1489 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001490 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001491 // Emulates user build if necessarily.
1492 SetBuildType("user");
1493 }
1494
1495 DropRoot();
1496
Felipe Lemef0292972016-11-22 13:57:05 -08001497 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001498
1499 // We don't know the exact path of su, so we just check for the 'root ...' commands
1500 EXPECT_THAT(out, StartsWith("Skipping"));
1501 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1502 EXPECT_THAT(err, IsEmpty());
1503}
1504
1505TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1506 if (!IsStandalone()) {
1507 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1508 // to Shell - need to refactor tests to avoid this problem)
1509 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1510 return;
1511 }
1512 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001513 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001514 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1515 return;
1516 }
1517
1518 DropRoot();
1519
Felipe Lemef0292972016-11-22 13:57:05 -08001520 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1521 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001522
1523 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1524 EXPECT_THAT(err, StrEq("stderr\n"));
1525}
Felipe Leme46b85da2016-11-21 17:40:45 -08001526
Yifan Hong48e83a12017-10-03 14:10:07 -07001527
1528TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnUserBuild) {
1529 if (!IsStandalone()) {
1530 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1531 // to Shell - need to refactor tests to avoid this problem)
1532 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
1533 return;
1534 }
1535 CreateFd("RunCommandAsRootIfAvailableOnUserBuild.txt");
1536 if (!PropertiesHelper::IsUserBuild()) {
1537 // Emulates user build if necessarily.
1538 SetBuildType("user");
1539 }
1540
1541 DropRoot();
1542
1543 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1544 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1545
1546 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1547 EXPECT_THAT(err, StrEq("stderr\n"));
1548}
1549
1550TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnDebugBuild) {
1551 if (!IsStandalone()) {
1552 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1553 // to Shell - need to refactor tests to avoid this problem)
1554 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
1555 return;
1556 }
1557 CreateFd("RunCommandAsRootIfAvailableOnDebugBuild.txt");
1558 if (PropertiesHelper::IsUserBuild()) {
1559 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1560 return;
1561 }
1562
1563 DropRoot();
1564
1565 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1566 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1567
1568 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1569 EXPECT_THAT(err, StrEq("stderr\n"));
1570}
1571
Felipe Leme46b85da2016-11-21 17:40:45 -08001572TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1573 if (!IsStandalone()) {
1574 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1575 // to Shell - need to refactor tests to avoid this problem)
1576 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1577 return;
1578 }
1579 CreateFd("RunCommandDropRoot.txt");
1580 // First check root case - only available when running with 'adb root'.
1581 uid_t uid = getuid();
1582 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001583 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001584 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1585 EXPECT_THAT(err, StrEq("stderr\n"));
1586 return;
1587 }
1588 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001589 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001590 CommandOptions::WithTimeout(1).DropRoot().Build()));
1591 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1592 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1593}
1594
Felipe Lemef0292972016-11-22 13:57:05 -08001595TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001596 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001597 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001598 EXPECT_THAT(out,
1599 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1600 EXPECT_THAT(err, IsEmpty());
1601}
1602
Felipe Lemef0292972016-11-22 13:57:05 -08001603TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1604 CreateFd("DumpFileNotFound.txt");
1605 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1606 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1607 "file or directory\n"));
1608 EXPECT_THAT(err, IsEmpty());
1609}
1610
Felipe Leme46b85da2016-11-21 17:40:45 -08001611TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1612 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001613 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001614 EXPECT_THAT(err, IsEmpty());
1615 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1616}
1617
1618TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1619 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001620 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001621 EXPECT_THAT(err, IsEmpty());
1622 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1623}
1624
1625TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1626 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001627 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001628 EXPECT_THAT(err, IsEmpty());
1629 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1630}
1631
1632TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1633 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001634 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001635 EXPECT_THAT(err, IsEmpty());
1636 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1637}
1638
Felipe Lemef0292972016-11-22 13:57:05 -08001639TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1640 CreateFd("DumpFileOnDryRun.txt");
1641 SetDryRun(true);
1642 std::string path = kTestDataPath + "single-line.txt";
1643 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1644 EXPECT_THAT(err, IsEmpty());
1645 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1646}
1647
Felipe Leme46b85da2016-11-21 17:40:45 -08001648TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1649 CreateFd("DumpFileOnDryRun.txt");
1650 SetDryRun(true);
1651 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001652 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001653 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001654 EXPECT_THAT(
1655 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1656 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001657}
Ecco Park61ffcf72016-10-27 15:46:26 -07001658
Rhed Jao27077b12020-07-14 18:38:08 +08001659class DumpPoolTest : public DumpstateBaseTest {
1660 public:
1661 void SetUp() {
Rhed Jao1c855122020-07-16 17:37:39 +08001662 dump_pool_ = std::make_unique<DumpPool>(kTestDataPath);
Rhed Jao27077b12020-07-14 18:38:08 +08001663 DumpstateBaseTest::SetUp();
1664 CreateOutputFile();
1665 }
1666
1667 void CreateOutputFile() {
1668 out_path_ = kTestDataPath + "out.txt";
1669 out_fd_.reset(TEMP_FAILURE_RETRY(open(out_path_.c_str(),
1670 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1671 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1672 ASSERT_GE(out_fd_.get(), 0) << "could not create FD for path "
1673 << out_path_;
1674 }
1675
1676 int getTempFileCounts(const std::string& folder) {
1677 int count = 0;
1678 std::unique_ptr<DIR, decltype(&closedir)> dir_ptr(opendir(folder.c_str()),
1679 &closedir);
1680 if (!dir_ptr) {
1681 return -1;
1682 }
1683 int dir_fd = dirfd(dir_ptr.get());
1684 if (dir_fd < 0) {
1685 return -1;
1686 }
1687
1688 struct dirent* de;
1689 while ((de = readdir(dir_ptr.get()))) {
1690 if (de->d_type != DT_REG) {
1691 continue;
1692 }
1693 std::string file_name(de->d_name);
1694 if (file_name.find(DumpPool::PREFIX_TMPFILE_NAME) != 0) {
1695 continue;
1696 }
1697 count++;
1698 }
1699 return count;
1700 }
1701
Rhed Jao1c855122020-07-16 17:37:39 +08001702 void setLogDuration(bool log_duration) {
1703 dump_pool_->setLogDuration(log_duration);
1704 }
1705
1706 std::unique_ptr<DumpPool> dump_pool_;
Rhed Jao27077b12020-07-14 18:38:08 +08001707 android::base::unique_fd out_fd_;
1708 std::string out_path_;
1709};
1710
Rhed Jao1c855122020-07-16 17:37:39 +08001711TEST_F(DumpPoolTest, EnqueueTaskWithFd) {
Rhed Jao27077b12020-07-14 18:38:08 +08001712 auto dump_func_1 = [](int out_fd) {
1713 dprintf(out_fd, "A");
1714 };
1715 auto dump_func_2 = [](int out_fd) {
1716 dprintf(out_fd, "B");
1717 sleep(1);
1718 };
1719 auto dump_func_3 = [](int out_fd) {
1720 dprintf(out_fd, "C");
1721 };
Rhed Jao1c855122020-07-16 17:37:39 +08001722 setLogDuration(/* log_duration = */false);
1723 dump_pool_->enqueueTaskWithFd(/* task_name = */"1", dump_func_1, std::placeholders::_1);
1724 dump_pool_->enqueueTaskWithFd(/* task_name = */"2", dump_func_2, std::placeholders::_1);
1725 dump_pool_->enqueueTaskWithFd(/* task_name = */"3", dump_func_3, std::placeholders::_1);
Rhed Jao27077b12020-07-14 18:38:08 +08001726
Rhed Jao1c855122020-07-16 17:37:39 +08001727 dump_pool_->waitForTask("1", "", out_fd_.get());
1728 dump_pool_->waitForTask("2", "", out_fd_.get());
1729 dump_pool_->waitForTask("3", "", out_fd_.get());
1730 dump_pool_->shutdown();
Rhed Jao27077b12020-07-14 18:38:08 +08001731
1732 std::string result;
1733 ReadFileToString(out_path_, &result);
1734 EXPECT_THAT(result, StrEq("A\nB\nC\n"));
1735 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao1c855122020-07-16 17:37:39 +08001736}
1737
1738TEST_F(DumpPoolTest, EnqueueTask_withDurationLog) {
1739 bool run_1 = false;
1740 auto dump_func_1 = [&]() {
1741 run_1 = true;
1742 };
1743
1744 dump_pool_->enqueueTask(/* task_name = */"1", dump_func_1);
1745 dump_pool_->waitForTask("1", "", out_fd_.get());
1746 dump_pool_->shutdown();
1747
1748 std::string result;
1749 ReadFileToString(out_path_, &result);
1750 EXPECT_TRUE(run_1);
1751 EXPECT_THAT(result, StrEq("------ 0.000s was the duration of '1' ------\n"));
1752 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao27077b12020-07-14 18:38:08 +08001753}
1754
Rhed Jao4875aa62020-07-20 17:46:29 +08001755class TaskQueueTest : public DumpstateBaseTest {
1756public:
1757 void SetUp() {
1758 DumpstateBaseTest::SetUp();
1759 }
1760
1761 TaskQueue task_queue_;
1762};
1763
1764TEST_F(TaskQueueTest, runTask) {
1765 bool is_task1_run = false;
1766 bool is_task2_run = false;
1767 auto task_1 = [&](bool task_cancelled) {
1768 if (task_cancelled) {
1769 return;
1770 }
1771 is_task1_run = true;
1772 };
1773 auto task_2 = [&](bool task_cancelled) {
1774 if (task_cancelled) {
1775 return;
1776 }
1777 is_task2_run = true;
1778 };
1779 task_queue_.add(task_1, std::placeholders::_1);
1780 task_queue_.add(task_2, std::placeholders::_1);
1781
1782 task_queue_.run(/* do_cancel = */false);
1783
1784 EXPECT_TRUE(is_task1_run);
1785 EXPECT_TRUE(is_task2_run);
1786}
1787
1788TEST_F(TaskQueueTest, runTask_withCancelled) {
1789 bool is_task1_cancelled = false;
1790 bool is_task2_cancelled = false;
1791 auto task_1 = [&](bool task_cancelled) {
1792 is_task1_cancelled = task_cancelled;
1793 };
1794 auto task_2 = [&](bool task_cancelled) {
1795 is_task2_cancelled = task_cancelled;
1796 };
1797 task_queue_.add(task_1, std::placeholders::_1);
1798 task_queue_.add(task_2, std::placeholders::_1);
1799
1800 task_queue_.run(/* do_cancel = */true);
1801
1802 EXPECT_TRUE(is_task1_cancelled);
1803 EXPECT_TRUE(is_task2_cancelled);
1804}
1805
Rhed Jao27077b12020-07-14 18:38:08 +08001806
Felipe Leme47e9be22016-12-21 15:37:07 -08001807} // namespace dumpstate
1808} // namespace os
1809} // namespace android