blob: b675c515fe8601167248e1f56ec7eaa58eae175f [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"
24
25#include <gmock/gmock.h>
26#include <gtest/gtest.h>
27
Felipe Leme46b85da2016-11-21 17:40:45 -080028#include <fcntl.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070029#include <libgen.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070030#include <signal.h>
31#include <sys/types.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070032#include <unistd.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070033#include <thread>
Felipe Leme4c2d6632016-09-28 14:32:00 -070034
35#include <android-base/file.h>
Felipe Lemed80e6b62016-10-03 13:08:14 -070036#include <android-base/properties.h>
37#include <android-base/stringprintf.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070038#include <android-base/strings.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070039
Felipe Leme47e9be22016-12-21 15:37:07 -080040namespace android {
41namespace os {
42namespace dumpstate {
Felipe Lemed80e6b62016-10-03 13:08:14 -070043
Felipe Leme4c2d6632016-09-28 14:32:00 -070044using ::testing::EndsWith;
Felipe Leme46b85da2016-11-21 17:40:45 -080045using ::testing::HasSubstr;
Felipe Leme009ecbb2016-11-07 10:18:44 -080046using ::testing::IsNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070047using ::testing::IsEmpty;
Felipe Leme009ecbb2016-11-07 10:18:44 -080048using ::testing::NotNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070049using ::testing::StrEq;
50using ::testing::StartsWith;
51using ::testing::Test;
52using ::testing::internal::CaptureStderr;
53using ::testing::internal::CaptureStdout;
54using ::testing::internal::GetCapturedStderr;
55using ::testing::internal::GetCapturedStdout;
56
Nandana Dutt3f8c7172018-09-25 12:01:54 +010057#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
Felipe Leme75876a22016-10-27 16:31:27 -070059class DumpstateListenerMock : public IDumpstateListener {
60 public:
61 MOCK_METHOD1(onProgressUpdated, binder::Status(int32_t progress));
62 MOCK_METHOD1(onMaxProgressUpdated, binder::Status(int32_t max_progress));
Vishnu Nair20cf5032018-01-05 13:15:49 -080063 MOCK_METHOD4(onSectionComplete, binder::Status(const ::std::string& name, int32_t status,
64 int32_t size, int32_t durationMs));
Felipe Leme75876a22016-10-27 16:31:27 -070065
66 protected:
67 MOCK_METHOD0(onAsBinder, IBinder*());
68};
69
Felipe Leme46b85da2016-11-21 17:40:45 -080070static int calls_;
71
Felipe Leme7447d7c2016-11-03 18:12:22 -070072// Base class for all tests in this file
73class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080074 public:
75 virtual void SetUp() override {
76 calls_++;
Felipe Lemef0292972016-11-22 13:57:05 -080077 SetDryRun(false);
Felipe Leme46b85da2016-11-21 17:40:45 -080078 }
79
Felipe Lemef0292972016-11-22 13:57:05 -080080 void SetDryRun(bool dry_run) const {
81 PropertiesHelper::dry_run_ = dry_run;
82 }
83
84 void SetBuildType(const std::string& build_type) const {
85 PropertiesHelper::build_type_ = build_type;
86 }
87
88 bool IsStandalone() const {
Felipe Leme46b85da2016-11-21 17:40:45 -080089 return calls_ == 1;
90 }
91
Felipe Lemef0292972016-11-22 13:57:05 -080092 void DropRoot() const {
93 DropRootUser();
Felipe Leme46b85da2016-11-21 17:40:45 -080094 uid_t uid = getuid();
95 ASSERT_EQ(2000, (int)uid);
96 }
97
Felipe Leme7447d7c2016-11-03 18:12:22 -070098 protected:
99 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
100 const std::string kFixturesPath = kTestPath + "/../dumpstate_test_fixture/";
Felipe Leme7fb8dee2017-08-25 10:15:01 -0700101 const std::string kTestDataPath = kFixturesPath + "tests/testdata/";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700102 const std::string kSimpleCommand = kFixturesPath + "dumpstate_test_fixture";
103 const std::string kEchoCommand = "/system/bin/echo";
104
105 /*
106 * Copies a text file fixture to a temporary file, returning it's path.
107 *
108 * Useful in cases where the test case changes the content of the tile.
109 */
110 std::string CopyTextFileFixture(const std::string& relative_name) {
111 std::string from = kTestDataPath + relative_name;
112 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
113 // around for poking when the test fails.
114 std::string to = kTestDataPath + relative_name + ".tmp";
115 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
116 android::base::RemoveFileIfExists(to);
117 CopyTextFile(from, to);
118 return to.c_str();
119 }
120
Felipe Leme46b85da2016-11-21 17:40:45 -0800121 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700122 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800123 void ReadFileToString(const std::string& path, std::string* content) {
124 ASSERT_TRUE(android::base::ReadFileToString(path, content))
125 << "could not read contents from " << path;
126 }
127 void WriteStringToFile(const std::string& content, const std::string& path) {
128 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
129 << "could not write contents to " << path;
130 }
131
132 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700133 void CopyTextFile(const std::string& from, const std::string& to) {
134 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800135 ReadFileToString(from, &content);
136 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700137 }
138};
139
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100140class DumpOptionsTest : public Test {
141 public:
142 virtual ~DumpOptionsTest() {
143 }
144 virtual void SetUp() {
145 options_ = Dumpstate::DumpOptions();
146 }
147
148 Dumpstate::DumpOptions options_;
149};
150
151TEST_F(DumpOptionsTest, InitializeNone) {
152 // clang-format off
153 char* argv[] = {
154 const_cast<char*>("dumpstate")
155 };
156 // clang-format on
157
158 Dumpstate::DumpOptions options;
159 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
160
161 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
162 EXPECT_FALSE(options_.do_add_date);
163 EXPECT_FALSE(options_.do_zip_file);
164 EXPECT_EQ("", options_.use_outfile);
165 EXPECT_FALSE(options_.use_socket);
166 EXPECT_FALSE(options_.use_control_socket);
167 EXPECT_FALSE(options_.show_header_only);
168 EXPECT_TRUE(options_.do_vibrate);
169 EXPECT_FALSE(options_.do_fb);
170 EXPECT_FALSE(options_.do_progress_updates);
171 EXPECT_FALSE(options_.is_remote_mode);
172 EXPECT_FALSE(options_.do_broadcast);
173}
174
175TEST_F(DumpOptionsTest, InitializePartial1) {
176 // clang-format off
177 char* argv[] = {
178 const_cast<char*>("dumpstate"),
179 const_cast<char*>("-d"),
180 const_cast<char*>("-z"),
181 const_cast<char*>("-o abc"),
182 const_cast<char*>("-s"),
183 const_cast<char*>("-S"),
184
185 };
186 // clang-format on
187
188 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
189
190 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
191 EXPECT_TRUE(options_.do_add_date);
192 EXPECT_TRUE(options_.do_zip_file);
193 // TODO: Maybe we should trim the filename
194 EXPECT_EQ(" abc", std::string(options_.use_outfile));
195 EXPECT_TRUE(options_.use_socket);
196 EXPECT_TRUE(options_.use_control_socket);
197
198 // Other options retain default values
199 EXPECT_FALSE(options_.show_header_only);
200 EXPECT_TRUE(options_.do_vibrate);
201 EXPECT_FALSE(options_.do_fb);
202 EXPECT_FALSE(options_.do_progress_updates);
203 EXPECT_FALSE(options_.is_remote_mode);
204 EXPECT_FALSE(options_.do_broadcast);
205}
206
207TEST_F(DumpOptionsTest, InitializePartial2) {
208 // clang-format off
209 char* argv[] = {
210 const_cast<char*>("dumpstate"),
211 const_cast<char*>("-v"),
212 const_cast<char*>("-q"),
213 const_cast<char*>("-p"),
214 const_cast<char*>("-P"),
215 const_cast<char*>("-R"),
216 const_cast<char*>("-B"),
217 };
218 // clang-format on
219
220 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
221
222 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
223 EXPECT_TRUE(options_.show_header_only);
224 EXPECT_FALSE(options_.do_vibrate);
225 EXPECT_TRUE(options_.do_fb);
226 EXPECT_TRUE(options_.do_progress_updates);
227 EXPECT_TRUE(options_.is_remote_mode);
228 EXPECT_TRUE(options_.do_broadcast);
229
230 // Other options retain default values
231 EXPECT_FALSE(options_.do_add_date);
232 EXPECT_FALSE(options_.do_zip_file);
233 EXPECT_EQ("", options_.use_outfile);
234 EXPECT_FALSE(options_.use_socket);
235 EXPECT_FALSE(options_.use_control_socket);
236}
237
238TEST_F(DumpOptionsTest, InitializeHelp) {
239 // clang-format off
240 char* argv[] = {
241 const_cast<char*>("dumpstate"),
242 const_cast<char*>("-h")
243 };
244 // clang-format on
245
246 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
247
248 // -h is for help.
249 EXPECT_EQ(status, Dumpstate::RunStatus::HELP);
250}
251
252TEST_F(DumpOptionsTest, InitializeUnknown) {
253 // clang-format off
254 char* argv[] = {
255 const_cast<char*>("dumpstate"),
256 const_cast<char*>("-u") // unknown flag
257 };
258 // clang-format on
259
260 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
261
262 // -u is unknown.
263 EXPECT_EQ(status, Dumpstate::RunStatus::INVALID_INPUT);
264}
265
266TEST_F(DumpOptionsTest, ValidateOptionsNeedOutfile1) {
267 options_.do_zip_file = true;
268 EXPECT_FALSE(options_.ValidateOptions());
269 options_.use_outfile = "a/b/c";
270 EXPECT_TRUE(options_.ValidateOptions());
271}
272
273TEST_F(DumpOptionsTest, ValidateOptionsNeedOutfile2) {
274 options_.do_broadcast = true;
275 EXPECT_FALSE(options_.ValidateOptions());
276 options_.use_outfile = "a/b/c";
277 EXPECT_TRUE(options_.ValidateOptions());
278}
279
280TEST_F(DumpOptionsTest, ValidateOptionsNeedZipfile) {
281 options_.use_control_socket = true;
282 EXPECT_FALSE(options_.ValidateOptions());
283
284 options_.do_zip_file = true;
285 options_.use_outfile = "a/b/c"; // do_zip_file needs outfile
286 EXPECT_TRUE(options_.ValidateOptions());
287}
288
289TEST_F(DumpOptionsTest, ValidateOptionsUpdateProgressNeedsBroadcast) {
290 options_.do_progress_updates = true;
291 options_.use_outfile = "a/b/c"; // do_progress_updates needs outfile
292 EXPECT_FALSE(options_.ValidateOptions());
293
294 options_.do_broadcast = true;
295 EXPECT_TRUE(options_.ValidateOptions());
296}
297
298TEST_F(DumpOptionsTest, ValidateOptionsRemoteMode) {
299 options_.is_remote_mode = true;
300 EXPECT_FALSE(options_.ValidateOptions());
301
302 options_.do_broadcast = true;
303 options_.do_zip_file = true;
304 options_.do_add_date = true;
305 options_.use_outfile = "a/b/c"; // do_broadcast needs outfile
306 EXPECT_TRUE(options_.ValidateOptions());
307}
308
Felipe Leme7447d7c2016-11-03 18:12:22 -0700309class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700310 public:
311 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800312 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700313 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700314 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700315 ds.progress_.reset(new Progress());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800316 ds.update_progress_threshold_ = 0;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100317 ds.options_.reset(new Dumpstate::DumpOptions());
Felipe Leme4c2d6632016-09-28 14:32:00 -0700318 }
319
320 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700321 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700322 const CommandOptions& options = CommandOptions::DEFAULT) {
323 CaptureStdout();
324 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700325 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700326 out = GetCapturedStdout();
327 err = GetCapturedStderr();
328 return status;
329 }
330
Felipe Lemecef02982016-10-03 17:22:22 -0700331 // Dumps a file and capture `stdout` and `stderr`.
332 int DumpFile(const std::string& title, const std::string& path) {
333 CaptureStdout();
334 CaptureStderr();
335 int status = ds.DumpFile(title, path);
336 out = GetCapturedStdout();
337 err = GetCapturedStderr();
338 return status;
339 }
340
Felipe Leme009ecbb2016-11-07 10:18:44 -0800341 void SetProgress(long progress, long initial_max, long threshold = 0) {
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100342 ds.options_->do_progress_updates = true;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800343 ds.update_progress_threshold_ = threshold;
344 ds.last_updated_progress_ = 0;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700345 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
346 }
347
Felipe Leme7447d7c2016-11-03 18:12:22 -0700348 std::string GetProgressMessage(const std::string& listener_name, int progress, int max,
Felipe Leme009ecbb2016-11-07 10:18:44 -0800349 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700350 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
351 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700352
Felipe Leme7447d7c2016-11-03 18:12:22 -0700353 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700354
Felipe Leme009ecbb2016-11-07 10:18:44 -0800355 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700356 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800357 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700358 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700359 }
360
Felipe Leme009ecbb2016-11-07 10:18:44 -0800361 if (update_progress) {
362 message += android::base::StringPrintf("Setting progress (%s): %d/%d\n",
363 listener_name.c_str(), progress, max);
364 }
365
366 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700367 }
368
Felipe Leme4c2d6632016-09-28 14:32:00 -0700369 // `stdout` and `stderr` from the last command ran.
370 std::string out, err;
371
Felipe Lemefd8affa2016-09-30 17:38:57 -0700372 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700373};
374
375TEST_F(DumpstateTest, RunCommandNoArgs) {
376 EXPECT_EQ(-1, RunCommand("", {}));
377}
378
379TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700380 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700381 EXPECT_THAT(out, StrEq("stdout\n"));
382 EXPECT_THAT(err, StrEq("stderr\n"));
383}
384
385TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700386 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700387 EXPECT_THAT(err, StrEq("stderr\n"));
388 // We don't know the exact duration, so we check the prefix and suffix
Felipe Lemefd8affa2016-09-30 17:38:57 -0700389 EXPECT_THAT(out,
Felipe Leme7447d7c2016-11-03 18:12:22 -0700390 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n------"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700391 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
392}
393
Felipe Lemefd8affa2016-09-30 17:38:57 -0700394TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700395 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700396 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700397 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
398 EXPECT_THAT(out, StrEq("stdout\n"));
399 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
400}
401
402TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700403 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700404 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700405 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700406 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700407}
408
409TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700410 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700411 EXPECT_THAT(err, IsEmpty());
412 EXPECT_THAT(out, StrEq("one\n"));
413}
414
Felipe Lemefd8affa2016-09-30 17:38:57 -0700415TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700416 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700417 EXPECT_THAT(err, IsEmpty());
418 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
419}
420
421TEST_F(DumpstateTest, RunCommandDryRun) {
422 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700423 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700424 // We don't know the exact duration, so we check the prefix and suffix
Felipe Leme7447d7c2016-11-03 18:12:22 -0700425 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Felipe Leme4c2d6632016-09-28 14:32:00 -0700426 ") ------\n\t(skipped on dry run)\n------"));
427 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
428 EXPECT_THAT(err, IsEmpty());
429}
430
431TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
432 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700433 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700434 EXPECT_THAT(out, IsEmpty());
435 EXPECT_THAT(err, IsEmpty());
436}
437
438TEST_F(DumpstateTest, RunCommandDryRunAlways) {
439 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700440 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700441 EXPECT_THAT(out, StrEq("stdout\n"));
442 EXPECT_THAT(err, StrEq("stderr\n"));
443}
444
Felipe Lemefd8affa2016-09-30 17:38:57 -0700445TEST_F(DumpstateTest, RunCommandNotFound) {
446 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
447 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
448 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
449}
450
451TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700452 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
453 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700454 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700455 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700456 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700457}
458
459TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700460 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700461 // We don't know the exit code, so check just the prefix.
462 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700463 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700464 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700465 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700466}
467
468TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700469 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700470 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700471 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700472 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700473 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700474 " --sleep 2' timed out after 1"));
475}
476
477TEST_F(DumpstateTest, RunCommandIsKilled) {
478 CaptureStdout();
479 CaptureStderr();
480
481 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700482 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700483 CommandOptions::WithTimeout(100).Always().Build()));
484 });
485
486 // Capture pid and pre-sleep output.
487 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
488 std::string err = GetCapturedStderr();
489 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
490
491 std::string out = GetCapturedStdout();
492 std::vector<std::string> lines = android::base::Split(out, "\n");
493 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
494
495 int pid = atoi(lines[0].c_str());
496 EXPECT_THAT(lines[1], StrEq("stdout line1"));
497 EXPECT_THAT(lines[2], IsEmpty()); // \n
498
499 // Then kill the process.
500 CaptureStdout();
501 CaptureStderr();
502 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
503 t.join();
504
505 // Finally, check output after murder.
506 out = GetCapturedStdout();
507 err = GetCapturedStderr();
508
Felipe Leme7447d7c2016-11-03 18:12:22 -0700509 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700510 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700511 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700512 " --pid --sleep 20' failed: killed by signal 15\n"));
513}
514
Felipe Leme75876a22016-10-27 16:31:27 -0700515TEST_F(DumpstateTest, RunCommandProgress) {
516 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
517 ds.listener_ = listener;
518 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700519 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700520
521 EXPECT_CALL(*listener, onProgressUpdated(20));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700522 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700523 std::string progress_message = GetProgressMessage(ds.listener_name_, 20, 30);
524 EXPECT_THAT(out, StrEq("stdout\n"));
525 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
526
527 EXPECT_CALL(*listener, onProgressUpdated(30));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700528 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700529 progress_message = GetProgressMessage(ds.listener_name_, 30, 30);
530 EXPECT_THAT(out, StrEq("stdout\n"));
531 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
532
533 // Run a command that will increase maximum timeout.
534 EXPECT_CALL(*listener, onProgressUpdated(31));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700535 EXPECT_CALL(*listener, onMaxProgressUpdated(37));
536 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
537 progress_message = GetProgressMessage(ds.listener_name_, 31, 37, 30); // 20% increase
Felipe Leme75876a22016-10-27 16:31:27 -0700538 EXPECT_THAT(out, StrEq("stdout\n"));
539 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
540
541 // Make sure command ran while in dry_run is counted.
542 SetDryRun(true);
543 EXPECT_CALL(*listener, onProgressUpdated(35));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700544 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
545 progress_message = GetProgressMessage(ds.listener_name_, 35, 37);
Felipe Leme75876a22016-10-27 16:31:27 -0700546 EXPECT_THAT(out, IsEmpty());
547 EXPECT_THAT(err, StrEq(progress_message));
548
549 ds.listener_.clear();
550}
551
Felipe Leme009ecbb2016-11-07 10:18:44 -0800552TEST_F(DumpstateTest, RunCommandProgressIgnoreThreshold) {
553 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
554 ds.listener_ = listener;
555 ds.listener_name_ = "FoxMulder";
556 SetProgress(0, 8, 5); // 8 max, 5 threshold
557
558 // First update should always be sent.
559 EXPECT_CALL(*listener, onProgressUpdated(1));
560 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
561 std::string progress_message = GetProgressMessage(ds.listener_name_, 1, 8);
562 EXPECT_THAT(out, StrEq("stdout\n"));
563 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
564
565 // Fourth update should be ignored because it's between the threshold (5 -1 = 4 < 5).
566 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
567 EXPECT_THAT(out, StrEq("stdout\n"));
568 EXPECT_THAT(err, StrEq("stderr\n"));
569
570 // Third update should be sent because it reaches threshold (6 - 1 = 5).
571 EXPECT_CALL(*listener, onProgressUpdated(6));
572 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
573 progress_message = GetProgressMessage(ds.listener_name_, 6, 8);
574 EXPECT_THAT(out, StrEq("stdout\n"));
575 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
576
577 // Fourth update should be ignored because it's between the threshold (9 - 6 = 3 < 5).
578 // But max update should be sent.
579 EXPECT_CALL(*listener, onMaxProgressUpdated(10)); // 9 * 120% = 10.8 = 10
580 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
581 progress_message = GetProgressMessage(ds.listener_name_, 9, 10, 8, false);
582 EXPECT_THAT(out, StrEq("stdout\n"));
583 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
584
585 ds.listener_.clear();
586}
587
Felipe Lemed80e6b62016-10-03 13:08:14 -0700588TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800589 if (!IsStandalone()) {
590 // TODO: temporarily disabled because it might cause other tests to fail after dropping
591 // to Shell - need to refactor tests to avoid this problem)
592 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
593 return;
594 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700595 // First check root case - only available when running with 'adb root'.
596 uid_t uid = getuid();
597 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700598 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700599 EXPECT_THAT(out, StrEq("0\nstdout\n"));
600 EXPECT_THAT(err, StrEq("stderr\n"));
601 return;
602 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700603 // Then run dropping root.
604 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700605 CommandOptions::WithTimeout(1).DropRoot().Build()));
606 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700607 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700608}
609
610TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800611 if (!IsStandalone()) {
612 // TODO: temporarily disabled because it might cause other tests to fail after dropping
613 // to Shell - need to refactor tests to avoid this problem)
614 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
615 return;
616 }
Felipe Lemef0292972016-11-22 13:57:05 -0800617 if (!PropertiesHelper::IsUserBuild()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700618 // Emulates user build if necessarily.
619 SetBuildType("user");
620 }
621
622 DropRoot();
623
Felipe Leme7447d7c2016-11-03 18:12:22 -0700624 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700625
626 // We don't know the exact path of su, so we just check for the 'root ...' commands
627 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700628 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700629 EXPECT_THAT(err, IsEmpty());
630}
631
Felipe Leme46b85da2016-11-21 17:40:45 -0800632TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
633 if (!IsStandalone()) {
634 // TODO: temporarily disabled because it might cause other tests to fail after dropping
635 // to Shell - need to refactor tests to avoid this problem)
636 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
637 return;
638 }
Felipe Lemef0292972016-11-22 13:57:05 -0800639 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800640 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
641 return;
642 }
643
644 DropRoot();
645
646 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
647 CommandOptions::WithTimeout(1).AsRoot().Build()));
648
649 EXPECT_THAT(out, StrEq("0\nstdout\n"));
650 EXPECT_THAT(err, StrEq("stderr\n"));
651}
652
Yifan Hong48e83a12017-10-03 14:10:07 -0700653TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnUserBuild) {
654 if (!IsStandalone()) {
655 // TODO: temporarily disabled because it might cause other tests to fail after dropping
656 // to Shell - need to refactor tests to avoid this problem)
657 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
658 return;
659 }
660 if (!PropertiesHelper::IsUserBuild()) {
661 // Emulates user build if necessarily.
662 SetBuildType("user");
663 }
664
665 DropRoot();
666
667 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
668 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
669
670 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
671 EXPECT_THAT(err, StrEq("stderr\n"));
672}
673
674TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild) {
675 if (!IsStandalone()) {
676 // TODO: temporarily disabled because it might cause other tests to fail after dropping
677 // to Shell - need to refactor tests to avoid this problem)
678 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
679 return;
680 }
681 if (PropertiesHelper::IsUserBuild()) {
682 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
683 return;
684 }
685
686 DropRoot();
687
688 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
689 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
690
691 EXPECT_THAT(out, StrEq("0\nstdout\n"));
692 EXPECT_THAT(err, StrEq("stderr\n"));
693}
694
Felipe Lemecef02982016-10-03 17:22:22 -0700695TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
696 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
697 EXPECT_THAT(out,
698 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
699 EXPECT_THAT(err, IsEmpty());
700}
701
702TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
703 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
704 EXPECT_THAT(err, IsEmpty());
705 // We don't know the exact duration, so we check the prefix and suffix
706 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
707 "such file or directory\n"));
708 EXPECT_THAT(out, EndsWith("s was the duration of 'Y U NO EXIST?' ------\n"));
709}
710
711TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700712 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700713 EXPECT_THAT(err, IsEmpty());
714 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
715}
716
717TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700718 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700719 EXPECT_THAT(err, IsEmpty());
720 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
721}
722
723TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700724 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700725 EXPECT_THAT(err, IsEmpty());
726 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
727}
728
729TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700730 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700731 EXPECT_THAT(err, IsEmpty());
732 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
733}
734
735TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
736 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700737 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700738 EXPECT_THAT(err, IsEmpty());
739 EXPECT_THAT(out, IsEmpty());
740}
741
742TEST_F(DumpstateTest, DumpFileOnDryRun) {
743 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700744 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700745 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -0800746 EXPECT_THAT(
747 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
748 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n------"));
Felipe Lemecef02982016-10-03 17:22:22 -0700749 EXPECT_THAT(out, EndsWith("s was the duration of 'Might as well dump. Dump!' ------\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700750}
751
Felipe Leme75876a22016-10-27 16:31:27 -0700752TEST_F(DumpstateTest, DumpFileUpdateProgress) {
753 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
754 ds.listener_ = listener;
755 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700756 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700757
758 EXPECT_CALL(*listener, onProgressUpdated(5));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700759 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -0700760
761 std::string progress_message =
762 GetProgressMessage(ds.listener_name_, 5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
763 EXPECT_THAT(err, StrEq(progress_message));
764 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
765
766 ds.listener_.clear();
767}
768
Felipe Leme7447d7c2016-11-03 18:12:22 -0700769class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -0700770 public:
771 DumpstateService dss;
772};
773
774TEST_F(DumpstateServiceTest, SetListenerNoName) {
775 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800776 sp<IDumpstateToken> token;
Vishnu Nair20cf5032018-01-05 13:15:49 -0800777 EXPECT_TRUE(dss.setListener("", listener, /* getSectionDetails = */ false, &token).isOk());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800778 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700779}
780
781TEST_F(DumpstateServiceTest, SetListenerNoPointer) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800782 sp<IDumpstateToken> token;
Vishnu Nair20cf5032018-01-05 13:15:49 -0800783 EXPECT_TRUE(
784 dss.setListener("whatever", nullptr, /* getSectionDetails = */ false, &token).isOk());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800785 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700786}
787
788TEST_F(DumpstateServiceTest, SetListenerTwice) {
789 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800790 sp<IDumpstateToken> token;
Vishnu Nair20cf5032018-01-05 13:15:49 -0800791 EXPECT_TRUE(
792 dss.setListener("whatever", listener, /* getSectionDetails = */ false, &token).isOk());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800793 ASSERT_THAT(token, NotNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700794 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
Vishnu Nair20cf5032018-01-05 13:15:49 -0800795 EXPECT_FALSE(Dumpstate::GetInstance().report_section_);
Felipe Leme75876a22016-10-27 16:31:27 -0700796
Felipe Leme009ecbb2016-11-07 10:18:44 -0800797 token.clear();
Vishnu Nair20cf5032018-01-05 13:15:49 -0800798 EXPECT_TRUE(
799 dss.setListener("whatsoever", listener, /* getSectionDetails = */ false, &token).isOk());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800800 ASSERT_THAT(token, IsNull());
801 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
Vishnu Nair20cf5032018-01-05 13:15:49 -0800802 EXPECT_FALSE(Dumpstate::GetInstance().report_section_);
803}
804
805TEST_F(DumpstateServiceTest, SetListenerWithSectionDetails) {
806 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
807 sp<IDumpstateToken> token;
808 Dumpstate::GetInstance().listener_ = nullptr;
809 EXPECT_TRUE(
810 dss.setListener("whatever", listener, /* getSectionDetails = */ true, &token).isOk());
811 ASSERT_THAT(token, NotNull());
812 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
813 EXPECT_TRUE(Dumpstate::GetInstance().report_section_);
Felipe Leme75876a22016-10-27 16:31:27 -0700814}
Felipe Leme7447d7c2016-11-03 18:12:22 -0700815
816class ProgressTest : public DumpstateBaseTest {
817 public:
818 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
819 return Progress(max, growth_factor, path);
820 }
821
822 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
823 std::string expected_content =
824 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
825 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800826 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700827 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
828 }
829};
830
831TEST_F(ProgressTest, SimpleTest) {
832 Progress progress;
833 EXPECT_EQ(0, progress.Get());
834 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
835 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
836
837 bool max_increased = progress.Inc(1);
838 EXPECT_EQ(1, progress.Get());
839 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
840 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
841 EXPECT_FALSE(max_increased);
842
843 // Ignore negative increase.
844 max_increased = progress.Inc(-1);
845 EXPECT_EQ(1, progress.Get());
846 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
847 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
848 EXPECT_FALSE(max_increased);
849}
850
851TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
852 Progress progress = GetInstance(10, 1.2); // 20% growth factor
853 EXPECT_EQ(0, progress.Get());
854 EXPECT_EQ(10, progress.GetInitialMax());
855 EXPECT_EQ(10, progress.GetMax());
856
857 // No increase
858 bool max_increased = progress.Inc(10);
859 EXPECT_EQ(10, progress.Get());
860 EXPECT_EQ(10, progress.GetMax());
861 EXPECT_FALSE(max_increased);
862
863 // Increase, with new value < max*20%
864 max_increased = progress.Inc(1);
865 EXPECT_EQ(11, progress.Get());
866 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
867 EXPECT_TRUE(max_increased);
868}
869
870TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
871 Progress progress = GetInstance(10, 1.2); // 20% growth factor
872 EXPECT_EQ(0, progress.Get());
873 EXPECT_EQ(10, progress.GetInitialMax());
874 EXPECT_EQ(10, progress.GetMax());
875
876 // No increase
877 bool max_increased = progress.Inc(10);
878 EXPECT_EQ(10, progress.Get());
879 EXPECT_EQ(10, progress.GetMax());
880 EXPECT_FALSE(max_increased);
881
882 // Increase, with new value > max*20%
883 max_increased = progress.Inc(5);
884 EXPECT_EQ(15, progress.Get());
885 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
886 EXPECT_TRUE(max_increased);
887}
888
889TEST_F(ProgressTest, InvalidPath) {
890 Progress progress("/devil/null");
891 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
892}
893
894TEST_F(ProgressTest, EmptyFile) {
895 Progress progress(CopyTextFileFixture("empty-file.txt"));
896 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
897}
898
899TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
900 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
901 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
902}
903
904TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
905 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
906 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
907}
908
909TEST_F(ProgressTest, InvalidLineBothNAN) {
910 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
911 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
912}
913
914TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
915 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
916 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
917}
918
919TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
920 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
921 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
922}
923
924TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
925 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
926 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
927}
928
929TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
930 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
931 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
932}
933
934// Tests stats are properly saved when the file does not exists.
935TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800936 if (!IsStandalone()) {
937 // TODO: temporarily disabled because it's failing when running as suite
938 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
939 return;
940 }
941
Felipe Leme7447d7c2016-11-03 18:12:22 -0700942 std::string path = kTestDataPath + "FirstTime.txt";
943 android::base::RemoveFileIfExists(path);
944
945 Progress run1(path);
946 EXPECT_EQ(0, run1.Get());
947 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
948 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
949
950 bool max_increased = run1.Inc(20);
951 EXPECT_EQ(20, run1.Get());
952 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
953 EXPECT_FALSE(max_increased);
954
955 run1.Save();
956 AssertStats(path, 1, 20);
957}
958
959// Tests what happens when the persistent settings contains the average duration of 1 run.
960// Data on file is 1 run and 109 average.
961TEST_F(ProgressTest, SecondTime) {
962 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
963
964 Progress run1 = GetInstance(-42, 1.2, path);
965 EXPECT_EQ(0, run1.Get());
966 EXPECT_EQ(10, run1.GetInitialMax());
967 EXPECT_EQ(10, run1.GetMax());
968
969 bool max_increased = run1.Inc(20);
970 EXPECT_EQ(20, run1.Get());
971 EXPECT_EQ(24, run1.GetMax());
972 EXPECT_TRUE(max_increased);
973
974 // Average now is 2 runs and (10 + 20)/ 2 = 15
975 run1.Save();
976 AssertStats(path, 2, 15);
977
978 Progress run2 = GetInstance(-42, 1.2, path);
979 EXPECT_EQ(0, run2.Get());
980 EXPECT_EQ(15, run2.GetInitialMax());
981 EXPECT_EQ(15, run2.GetMax());
982
983 max_increased = run2.Inc(25);
984 EXPECT_EQ(25, run2.Get());
985 EXPECT_EQ(30, run2.GetMax());
986 EXPECT_TRUE(max_increased);
987
988 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
989 run2.Save();
990 AssertStats(path, 3, 18);
991
992 Progress run3 = GetInstance(-42, 1.2, path);
993 EXPECT_EQ(0, run3.Get());
994 EXPECT_EQ(18, run3.GetInitialMax());
995 EXPECT_EQ(18, run3.GetMax());
996
997 // Make sure average decreases as well
998 max_increased = run3.Inc(5);
999 EXPECT_EQ(5, run3.Get());
1000 EXPECT_EQ(18, run3.GetMax());
1001 EXPECT_FALSE(max_increased);
1002
1003 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
1004 run3.Save();
1005 AssertStats(path, 4, 14);
1006}
1007
1008// Tests what happens when the persistent settings contains the average duration of 2 runs.
1009// Data on file is 2 runs and 15 average.
1010TEST_F(ProgressTest, ThirdTime) {
1011 std::string path = CopyTextFileFixture("stats-two-runs.txt");
1012 AssertStats(path, 2, 15); // Sanity check
1013
1014 Progress run1 = GetInstance(-42, 1.2, path);
1015 EXPECT_EQ(0, run1.Get());
1016 EXPECT_EQ(15, run1.GetInitialMax());
1017 EXPECT_EQ(15, run1.GetMax());
1018
1019 bool max_increased = run1.Inc(20);
1020 EXPECT_EQ(20, run1.Get());
1021 EXPECT_EQ(24, run1.GetMax());
1022 EXPECT_TRUE(max_increased);
1023
1024 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
1025 run1.Save();
1026 AssertStats(path, 3, 16);
1027}
1028
Felipe Leme46b85da2016-11-21 17:40:45 -08001029class DumpstateUtilTest : public DumpstateBaseTest {
1030 public:
1031 void SetUp() {
1032 DumpstateBaseTest::SetUp();
1033 SetDryRun(false);
1034 }
1035
Felipe Leme46b85da2016-11-21 17:40:45 -08001036 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -08001037 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -08001038 }
1039
1040 void CreateFd(const std::string& name) {
1041 path_ = kTestDataPath + name;
1042 MYLOGD("Creating fd for file %s\n", path_.c_str());
1043
1044 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
1045 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1046 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
1047 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
1048 }
1049
1050 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001051 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -08001052 const CommandOptions& options = CommandOptions::DEFAULT) {
1053 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001054 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -08001055 close(fd);
1056
1057 CaptureFdOut();
1058 err = GetCapturedStderr();
1059 return status;
1060 }
1061
1062 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001063 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001064 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001065 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -08001066 close(fd);
1067
1068 CaptureFdOut();
1069 err = GetCapturedStderr();
1070 return status;
1071 }
1072
Ecco Park61ffcf72016-10-27 15:46:26 -07001073 // Find out the pid of the process_name
1074 int FindPidOfProcess(const std::string& process_name) {
1075 CaptureStderr();
1076 int status = GetPidByName(process_name);
1077 err = GetCapturedStderr();
1078 return status;
1079 }
1080
Felipe Leme46b85da2016-11-21 17:40:45 -08001081 int fd;
1082
1083 // 'fd` output and `stderr` from the last command ran.
1084 std::string out, err;
1085
1086 private:
1087 std::string path_;
1088};
1089
1090TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -08001091 CreateFd("RunCommandNoArgs.txt");
1092 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001093}
1094
Felipe Lemef0292972016-11-22 13:57:05 -08001095TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001096 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001097 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001098 EXPECT_THAT(out, StrEq("stdout\n"));
1099 EXPECT_THAT(err, StrEq("stderr\n"));
1100}
1101
Felipe Lemef0292972016-11-22 13:57:05 -08001102TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
1103 CreateFd("RunCommandWithNoArgs.txt");
1104 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1105 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
1106 EXPECT_THAT(err, StrEq("stderr\n"));
1107}
1108
Felipe Leme46b85da2016-11-21 17:40:45 -08001109TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
1110 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001111 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001112 EXPECT_THAT(err, IsEmpty());
1113 EXPECT_THAT(out, StrEq("one\n"));
1114}
1115
1116TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
1117 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001118 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001119 EXPECT_THAT(err, IsEmpty());
1120 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
1121}
1122
1123TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
1124 CreateFd("RunCommandWithLoggingMessage.txt");
1125 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -08001126 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -08001127 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
1128 EXPECT_THAT(out, StrEq("stdout\n"));
1129 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
1130}
1131
1132TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
1133 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001134 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
1135 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001136 EXPECT_THAT(out, IsEmpty());
1137 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
1138}
1139
1140TEST_F(DumpstateUtilTest, RunCommandDryRun) {
1141 CreateFd("RunCommandDryRun.txt");
1142 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001143 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1144 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
1145 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
1146 kSimpleCommand.c_str())));
1147 EXPECT_THAT(err, IsEmpty());
1148}
1149
1150TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
1151 CreateFd("RunCommandDryRun.txt");
1152 SetDryRun(true);
1153 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001154 EXPECT_THAT(
1155 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
1156 EXPECT_THAT(err, IsEmpty());
1157}
1158
1159TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
1160 CreateFd("RunCommandDryRunAlways.txt");
1161 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001162 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001163 EXPECT_THAT(out, StrEq("stdout\n"));
1164 EXPECT_THAT(err, StrEq("stderr\n"));
1165}
1166
1167TEST_F(DumpstateUtilTest, RunCommandNotFound) {
1168 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001169 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001170 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
1171 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
1172}
1173
1174TEST_F(DumpstateUtilTest, RunCommandFails) {
1175 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001176 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001177 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
1178 " --exit 42' failed: exit code 42\n"));
1179 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
1180 " --exit 42' failed: exit code 42\n"));
1181}
1182
1183TEST_F(DumpstateUtilTest, RunCommandCrashes) {
1184 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001185 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001186 // We don't know the exit code, so check just the prefix.
1187 EXPECT_THAT(
1188 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1189 EXPECT_THAT(
1190 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1191}
1192
Vishnu Nair6921f802017-11-22 09:17:23 -08001193TEST_F(DumpstateUtilTest, RunCommandTimesoutWithSec) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001194 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001195 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1196 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001197 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1198 " --sleep 2' timed out after 1"));
1199 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1200 " --sleep 2' timed out after 1"));
1201}
1202
Vishnu Nair6921f802017-11-22 09:17:23 -08001203TEST_F(DumpstateUtilTest, RunCommandTimesoutWithMsec) {
1204 CreateFd("RunCommandTimesout.txt");
1205 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1206 CommandOptions::WithTimeoutInMs(1000).Build()));
1207 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1208 " --sleep 2' timed out after 1"));
1209 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1210 " --sleep 2' timed out after 1"));
1211}
1212
1213
Felipe Leme46b85da2016-11-21 17:40:45 -08001214TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
1215 CreateFd("RunCommandIsKilled.txt");
1216 CaptureStderr();
1217
1218 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -08001219 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001220 CommandOptions::WithTimeout(100).Always().Build()));
1221 });
1222
1223 // Capture pid and pre-sleep output.
1224 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
1225 std::string err = GetCapturedStderr();
1226 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
1227
1228 CaptureFdOut();
1229 std::vector<std::string> lines = android::base::Split(out, "\n");
1230 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
1231
1232 int pid = atoi(lines[0].c_str());
1233 EXPECT_THAT(lines[1], StrEq("stdout line1"));
1234 EXPECT_THAT(lines[2], IsEmpty()); // \n
1235
1236 // Then kill the process.
1237 CaptureFdOut();
1238 CaptureStderr();
1239 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1240 t.join();
1241
1242 // Finally, check output after murder.
1243 CaptureFdOut();
1244 err = GetCapturedStderr();
1245
1246 // out starts with the pid, which is an unknown
1247 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1248 " --pid --sleep 20' failed: killed by signal 15\n"));
1249 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1250 " --pid --sleep 20' failed: killed by signal 15\n"));
1251}
1252
1253TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1254 if (!IsStandalone()) {
1255 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1256 // to Shell - need to refactor tests to avoid this problem)
1257 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1258 return;
1259 }
1260 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001261 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001262 // Emulates user build if necessarily.
1263 SetBuildType("user");
1264 }
1265
1266 DropRoot();
1267
Felipe Lemef0292972016-11-22 13:57:05 -08001268 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001269
1270 // We don't know the exact path of su, so we just check for the 'root ...' commands
1271 EXPECT_THAT(out, StartsWith("Skipping"));
1272 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1273 EXPECT_THAT(err, IsEmpty());
1274}
1275
1276TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1277 if (!IsStandalone()) {
1278 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1279 // to Shell - need to refactor tests to avoid this problem)
1280 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1281 return;
1282 }
1283 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001284 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001285 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1286 return;
1287 }
1288
1289 DropRoot();
1290
Felipe Lemef0292972016-11-22 13:57:05 -08001291 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1292 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001293
1294 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1295 EXPECT_THAT(err, StrEq("stderr\n"));
1296}
Felipe Leme46b85da2016-11-21 17:40:45 -08001297
Yifan Hong48e83a12017-10-03 14:10:07 -07001298
1299TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnUserBuild) {
1300 if (!IsStandalone()) {
1301 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1302 // to Shell - need to refactor tests to avoid this problem)
1303 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
1304 return;
1305 }
1306 CreateFd("RunCommandAsRootIfAvailableOnUserBuild.txt");
1307 if (!PropertiesHelper::IsUserBuild()) {
1308 // Emulates user build if necessarily.
1309 SetBuildType("user");
1310 }
1311
1312 DropRoot();
1313
1314 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1315 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1316
1317 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1318 EXPECT_THAT(err, StrEq("stderr\n"));
1319}
1320
1321TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnDebugBuild) {
1322 if (!IsStandalone()) {
1323 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1324 // to Shell - need to refactor tests to avoid this problem)
1325 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
1326 return;
1327 }
1328 CreateFd("RunCommandAsRootIfAvailableOnDebugBuild.txt");
1329 if (PropertiesHelper::IsUserBuild()) {
1330 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1331 return;
1332 }
1333
1334 DropRoot();
1335
1336 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1337 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1338
1339 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1340 EXPECT_THAT(err, StrEq("stderr\n"));
1341}
1342
Felipe Leme46b85da2016-11-21 17:40:45 -08001343TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1344 if (!IsStandalone()) {
1345 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1346 // to Shell - need to refactor tests to avoid this problem)
1347 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1348 return;
1349 }
1350 CreateFd("RunCommandDropRoot.txt");
1351 // First check root case - only available when running with 'adb root'.
1352 uid_t uid = getuid();
1353 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001354 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001355 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1356 EXPECT_THAT(err, StrEq("stderr\n"));
1357 return;
1358 }
1359 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001360 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001361 CommandOptions::WithTimeout(1).DropRoot().Build()));
1362 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1363 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1364}
1365
Felipe Lemef0292972016-11-22 13:57:05 -08001366TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001367 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001368 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001369 EXPECT_THAT(out,
1370 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1371 EXPECT_THAT(err, IsEmpty());
1372}
1373
Felipe Lemef0292972016-11-22 13:57:05 -08001374TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1375 CreateFd("DumpFileNotFound.txt");
1376 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1377 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1378 "file or directory\n"));
1379 EXPECT_THAT(err, IsEmpty());
1380}
1381
Felipe Leme46b85da2016-11-21 17:40:45 -08001382TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1383 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001384 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001385 EXPECT_THAT(err, IsEmpty());
1386 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1387}
1388
1389TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1390 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001391 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001392 EXPECT_THAT(err, IsEmpty());
1393 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1394}
1395
1396TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1397 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001398 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001399 EXPECT_THAT(err, IsEmpty());
1400 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1401}
1402
1403TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1404 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001405 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001406 EXPECT_THAT(err, IsEmpty());
1407 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1408}
1409
Felipe Lemef0292972016-11-22 13:57:05 -08001410TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1411 CreateFd("DumpFileOnDryRun.txt");
1412 SetDryRun(true);
1413 std::string path = kTestDataPath + "single-line.txt";
1414 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1415 EXPECT_THAT(err, IsEmpty());
1416 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1417}
1418
Felipe Leme46b85da2016-11-21 17:40:45 -08001419TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1420 CreateFd("DumpFileOnDryRun.txt");
1421 SetDryRun(true);
1422 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001423 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001424 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001425 EXPECT_THAT(
1426 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1427 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001428}
Ecco Park61ffcf72016-10-27 15:46:26 -07001429
1430TEST_F(DumpstateUtilTest, FindingPidWithExistingProcess) {
1431 // init process always has pid 1.
1432 EXPECT_EQ(1, FindPidOfProcess("init"));
1433 EXPECT_THAT(err, IsEmpty());
1434}
1435
1436TEST_F(DumpstateUtilTest, FindingPidWithNotExistingProcess) {
1437 // find the process with abnormal name.
1438 EXPECT_EQ(-1, FindPidOfProcess("abcdef12345-543"));
1439 EXPECT_THAT(err, StrEq("can't find the pid\n"));
1440}
Felipe Leme47e9be22016-12-21 15:37:07 -08001441
1442} // namespace dumpstate
1443} // namespace os
1444} // namespace android