blob: e7999ac8dc06478e2b02e9541664573db0e88965 [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 Leme75876a22016-10-27 16:31:27 -070040using namespace android;
Felipe Lemed80e6b62016-10-03 13:08:14 -070041
Felipe Leme4c2d6632016-09-28 14:32:00 -070042using ::testing::EndsWith;
Felipe Leme46b85da2016-11-21 17:40:45 -080043using ::testing::HasSubstr;
Felipe Leme009ecbb2016-11-07 10:18:44 -080044using ::testing::IsNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070045using ::testing::IsEmpty;
Felipe Leme009ecbb2016-11-07 10:18:44 -080046using ::testing::NotNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070047using ::testing::StrEq;
48using ::testing::StartsWith;
49using ::testing::Test;
50using ::testing::internal::CaptureStderr;
51using ::testing::internal::CaptureStdout;
52using ::testing::internal::GetCapturedStderr;
53using ::testing::internal::GetCapturedStdout;
54
Felipe Leme75876a22016-10-27 16:31:27 -070055using os::DumpstateService;
56using os::IDumpstateListener;
Felipe Leme009ecbb2016-11-07 10:18:44 -080057using os::IDumpstateToken;
Felipe Leme75876a22016-10-27 16:31:27 -070058
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));
63
64 protected:
65 MOCK_METHOD0(onAsBinder, IBinder*());
66};
67
Felipe Leme46b85da2016-11-21 17:40:45 -080068static int calls_;
69
Felipe Leme7447d7c2016-11-03 18:12:22 -070070// Base class for all tests in this file
71class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080072 public:
73 virtual void SetUp() override {
74 calls_++;
Felipe Lemef0292972016-11-22 13:57:05 -080075 SetDryRun(false);
Felipe Leme46b85da2016-11-21 17:40:45 -080076 }
77
Felipe Lemef0292972016-11-22 13:57:05 -080078 void SetDryRun(bool dry_run) const {
79 PropertiesHelper::dry_run_ = dry_run;
80 }
81
82 void SetBuildType(const std::string& build_type) const {
83 PropertiesHelper::build_type_ = build_type;
84 }
85
86 bool IsStandalone() const {
Felipe Leme46b85da2016-11-21 17:40:45 -080087 return calls_ == 1;
88 }
89
Felipe Lemef0292972016-11-22 13:57:05 -080090 void DropRoot() const {
91 DropRootUser();
Felipe Leme46b85da2016-11-21 17:40:45 -080092 uid_t uid = getuid();
93 ASSERT_EQ(2000, (int)uid);
94 }
95
Felipe Leme7447d7c2016-11-03 18:12:22 -070096 protected:
97 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
98 const std::string kFixturesPath = kTestPath + "/../dumpstate_test_fixture/";
99 const std::string kTestDataPath = kFixturesPath + "/testdata/";
100 const std::string kSimpleCommand = kFixturesPath + "dumpstate_test_fixture";
101 const std::string kEchoCommand = "/system/bin/echo";
102
103 /*
104 * Copies a text file fixture to a temporary file, returning it's path.
105 *
106 * Useful in cases where the test case changes the content of the tile.
107 */
108 std::string CopyTextFileFixture(const std::string& relative_name) {
109 std::string from = kTestDataPath + relative_name;
110 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
111 // around for poking when the test fails.
112 std::string to = kTestDataPath + relative_name + ".tmp";
113 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
114 android::base::RemoveFileIfExists(to);
115 CopyTextFile(from, to);
116 return to.c_str();
117 }
118
Felipe Leme46b85da2016-11-21 17:40:45 -0800119 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700120 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800121 void ReadFileToString(const std::string& path, std::string* content) {
122 ASSERT_TRUE(android::base::ReadFileToString(path, content))
123 << "could not read contents from " << path;
124 }
125 void WriteStringToFile(const std::string& content, const std::string& path) {
126 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
127 << "could not write contents to " << path;
128 }
129
130 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700131 void CopyTextFile(const std::string& from, const std::string& to) {
132 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800133 ReadFileToString(from, &content);
134 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700135 }
136};
137
138class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700139 public:
140 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800141 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700142 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700143 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700144 ds.progress_.reset(new Progress());
Felipe Leme9a523ae2016-10-20 15:10:33 -0700145 ds.update_progress_ = false;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800146 ds.update_progress_threshold_ = 0;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700147 }
148
149 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700150 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700151 const CommandOptions& options = CommandOptions::DEFAULT) {
152 CaptureStdout();
153 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700154 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700155 out = GetCapturedStdout();
156 err = GetCapturedStderr();
157 return status;
158 }
159
Felipe Lemecef02982016-10-03 17:22:22 -0700160 // Dumps a file and capture `stdout` and `stderr`.
161 int DumpFile(const std::string& title, const std::string& path) {
162 CaptureStdout();
163 CaptureStderr();
164 int status = ds.DumpFile(title, path);
165 out = GetCapturedStdout();
166 err = GetCapturedStderr();
167 return status;
168 }
169
Felipe Leme009ecbb2016-11-07 10:18:44 -0800170 void SetProgress(long progress, long initial_max, long threshold = 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700171 ds.update_progress_ = true;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800172 ds.update_progress_threshold_ = threshold;
173 ds.last_updated_progress_ = 0;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700174 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
175 }
176
Felipe Leme7447d7c2016-11-03 18:12:22 -0700177 std::string GetProgressMessage(const std::string& listener_name, int progress, int max,
Felipe Leme009ecbb2016-11-07 10:18:44 -0800178 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700179 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
180 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700181
Felipe Leme7447d7c2016-11-03 18:12:22 -0700182 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700183
Felipe Leme009ecbb2016-11-07 10:18:44 -0800184 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700185 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800186 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700187 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700188 }
189
Felipe Leme009ecbb2016-11-07 10:18:44 -0800190 if (update_progress) {
191 message += android::base::StringPrintf("Setting progress (%s): %d/%d\n",
192 listener_name.c_str(), progress, max);
193 }
194
195 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700196 }
197
Felipe Leme4c2d6632016-09-28 14:32:00 -0700198 // `stdout` and `stderr` from the last command ran.
199 std::string out, err;
200
Felipe Lemefd8affa2016-09-30 17:38:57 -0700201 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700202};
203
204TEST_F(DumpstateTest, RunCommandNoArgs) {
205 EXPECT_EQ(-1, RunCommand("", {}));
206}
207
208TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700209 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700210 EXPECT_THAT(out, StrEq("stdout\n"));
211 EXPECT_THAT(err, StrEq("stderr\n"));
212}
213
214TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700215 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700216 EXPECT_THAT(err, StrEq("stderr\n"));
217 // We don't know the exact duration, so we check the prefix and suffix
Felipe Lemefd8affa2016-09-30 17:38:57 -0700218 EXPECT_THAT(out,
Felipe Leme7447d7c2016-11-03 18:12:22 -0700219 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n------"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700220 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
221}
222
Felipe Lemefd8affa2016-09-30 17:38:57 -0700223TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700224 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700225 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700226 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
227 EXPECT_THAT(out, StrEq("stdout\n"));
228 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
229}
230
231TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700232 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700233 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700234 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700235 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700236}
237
238TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700239 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700240 EXPECT_THAT(err, IsEmpty());
241 EXPECT_THAT(out, StrEq("one\n"));
242}
243
Felipe Lemefd8affa2016-09-30 17:38:57 -0700244TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700245 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700246 EXPECT_THAT(err, IsEmpty());
247 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
248}
249
250TEST_F(DumpstateTest, RunCommandDryRun) {
251 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700252 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700253 // We don't know the exact duration, so we check the prefix and suffix
Felipe Leme7447d7c2016-11-03 18:12:22 -0700254 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Felipe Leme4c2d6632016-09-28 14:32:00 -0700255 ") ------\n\t(skipped on dry run)\n------"));
256 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
257 EXPECT_THAT(err, IsEmpty());
258}
259
260TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
261 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700262 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700263 EXPECT_THAT(out, IsEmpty());
264 EXPECT_THAT(err, IsEmpty());
265}
266
267TEST_F(DumpstateTest, RunCommandDryRunAlways) {
268 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700269 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700270 EXPECT_THAT(out, StrEq("stdout\n"));
271 EXPECT_THAT(err, StrEq("stderr\n"));
272}
273
Felipe Lemefd8affa2016-09-30 17:38:57 -0700274TEST_F(DumpstateTest, RunCommandNotFound) {
275 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
276 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
277 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
278}
279
280TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700281 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
282 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700283 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700284 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700285 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700286}
287
288TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700289 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700290 // We don't know the exit code, so check just the prefix.
291 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700292 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700293 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700294 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700295}
296
297TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700298 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700299 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700300 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700301 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700302 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700303 " --sleep 2' timed out after 1"));
304}
305
306TEST_F(DumpstateTest, RunCommandIsKilled) {
307 CaptureStdout();
308 CaptureStderr();
309
310 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700311 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700312 CommandOptions::WithTimeout(100).Always().Build()));
313 });
314
315 // Capture pid and pre-sleep output.
316 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
317 std::string err = GetCapturedStderr();
318 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
319
320 std::string out = GetCapturedStdout();
321 std::vector<std::string> lines = android::base::Split(out, "\n");
322 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
323
324 int pid = atoi(lines[0].c_str());
325 EXPECT_THAT(lines[1], StrEq("stdout line1"));
326 EXPECT_THAT(lines[2], IsEmpty()); // \n
327
328 // Then kill the process.
329 CaptureStdout();
330 CaptureStderr();
331 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
332 t.join();
333
334 // Finally, check output after murder.
335 out = GetCapturedStdout();
336 err = GetCapturedStderr();
337
Felipe Leme7447d7c2016-11-03 18:12:22 -0700338 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700339 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700340 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700341 " --pid --sleep 20' failed: killed by signal 15\n"));
342}
343
Felipe Leme75876a22016-10-27 16:31:27 -0700344TEST_F(DumpstateTest, RunCommandProgress) {
345 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
346 ds.listener_ = listener;
347 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700348 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700349
350 EXPECT_CALL(*listener, onProgressUpdated(20));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700351 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700352 std::string progress_message = GetProgressMessage(ds.listener_name_, 20, 30);
353 EXPECT_THAT(out, StrEq("stdout\n"));
354 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
355
356 EXPECT_CALL(*listener, onProgressUpdated(30));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700357 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700358 progress_message = GetProgressMessage(ds.listener_name_, 30, 30);
359 EXPECT_THAT(out, StrEq("stdout\n"));
360 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
361
362 // Run a command that will increase maximum timeout.
363 EXPECT_CALL(*listener, onProgressUpdated(31));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700364 EXPECT_CALL(*listener, onMaxProgressUpdated(37));
365 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
366 progress_message = GetProgressMessage(ds.listener_name_, 31, 37, 30); // 20% increase
Felipe Leme75876a22016-10-27 16:31:27 -0700367 EXPECT_THAT(out, StrEq("stdout\n"));
368 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
369
370 // Make sure command ran while in dry_run is counted.
371 SetDryRun(true);
372 EXPECT_CALL(*listener, onProgressUpdated(35));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700373 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
374 progress_message = GetProgressMessage(ds.listener_name_, 35, 37);
Felipe Leme75876a22016-10-27 16:31:27 -0700375 EXPECT_THAT(out, IsEmpty());
376 EXPECT_THAT(err, StrEq(progress_message));
377
378 ds.listener_.clear();
379}
380
Felipe Leme009ecbb2016-11-07 10:18:44 -0800381TEST_F(DumpstateTest, RunCommandProgressIgnoreThreshold) {
382 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
383 ds.listener_ = listener;
384 ds.listener_name_ = "FoxMulder";
385 SetProgress(0, 8, 5); // 8 max, 5 threshold
386
387 // First update should always be sent.
388 EXPECT_CALL(*listener, onProgressUpdated(1));
389 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
390 std::string progress_message = GetProgressMessage(ds.listener_name_, 1, 8);
391 EXPECT_THAT(out, StrEq("stdout\n"));
392 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
393
394 // Fourth update should be ignored because it's between the threshold (5 -1 = 4 < 5).
395 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
396 EXPECT_THAT(out, StrEq("stdout\n"));
397 EXPECT_THAT(err, StrEq("stderr\n"));
398
399 // Third update should be sent because it reaches threshold (6 - 1 = 5).
400 EXPECT_CALL(*listener, onProgressUpdated(6));
401 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
402 progress_message = GetProgressMessage(ds.listener_name_, 6, 8);
403 EXPECT_THAT(out, StrEq("stdout\n"));
404 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
405
406 // Fourth update should be ignored because it's between the threshold (9 - 6 = 3 < 5).
407 // But max update should be sent.
408 EXPECT_CALL(*listener, onMaxProgressUpdated(10)); // 9 * 120% = 10.8 = 10
409 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
410 progress_message = GetProgressMessage(ds.listener_name_, 9, 10, 8, false);
411 EXPECT_THAT(out, StrEq("stdout\n"));
412 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
413
414 ds.listener_.clear();
415}
416
Felipe Lemed80e6b62016-10-03 13:08:14 -0700417TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800418 if (!IsStandalone()) {
419 // TODO: temporarily disabled because it might cause other tests to fail after dropping
420 // to Shell - need to refactor tests to avoid this problem)
421 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
422 return;
423 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700424 // First check root case - only available when running with 'adb root'.
425 uid_t uid = getuid();
426 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700427 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700428 EXPECT_THAT(out, StrEq("0\nstdout\n"));
429 EXPECT_THAT(err, StrEq("stderr\n"));
430 return;
431 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700432 // Then run dropping root.
433 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700434 CommandOptions::WithTimeout(1).DropRoot().Build()));
435 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700436 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700437}
438
439TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800440 if (!IsStandalone()) {
441 // TODO: temporarily disabled because it might cause other tests to fail after dropping
442 // to Shell - need to refactor tests to avoid this problem)
443 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
444 return;
445 }
Felipe Lemef0292972016-11-22 13:57:05 -0800446 if (!PropertiesHelper::IsUserBuild()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700447 // Emulates user build if necessarily.
448 SetBuildType("user");
449 }
450
451 DropRoot();
452
Felipe Leme7447d7c2016-11-03 18:12:22 -0700453 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700454
455 // We don't know the exact path of su, so we just check for the 'root ...' commands
456 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700457 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700458 EXPECT_THAT(err, IsEmpty());
459}
460
Felipe Leme46b85da2016-11-21 17:40:45 -0800461TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
462 if (!IsStandalone()) {
463 // TODO: temporarily disabled because it might cause other tests to fail after dropping
464 // to Shell - need to refactor tests to avoid this problem)
465 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
466 return;
467 }
Felipe Lemef0292972016-11-22 13:57:05 -0800468 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800469 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
470 return;
471 }
472
473 DropRoot();
474
475 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
476 CommandOptions::WithTimeout(1).AsRoot().Build()));
477
478 EXPECT_THAT(out, StrEq("0\nstdout\n"));
479 EXPECT_THAT(err, StrEq("stderr\n"));
480}
481
Felipe Lemecef02982016-10-03 17:22:22 -0700482TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
483 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
484 EXPECT_THAT(out,
485 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
486 EXPECT_THAT(err, IsEmpty());
487}
488
489TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
490 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
491 EXPECT_THAT(err, IsEmpty());
492 // We don't know the exact duration, so we check the prefix and suffix
493 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
494 "such file or directory\n"));
495 EXPECT_THAT(out, EndsWith("s was the duration of 'Y U NO EXIST?' ------\n"));
496}
497
498TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700499 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700500 EXPECT_THAT(err, IsEmpty());
501 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
502}
503
504TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700505 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700506 EXPECT_THAT(err, IsEmpty());
507 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
508}
509
510TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700511 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700512 EXPECT_THAT(err, IsEmpty());
513 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
514}
515
516TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700517 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700518 EXPECT_THAT(err, IsEmpty());
519 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
520}
521
522TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
523 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700524 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700525 EXPECT_THAT(err, IsEmpty());
526 EXPECT_THAT(out, IsEmpty());
527}
528
529TEST_F(DumpstateTest, DumpFileOnDryRun) {
530 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700531 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700532 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -0800533 EXPECT_THAT(
534 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
535 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n------"));
Felipe Lemecef02982016-10-03 17:22:22 -0700536 EXPECT_THAT(out, EndsWith("s was the duration of 'Might as well dump. Dump!' ------\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700537}
538
Felipe Leme75876a22016-10-27 16:31:27 -0700539TEST_F(DumpstateTest, DumpFileUpdateProgress) {
540 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
541 ds.listener_ = listener;
542 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700543 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700544
545 EXPECT_CALL(*listener, onProgressUpdated(5));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700546 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -0700547
548 std::string progress_message =
549 GetProgressMessage(ds.listener_name_, 5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
550 EXPECT_THAT(err, StrEq(progress_message));
551 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
552
553 ds.listener_.clear();
554}
555
Felipe Leme7447d7c2016-11-03 18:12:22 -0700556class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -0700557 public:
558 DumpstateService dss;
559};
560
561TEST_F(DumpstateServiceTest, SetListenerNoName) {
562 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800563 sp<IDumpstateToken> token;
564 EXPECT_TRUE(dss.setListener("", listener, &token).isOk());
565 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700566}
567
568TEST_F(DumpstateServiceTest, SetListenerNoPointer) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800569 sp<IDumpstateToken> token;
570 EXPECT_TRUE(dss.setListener("whatever", nullptr, &token).isOk());
571 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700572}
573
574TEST_F(DumpstateServiceTest, SetListenerTwice) {
575 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800576 sp<IDumpstateToken> token;
577 EXPECT_TRUE(dss.setListener("whatever", listener, &token).isOk());
578 ASSERT_THAT(token, NotNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700579 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
580
Felipe Leme009ecbb2016-11-07 10:18:44 -0800581 token.clear();
582 EXPECT_TRUE(dss.setListener("whatsoever", listener, &token).isOk());
583 ASSERT_THAT(token, IsNull());
584 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
Felipe Leme75876a22016-10-27 16:31:27 -0700585}
Felipe Leme7447d7c2016-11-03 18:12:22 -0700586
587class ProgressTest : public DumpstateBaseTest {
588 public:
589 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
590 return Progress(max, growth_factor, path);
591 }
592
593 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
594 std::string expected_content =
595 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
596 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800597 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700598 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
599 }
600};
601
602TEST_F(ProgressTest, SimpleTest) {
603 Progress progress;
604 EXPECT_EQ(0, progress.Get());
605 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
606 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
607
608 bool max_increased = progress.Inc(1);
609 EXPECT_EQ(1, progress.Get());
610 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
611 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
612 EXPECT_FALSE(max_increased);
613
614 // Ignore negative increase.
615 max_increased = progress.Inc(-1);
616 EXPECT_EQ(1, progress.Get());
617 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
618 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
619 EXPECT_FALSE(max_increased);
620}
621
622TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
623 Progress progress = GetInstance(10, 1.2); // 20% growth factor
624 EXPECT_EQ(0, progress.Get());
625 EXPECT_EQ(10, progress.GetInitialMax());
626 EXPECT_EQ(10, progress.GetMax());
627
628 // No increase
629 bool max_increased = progress.Inc(10);
630 EXPECT_EQ(10, progress.Get());
631 EXPECT_EQ(10, progress.GetMax());
632 EXPECT_FALSE(max_increased);
633
634 // Increase, with new value < max*20%
635 max_increased = progress.Inc(1);
636 EXPECT_EQ(11, progress.Get());
637 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
638 EXPECT_TRUE(max_increased);
639}
640
641TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
642 Progress progress = GetInstance(10, 1.2); // 20% growth factor
643 EXPECT_EQ(0, progress.Get());
644 EXPECT_EQ(10, progress.GetInitialMax());
645 EXPECT_EQ(10, progress.GetMax());
646
647 // No increase
648 bool max_increased = progress.Inc(10);
649 EXPECT_EQ(10, progress.Get());
650 EXPECT_EQ(10, progress.GetMax());
651 EXPECT_FALSE(max_increased);
652
653 // Increase, with new value > max*20%
654 max_increased = progress.Inc(5);
655 EXPECT_EQ(15, progress.Get());
656 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
657 EXPECT_TRUE(max_increased);
658}
659
660TEST_F(ProgressTest, InvalidPath) {
661 Progress progress("/devil/null");
662 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
663}
664
665TEST_F(ProgressTest, EmptyFile) {
666 Progress progress(CopyTextFileFixture("empty-file.txt"));
667 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
668}
669
670TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
671 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
672 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
673}
674
675TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
676 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
677 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
678}
679
680TEST_F(ProgressTest, InvalidLineBothNAN) {
681 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
682 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
683}
684
685TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
686 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
687 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
688}
689
690TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
691 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
692 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
693}
694
695TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
696 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
697 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
698}
699
700TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
701 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
702 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
703}
704
705// Tests stats are properly saved when the file does not exists.
706TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800707 if (!IsStandalone()) {
708 // TODO: temporarily disabled because it's failing when running as suite
709 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
710 return;
711 }
712
Felipe Leme7447d7c2016-11-03 18:12:22 -0700713 std::string path = kTestDataPath + "FirstTime.txt";
714 android::base::RemoveFileIfExists(path);
715
716 Progress run1(path);
717 EXPECT_EQ(0, run1.Get());
718 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
719 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
720
721 bool max_increased = run1.Inc(20);
722 EXPECT_EQ(20, run1.Get());
723 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
724 EXPECT_FALSE(max_increased);
725
726 run1.Save();
727 AssertStats(path, 1, 20);
728}
729
730// Tests what happens when the persistent settings contains the average duration of 1 run.
731// Data on file is 1 run and 109 average.
732TEST_F(ProgressTest, SecondTime) {
733 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
734
735 Progress run1 = GetInstance(-42, 1.2, path);
736 EXPECT_EQ(0, run1.Get());
737 EXPECT_EQ(10, run1.GetInitialMax());
738 EXPECT_EQ(10, run1.GetMax());
739
740 bool max_increased = run1.Inc(20);
741 EXPECT_EQ(20, run1.Get());
742 EXPECT_EQ(24, run1.GetMax());
743 EXPECT_TRUE(max_increased);
744
745 // Average now is 2 runs and (10 + 20)/ 2 = 15
746 run1.Save();
747 AssertStats(path, 2, 15);
748
749 Progress run2 = GetInstance(-42, 1.2, path);
750 EXPECT_EQ(0, run2.Get());
751 EXPECT_EQ(15, run2.GetInitialMax());
752 EXPECT_EQ(15, run2.GetMax());
753
754 max_increased = run2.Inc(25);
755 EXPECT_EQ(25, run2.Get());
756 EXPECT_EQ(30, run2.GetMax());
757 EXPECT_TRUE(max_increased);
758
759 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
760 run2.Save();
761 AssertStats(path, 3, 18);
762
763 Progress run3 = GetInstance(-42, 1.2, path);
764 EXPECT_EQ(0, run3.Get());
765 EXPECT_EQ(18, run3.GetInitialMax());
766 EXPECT_EQ(18, run3.GetMax());
767
768 // Make sure average decreases as well
769 max_increased = run3.Inc(5);
770 EXPECT_EQ(5, run3.Get());
771 EXPECT_EQ(18, run3.GetMax());
772 EXPECT_FALSE(max_increased);
773
774 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
775 run3.Save();
776 AssertStats(path, 4, 14);
777}
778
779// Tests what happens when the persistent settings contains the average duration of 2 runs.
780// Data on file is 2 runs and 15 average.
781TEST_F(ProgressTest, ThirdTime) {
782 std::string path = CopyTextFileFixture("stats-two-runs.txt");
783 AssertStats(path, 2, 15); // Sanity check
784
785 Progress run1 = GetInstance(-42, 1.2, path);
786 EXPECT_EQ(0, run1.Get());
787 EXPECT_EQ(15, run1.GetInitialMax());
788 EXPECT_EQ(15, run1.GetMax());
789
790 bool max_increased = run1.Inc(20);
791 EXPECT_EQ(20, run1.Get());
792 EXPECT_EQ(24, run1.GetMax());
793 EXPECT_TRUE(max_increased);
794
795 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
796 run1.Save();
797 AssertStats(path, 3, 16);
798}
799
Felipe Leme46b85da2016-11-21 17:40:45 -0800800class DumpstateUtilTest : public DumpstateBaseTest {
801 public:
802 void SetUp() {
803 DumpstateBaseTest::SetUp();
804 SetDryRun(false);
805 }
806
Felipe Leme46b85da2016-11-21 17:40:45 -0800807 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -0800808 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -0800809 }
810
811 void CreateFd(const std::string& name) {
812 path_ = kTestDataPath + name;
813 MYLOGD("Creating fd for file %s\n", path_.c_str());
814
815 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
816 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
817 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
818 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
819 }
820
821 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -0800822 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -0800823 const CommandOptions& options = CommandOptions::DEFAULT) {
824 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -0800825 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800826 close(fd);
827
828 CaptureFdOut();
829 err = GetCapturedStderr();
830 return status;
831 }
832
833 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -0800834 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800835 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -0800836 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800837 close(fd);
838
839 CaptureFdOut();
840 err = GetCapturedStderr();
841 return status;
842 }
843
Ecco Park61ffcf72016-10-27 15:46:26 -0700844 // Find out the pid of the process_name
845 int FindPidOfProcess(const std::string& process_name) {
846 CaptureStderr();
847 int status = GetPidByName(process_name);
848 err = GetCapturedStderr();
849 return status;
850 }
851
Felipe Leme46b85da2016-11-21 17:40:45 -0800852 int fd;
853
854 // 'fd` output and `stderr` from the last command ran.
855 std::string out, err;
856
857 private:
858 std::string path_;
859};
860
861TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -0800862 CreateFd("RunCommandNoArgs.txt");
863 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800864}
865
Felipe Lemef0292972016-11-22 13:57:05 -0800866TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800867 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800868 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800869 EXPECT_THAT(out, StrEq("stdout\n"));
870 EXPECT_THAT(err, StrEq("stderr\n"));
871}
872
Felipe Lemef0292972016-11-22 13:57:05 -0800873TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
874 CreateFd("RunCommandWithNoArgs.txt");
875 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
876 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
877 EXPECT_THAT(err, StrEq("stderr\n"));
878}
879
Felipe Leme46b85da2016-11-21 17:40:45 -0800880TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
881 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800882 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800883 EXPECT_THAT(err, IsEmpty());
884 EXPECT_THAT(out, StrEq("one\n"));
885}
886
887TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
888 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800889 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800890 EXPECT_THAT(err, IsEmpty());
891 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
892}
893
894TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
895 CreateFd("RunCommandWithLoggingMessage.txt");
896 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -0800897 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -0800898 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
899 EXPECT_THAT(out, StrEq("stdout\n"));
900 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
901}
902
903TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
904 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800905 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
906 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -0800907 EXPECT_THAT(out, IsEmpty());
908 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
909}
910
911TEST_F(DumpstateUtilTest, RunCommandDryRun) {
912 CreateFd("RunCommandDryRun.txt");
913 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -0800914 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
915 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
916 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
917 kSimpleCommand.c_str())));
918 EXPECT_THAT(err, IsEmpty());
919}
920
921TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
922 CreateFd("RunCommandDryRun.txt");
923 SetDryRun(true);
924 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800925 EXPECT_THAT(
926 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
927 EXPECT_THAT(err, IsEmpty());
928}
929
930TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
931 CreateFd("RunCommandDryRunAlways.txt");
932 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -0800933 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -0800934 EXPECT_THAT(out, StrEq("stdout\n"));
935 EXPECT_THAT(err, StrEq("stderr\n"));
936}
937
938TEST_F(DumpstateUtilTest, RunCommandNotFound) {
939 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800940 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800941 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
942 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
943}
944
945TEST_F(DumpstateUtilTest, RunCommandFails) {
946 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800947 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800948 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
949 " --exit 42' failed: exit code 42\n"));
950 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
951 " --exit 42' failed: exit code 42\n"));
952}
953
954TEST_F(DumpstateUtilTest, RunCommandCrashes) {
955 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800956 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800957 // We don't know the exit code, so check just the prefix.
958 EXPECT_THAT(
959 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
960 EXPECT_THAT(
961 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
962}
963
964TEST_F(DumpstateUtilTest, RunCommandTimesout) {
965 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800966 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
967 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -0800968 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
969 " --sleep 2' timed out after 1"));
970 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
971 " --sleep 2' timed out after 1"));
972}
973
974TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
975 CreateFd("RunCommandIsKilled.txt");
976 CaptureStderr();
977
978 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -0800979 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -0800980 CommandOptions::WithTimeout(100).Always().Build()));
981 });
982
983 // Capture pid and pre-sleep output.
984 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
985 std::string err = GetCapturedStderr();
986 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
987
988 CaptureFdOut();
989 std::vector<std::string> lines = android::base::Split(out, "\n");
990 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
991
992 int pid = atoi(lines[0].c_str());
993 EXPECT_THAT(lines[1], StrEq("stdout line1"));
994 EXPECT_THAT(lines[2], IsEmpty()); // \n
995
996 // Then kill the process.
997 CaptureFdOut();
998 CaptureStderr();
999 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1000 t.join();
1001
1002 // Finally, check output after murder.
1003 CaptureFdOut();
1004 err = GetCapturedStderr();
1005
1006 // out starts with the pid, which is an unknown
1007 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1008 " --pid --sleep 20' failed: killed by signal 15\n"));
1009 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1010 " --pid --sleep 20' failed: killed by signal 15\n"));
1011}
1012
1013TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1014 if (!IsStandalone()) {
1015 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1016 // to Shell - need to refactor tests to avoid this problem)
1017 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1018 return;
1019 }
1020 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001021 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001022 // Emulates user build if necessarily.
1023 SetBuildType("user");
1024 }
1025
1026 DropRoot();
1027
Felipe Lemef0292972016-11-22 13:57:05 -08001028 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001029
1030 // We don't know the exact path of su, so we just check for the 'root ...' commands
1031 EXPECT_THAT(out, StartsWith("Skipping"));
1032 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1033 EXPECT_THAT(err, IsEmpty());
1034}
1035
1036TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1037 if (!IsStandalone()) {
1038 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1039 // to Shell - need to refactor tests to avoid this problem)
1040 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1041 return;
1042 }
1043 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001044 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001045 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1046 return;
1047 }
1048
1049 DropRoot();
1050
Felipe Lemef0292972016-11-22 13:57:05 -08001051 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1052 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001053
1054 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1055 EXPECT_THAT(err, StrEq("stderr\n"));
1056}
Felipe Leme46b85da2016-11-21 17:40:45 -08001057
1058TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1059 if (!IsStandalone()) {
1060 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1061 // to Shell - need to refactor tests to avoid this problem)
1062 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1063 return;
1064 }
1065 CreateFd("RunCommandDropRoot.txt");
1066 // First check root case - only available when running with 'adb root'.
1067 uid_t uid = getuid();
1068 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001069 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001070 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1071 EXPECT_THAT(err, StrEq("stderr\n"));
1072 return;
1073 }
1074 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001075 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001076 CommandOptions::WithTimeout(1).DropRoot().Build()));
1077 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1078 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1079}
1080
Felipe Lemef0292972016-11-22 13:57:05 -08001081TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001082 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001083 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001084 EXPECT_THAT(out,
1085 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1086 EXPECT_THAT(err, IsEmpty());
1087}
1088
Felipe Lemef0292972016-11-22 13:57:05 -08001089TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1090 CreateFd("DumpFileNotFound.txt");
1091 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1092 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1093 "file or directory\n"));
1094 EXPECT_THAT(err, IsEmpty());
1095}
1096
Felipe Leme46b85da2016-11-21 17:40:45 -08001097TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1098 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001099 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001100 EXPECT_THAT(err, IsEmpty());
1101 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1102}
1103
1104TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1105 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001106 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001107 EXPECT_THAT(err, IsEmpty());
1108 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1109}
1110
1111TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1112 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001113 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001114 EXPECT_THAT(err, IsEmpty());
1115 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1116}
1117
1118TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1119 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001120 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001121 EXPECT_THAT(err, IsEmpty());
1122 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1123}
1124
Felipe Lemef0292972016-11-22 13:57:05 -08001125TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1126 CreateFd("DumpFileOnDryRun.txt");
1127 SetDryRun(true);
1128 std::string path = kTestDataPath + "single-line.txt";
1129 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1130 EXPECT_THAT(err, IsEmpty());
1131 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1132}
1133
Felipe Leme46b85da2016-11-21 17:40:45 -08001134TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1135 CreateFd("DumpFileOnDryRun.txt");
1136 SetDryRun(true);
1137 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001138 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001139 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001140 EXPECT_THAT(
1141 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1142 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001143}
Ecco Park61ffcf72016-10-27 15:46:26 -07001144
1145TEST_F(DumpstateUtilTest, FindingPidWithExistingProcess) {
1146 // init process always has pid 1.
1147 EXPECT_EQ(1, FindPidOfProcess("init"));
1148 EXPECT_THAT(err, IsEmpty());
1149}
1150
1151TEST_F(DumpstateUtilTest, FindingPidWithNotExistingProcess) {
1152 // find the process with abnormal name.
1153 EXPECT_EQ(-1, FindPidOfProcess("abcdef12345-543"));
1154 EXPECT_THAT(err, StrEq("can't find the pid\n"));
1155}