blob: 2e35112dfb4e11bc7eefce2bf4e8fb576e2499bd [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 Leme4c2d6632016-09-28 14:32:00 -070059// Not used on test cases yet...
60void dumpstate_board(void) {
61}
62
Felipe Leme75876a22016-10-27 16:31:27 -070063class DumpstateListenerMock : public IDumpstateListener {
64 public:
65 MOCK_METHOD1(onProgressUpdated, binder::Status(int32_t progress));
66 MOCK_METHOD1(onMaxProgressUpdated, binder::Status(int32_t max_progress));
67
68 protected:
69 MOCK_METHOD0(onAsBinder, IBinder*());
70};
71
Felipe Leme46b85da2016-11-21 17:40:45 -080072static int calls_;
73
Felipe Leme7447d7c2016-11-03 18:12:22 -070074// Base class for all tests in this file
75class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080076 public:
77 virtual void SetUp() override {
78 calls_++;
Felipe Lemef0292972016-11-22 13:57:05 -080079 SetDryRun(false);
Felipe Leme46b85da2016-11-21 17:40:45 -080080 }
81
Felipe Lemef0292972016-11-22 13:57:05 -080082 void SetDryRun(bool dry_run) const {
83 PropertiesHelper::dry_run_ = dry_run;
84 }
85
86 void SetBuildType(const std::string& build_type) const {
87 PropertiesHelper::build_type_ = build_type;
88 }
89
90 bool IsStandalone() const {
Felipe Leme46b85da2016-11-21 17:40:45 -080091 return calls_ == 1;
92 }
93
Felipe Lemef0292972016-11-22 13:57:05 -080094 void DropRoot() const {
95 DropRootUser();
Felipe Leme46b85da2016-11-21 17:40:45 -080096 uid_t uid = getuid();
97 ASSERT_EQ(2000, (int)uid);
98 }
99
Felipe Leme7447d7c2016-11-03 18:12:22 -0700100 protected:
101 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
102 const std::string kFixturesPath = kTestPath + "/../dumpstate_test_fixture/";
103 const std::string kTestDataPath = kFixturesPath + "/testdata/";
104 const std::string kSimpleCommand = kFixturesPath + "dumpstate_test_fixture";
105 const std::string kEchoCommand = "/system/bin/echo";
106
107 /*
108 * Copies a text file fixture to a temporary file, returning it's path.
109 *
110 * Useful in cases where the test case changes the content of the tile.
111 */
112 std::string CopyTextFileFixture(const std::string& relative_name) {
113 std::string from = kTestDataPath + relative_name;
114 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
115 // around for poking when the test fails.
116 std::string to = kTestDataPath + relative_name + ".tmp";
117 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
118 android::base::RemoveFileIfExists(to);
119 CopyTextFile(from, to);
120 return to.c_str();
121 }
122
Felipe Leme46b85da2016-11-21 17:40:45 -0800123 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700124 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800125 void ReadFileToString(const std::string& path, std::string* content) {
126 ASSERT_TRUE(android::base::ReadFileToString(path, content))
127 << "could not read contents from " << path;
128 }
129 void WriteStringToFile(const std::string& content, const std::string& path) {
130 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
131 << "could not write contents to " << path;
132 }
133
134 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700135 void CopyTextFile(const std::string& from, const std::string& to) {
136 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800137 ReadFileToString(from, &content);
138 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700139 }
140};
141
142class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700143 public:
144 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800145 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700146 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700147 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700148 ds.progress_.reset(new Progress());
Felipe Leme9a523ae2016-10-20 15:10:33 -0700149 ds.update_progress_ = false;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800150 ds.update_progress_threshold_ = 0;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700151 }
152
153 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700154 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700155 const CommandOptions& options = CommandOptions::DEFAULT) {
156 CaptureStdout();
157 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700158 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700159 out = GetCapturedStdout();
160 err = GetCapturedStderr();
161 return status;
162 }
163
Felipe Lemecef02982016-10-03 17:22:22 -0700164 // Dumps a file and capture `stdout` and `stderr`.
165 int DumpFile(const std::string& title, const std::string& path) {
166 CaptureStdout();
167 CaptureStderr();
168 int status = ds.DumpFile(title, path);
169 out = GetCapturedStdout();
170 err = GetCapturedStderr();
171 return status;
172 }
173
Felipe Leme009ecbb2016-11-07 10:18:44 -0800174 void SetProgress(long progress, long initial_max, long threshold = 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700175 ds.update_progress_ = true;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800176 ds.update_progress_threshold_ = threshold;
177 ds.last_updated_progress_ = 0;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700178 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
179 }
180
Felipe Leme7447d7c2016-11-03 18:12:22 -0700181 std::string GetProgressMessage(const std::string& listener_name, int progress, int max,
Felipe Leme009ecbb2016-11-07 10:18:44 -0800182 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700183 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
184 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700185
Felipe Leme7447d7c2016-11-03 18:12:22 -0700186 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700187
Felipe Leme009ecbb2016-11-07 10:18:44 -0800188 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700189 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800190 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700191 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700192 }
193
Felipe Leme009ecbb2016-11-07 10:18:44 -0800194 if (update_progress) {
195 message += android::base::StringPrintf("Setting progress (%s): %d/%d\n",
196 listener_name.c_str(), progress, max);
197 }
198
199 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700200 }
201
Felipe Leme4c2d6632016-09-28 14:32:00 -0700202 // `stdout` and `stderr` from the last command ran.
203 std::string out, err;
204
Felipe Lemefd8affa2016-09-30 17:38:57 -0700205 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700206};
207
208TEST_F(DumpstateTest, RunCommandNoArgs) {
209 EXPECT_EQ(-1, RunCommand("", {}));
210}
211
212TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700213 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700214 EXPECT_THAT(out, StrEq("stdout\n"));
215 EXPECT_THAT(err, StrEq("stderr\n"));
216}
217
218TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700219 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700220 EXPECT_THAT(err, StrEq("stderr\n"));
221 // We don't know the exact duration, so we check the prefix and suffix
Felipe Lemefd8affa2016-09-30 17:38:57 -0700222 EXPECT_THAT(out,
Felipe Leme7447d7c2016-11-03 18:12:22 -0700223 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n------"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700224 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
225}
226
Felipe Lemefd8affa2016-09-30 17:38:57 -0700227TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700228 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700229 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700230 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
231 EXPECT_THAT(out, StrEq("stdout\n"));
232 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
233}
234
235TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700236 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700237 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700238 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700239 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700240}
241
242TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700243 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700244 EXPECT_THAT(err, IsEmpty());
245 EXPECT_THAT(out, StrEq("one\n"));
246}
247
Felipe Lemefd8affa2016-09-30 17:38:57 -0700248TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700249 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700250 EXPECT_THAT(err, IsEmpty());
251 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
252}
253
254TEST_F(DumpstateTest, RunCommandDryRun) {
255 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700256 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700257 // We don't know the exact duration, so we check the prefix and suffix
Felipe Leme7447d7c2016-11-03 18:12:22 -0700258 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Felipe Leme4c2d6632016-09-28 14:32:00 -0700259 ") ------\n\t(skipped on dry run)\n------"));
260 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
261 EXPECT_THAT(err, IsEmpty());
262}
263
264TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
265 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700266 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700267 EXPECT_THAT(out, IsEmpty());
268 EXPECT_THAT(err, IsEmpty());
269}
270
271TEST_F(DumpstateTest, RunCommandDryRunAlways) {
272 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700273 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700274 EXPECT_THAT(out, StrEq("stdout\n"));
275 EXPECT_THAT(err, StrEq("stderr\n"));
276}
277
Felipe Lemefd8affa2016-09-30 17:38:57 -0700278TEST_F(DumpstateTest, RunCommandNotFound) {
279 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
280 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
281 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
282}
283
284TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700285 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
286 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700287 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700288 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700289 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700290}
291
292TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700293 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700294 // We don't know the exit code, so check just the prefix.
295 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700296 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700297 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700298 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700299}
300
301TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700302 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700303 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700304 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700305 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700306 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700307 " --sleep 2' timed out after 1"));
308}
309
310TEST_F(DumpstateTest, RunCommandIsKilled) {
311 CaptureStdout();
312 CaptureStderr();
313
314 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700315 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700316 CommandOptions::WithTimeout(100).Always().Build()));
317 });
318
319 // Capture pid and pre-sleep output.
320 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
321 std::string err = GetCapturedStderr();
322 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
323
324 std::string out = GetCapturedStdout();
325 std::vector<std::string> lines = android::base::Split(out, "\n");
326 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
327
328 int pid = atoi(lines[0].c_str());
329 EXPECT_THAT(lines[1], StrEq("stdout line1"));
330 EXPECT_THAT(lines[2], IsEmpty()); // \n
331
332 // Then kill the process.
333 CaptureStdout();
334 CaptureStderr();
335 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
336 t.join();
337
338 // Finally, check output after murder.
339 out = GetCapturedStdout();
340 err = GetCapturedStderr();
341
Felipe Leme7447d7c2016-11-03 18:12:22 -0700342 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700343 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700344 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700345 " --pid --sleep 20' failed: killed by signal 15\n"));
346}
347
Felipe Leme75876a22016-10-27 16:31:27 -0700348TEST_F(DumpstateTest, RunCommandProgress) {
349 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
350 ds.listener_ = listener;
351 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700352 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700353
354 EXPECT_CALL(*listener, onProgressUpdated(20));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700355 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700356 std::string progress_message = GetProgressMessage(ds.listener_name_, 20, 30);
357 EXPECT_THAT(out, StrEq("stdout\n"));
358 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
359
360 EXPECT_CALL(*listener, onProgressUpdated(30));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700361 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700362 progress_message = GetProgressMessage(ds.listener_name_, 30, 30);
363 EXPECT_THAT(out, StrEq("stdout\n"));
364 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
365
366 // Run a command that will increase maximum timeout.
367 EXPECT_CALL(*listener, onProgressUpdated(31));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700368 EXPECT_CALL(*listener, onMaxProgressUpdated(37));
369 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
370 progress_message = GetProgressMessage(ds.listener_name_, 31, 37, 30); // 20% increase
Felipe Leme75876a22016-10-27 16:31:27 -0700371 EXPECT_THAT(out, StrEq("stdout\n"));
372 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
373
374 // Make sure command ran while in dry_run is counted.
375 SetDryRun(true);
376 EXPECT_CALL(*listener, onProgressUpdated(35));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700377 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
378 progress_message = GetProgressMessage(ds.listener_name_, 35, 37);
Felipe Leme75876a22016-10-27 16:31:27 -0700379 EXPECT_THAT(out, IsEmpty());
380 EXPECT_THAT(err, StrEq(progress_message));
381
382 ds.listener_.clear();
383}
384
Felipe Leme009ecbb2016-11-07 10:18:44 -0800385TEST_F(DumpstateTest, RunCommandProgressIgnoreThreshold) {
386 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
387 ds.listener_ = listener;
388 ds.listener_name_ = "FoxMulder";
389 SetProgress(0, 8, 5); // 8 max, 5 threshold
390
391 // First update should always be sent.
392 EXPECT_CALL(*listener, onProgressUpdated(1));
393 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
394 std::string progress_message = GetProgressMessage(ds.listener_name_, 1, 8);
395 EXPECT_THAT(out, StrEq("stdout\n"));
396 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
397
398 // Fourth update should be ignored because it's between the threshold (5 -1 = 4 < 5).
399 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
400 EXPECT_THAT(out, StrEq("stdout\n"));
401 EXPECT_THAT(err, StrEq("stderr\n"));
402
403 // Third update should be sent because it reaches threshold (6 - 1 = 5).
404 EXPECT_CALL(*listener, onProgressUpdated(6));
405 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
406 progress_message = GetProgressMessage(ds.listener_name_, 6, 8);
407 EXPECT_THAT(out, StrEq("stdout\n"));
408 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
409
410 // Fourth update should be ignored because it's between the threshold (9 - 6 = 3 < 5).
411 // But max update should be sent.
412 EXPECT_CALL(*listener, onMaxProgressUpdated(10)); // 9 * 120% = 10.8 = 10
413 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
414 progress_message = GetProgressMessage(ds.listener_name_, 9, 10, 8, false);
415 EXPECT_THAT(out, StrEq("stdout\n"));
416 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
417
418 ds.listener_.clear();
419}
420
Felipe Lemed80e6b62016-10-03 13:08:14 -0700421TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800422 if (!IsStandalone()) {
423 // TODO: temporarily disabled because it might cause other tests to fail after dropping
424 // to Shell - need to refactor tests to avoid this problem)
425 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
426 return;
427 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700428 // First check root case - only available when running with 'adb root'.
429 uid_t uid = getuid();
430 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700431 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700432 EXPECT_THAT(out, StrEq("0\nstdout\n"));
433 EXPECT_THAT(err, StrEq("stderr\n"));
434 return;
435 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700436 // Then run dropping root.
437 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700438 CommandOptions::WithTimeout(1).DropRoot().Build()));
439 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700440 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700441}
442
443TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800444 if (!IsStandalone()) {
445 // TODO: temporarily disabled because it might cause other tests to fail after dropping
446 // to Shell - need to refactor tests to avoid this problem)
447 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
448 return;
449 }
Felipe Lemef0292972016-11-22 13:57:05 -0800450 if (!PropertiesHelper::IsUserBuild()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700451 // Emulates user build if necessarily.
452 SetBuildType("user");
453 }
454
455 DropRoot();
456
Felipe Leme7447d7c2016-11-03 18:12:22 -0700457 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700458
459 // We don't know the exact path of su, so we just check for the 'root ...' commands
460 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700461 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700462 EXPECT_THAT(err, IsEmpty());
463}
464
Felipe Leme46b85da2016-11-21 17:40:45 -0800465TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
466 if (!IsStandalone()) {
467 // TODO: temporarily disabled because it might cause other tests to fail after dropping
468 // to Shell - need to refactor tests to avoid this problem)
469 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
470 return;
471 }
Felipe Lemef0292972016-11-22 13:57:05 -0800472 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800473 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
474 return;
475 }
476
477 DropRoot();
478
479 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
480 CommandOptions::WithTimeout(1).AsRoot().Build()));
481
482 EXPECT_THAT(out, StrEq("0\nstdout\n"));
483 EXPECT_THAT(err, StrEq("stderr\n"));
484}
485
Felipe Lemecef02982016-10-03 17:22:22 -0700486TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
487 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
488 EXPECT_THAT(out,
489 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
490 EXPECT_THAT(err, IsEmpty());
491}
492
493TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
494 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
495 EXPECT_THAT(err, IsEmpty());
496 // We don't know the exact duration, so we check the prefix and suffix
497 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
498 "such file or directory\n"));
499 EXPECT_THAT(out, EndsWith("s was the duration of 'Y U NO EXIST?' ------\n"));
500}
501
502TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700503 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700504 EXPECT_THAT(err, IsEmpty());
505 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
506}
507
508TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700509 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700510 EXPECT_THAT(err, IsEmpty());
511 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
512}
513
514TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700515 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700516 EXPECT_THAT(err, IsEmpty());
517 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
518}
519
520TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700521 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700522 EXPECT_THAT(err, IsEmpty());
523 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
524}
525
526TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
527 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700528 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700529 EXPECT_THAT(err, IsEmpty());
530 EXPECT_THAT(out, IsEmpty());
531}
532
533TEST_F(DumpstateTest, DumpFileOnDryRun) {
534 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700535 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700536 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -0800537 EXPECT_THAT(
538 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
539 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n------"));
Felipe Lemecef02982016-10-03 17:22:22 -0700540 EXPECT_THAT(out, EndsWith("s was the duration of 'Might as well dump. Dump!' ------\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700541}
542
Felipe Leme75876a22016-10-27 16:31:27 -0700543TEST_F(DumpstateTest, DumpFileUpdateProgress) {
544 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
545 ds.listener_ = listener;
546 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700547 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700548
549 EXPECT_CALL(*listener, onProgressUpdated(5));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700550 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -0700551
552 std::string progress_message =
553 GetProgressMessage(ds.listener_name_, 5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
554 EXPECT_THAT(err, StrEq(progress_message));
555 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
556
557 ds.listener_.clear();
558}
559
Felipe Leme7447d7c2016-11-03 18:12:22 -0700560class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -0700561 public:
562 DumpstateService dss;
563};
564
565TEST_F(DumpstateServiceTest, SetListenerNoName) {
566 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800567 sp<IDumpstateToken> token;
568 EXPECT_TRUE(dss.setListener("", listener, &token).isOk());
569 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700570}
571
572TEST_F(DumpstateServiceTest, SetListenerNoPointer) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800573 sp<IDumpstateToken> token;
574 EXPECT_TRUE(dss.setListener("whatever", nullptr, &token).isOk());
575 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700576}
577
578TEST_F(DumpstateServiceTest, SetListenerTwice) {
579 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800580 sp<IDumpstateToken> token;
581 EXPECT_TRUE(dss.setListener("whatever", listener, &token).isOk());
582 ASSERT_THAT(token, NotNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700583 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
584
Felipe Leme009ecbb2016-11-07 10:18:44 -0800585 token.clear();
586 EXPECT_TRUE(dss.setListener("whatsoever", listener, &token).isOk());
587 ASSERT_THAT(token, IsNull());
588 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
Felipe Leme75876a22016-10-27 16:31:27 -0700589}
Felipe Leme7447d7c2016-11-03 18:12:22 -0700590
591class ProgressTest : public DumpstateBaseTest {
592 public:
593 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
594 return Progress(max, growth_factor, path);
595 }
596
597 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
598 std::string expected_content =
599 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
600 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800601 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700602 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
603 }
604};
605
606TEST_F(ProgressTest, SimpleTest) {
607 Progress progress;
608 EXPECT_EQ(0, progress.Get());
609 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
610 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
611
612 bool max_increased = progress.Inc(1);
613 EXPECT_EQ(1, progress.Get());
614 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
615 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
616 EXPECT_FALSE(max_increased);
617
618 // Ignore negative increase.
619 max_increased = progress.Inc(-1);
620 EXPECT_EQ(1, progress.Get());
621 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
622 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
623 EXPECT_FALSE(max_increased);
624}
625
626TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
627 Progress progress = GetInstance(10, 1.2); // 20% growth factor
628 EXPECT_EQ(0, progress.Get());
629 EXPECT_EQ(10, progress.GetInitialMax());
630 EXPECT_EQ(10, progress.GetMax());
631
632 // No increase
633 bool max_increased = progress.Inc(10);
634 EXPECT_EQ(10, progress.Get());
635 EXPECT_EQ(10, progress.GetMax());
636 EXPECT_FALSE(max_increased);
637
638 // Increase, with new value < max*20%
639 max_increased = progress.Inc(1);
640 EXPECT_EQ(11, progress.Get());
641 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
642 EXPECT_TRUE(max_increased);
643}
644
645TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
646 Progress progress = GetInstance(10, 1.2); // 20% growth factor
647 EXPECT_EQ(0, progress.Get());
648 EXPECT_EQ(10, progress.GetInitialMax());
649 EXPECT_EQ(10, progress.GetMax());
650
651 // No increase
652 bool max_increased = progress.Inc(10);
653 EXPECT_EQ(10, progress.Get());
654 EXPECT_EQ(10, progress.GetMax());
655 EXPECT_FALSE(max_increased);
656
657 // Increase, with new value > max*20%
658 max_increased = progress.Inc(5);
659 EXPECT_EQ(15, progress.Get());
660 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
661 EXPECT_TRUE(max_increased);
662}
663
664TEST_F(ProgressTest, InvalidPath) {
665 Progress progress("/devil/null");
666 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
667}
668
669TEST_F(ProgressTest, EmptyFile) {
670 Progress progress(CopyTextFileFixture("empty-file.txt"));
671 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
672}
673
674TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
675 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
676 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
677}
678
679TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
680 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
681 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
682}
683
684TEST_F(ProgressTest, InvalidLineBothNAN) {
685 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
686 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
687}
688
689TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
690 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
691 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
692}
693
694TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
695 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
696 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
697}
698
699TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
700 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
701 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
702}
703
704TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
705 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
706 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
707}
708
709// Tests stats are properly saved when the file does not exists.
710TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800711 if (!IsStandalone()) {
712 // TODO: temporarily disabled because it's failing when running as suite
713 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
714 return;
715 }
716
Felipe Leme7447d7c2016-11-03 18:12:22 -0700717 std::string path = kTestDataPath + "FirstTime.txt";
718 android::base::RemoveFileIfExists(path);
719
720 Progress run1(path);
721 EXPECT_EQ(0, run1.Get());
722 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
723 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
724
725 bool max_increased = run1.Inc(20);
726 EXPECT_EQ(20, run1.Get());
727 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
728 EXPECT_FALSE(max_increased);
729
730 run1.Save();
731 AssertStats(path, 1, 20);
732}
733
734// Tests what happens when the persistent settings contains the average duration of 1 run.
735// Data on file is 1 run and 109 average.
736TEST_F(ProgressTest, SecondTime) {
737 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
738
739 Progress run1 = GetInstance(-42, 1.2, path);
740 EXPECT_EQ(0, run1.Get());
741 EXPECT_EQ(10, run1.GetInitialMax());
742 EXPECT_EQ(10, run1.GetMax());
743
744 bool max_increased = run1.Inc(20);
745 EXPECT_EQ(20, run1.Get());
746 EXPECT_EQ(24, run1.GetMax());
747 EXPECT_TRUE(max_increased);
748
749 // Average now is 2 runs and (10 + 20)/ 2 = 15
750 run1.Save();
751 AssertStats(path, 2, 15);
752
753 Progress run2 = GetInstance(-42, 1.2, path);
754 EXPECT_EQ(0, run2.Get());
755 EXPECT_EQ(15, run2.GetInitialMax());
756 EXPECT_EQ(15, run2.GetMax());
757
758 max_increased = run2.Inc(25);
759 EXPECT_EQ(25, run2.Get());
760 EXPECT_EQ(30, run2.GetMax());
761 EXPECT_TRUE(max_increased);
762
763 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
764 run2.Save();
765 AssertStats(path, 3, 18);
766
767 Progress run3 = GetInstance(-42, 1.2, path);
768 EXPECT_EQ(0, run3.Get());
769 EXPECT_EQ(18, run3.GetInitialMax());
770 EXPECT_EQ(18, run3.GetMax());
771
772 // Make sure average decreases as well
773 max_increased = run3.Inc(5);
774 EXPECT_EQ(5, run3.Get());
775 EXPECT_EQ(18, run3.GetMax());
776 EXPECT_FALSE(max_increased);
777
778 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
779 run3.Save();
780 AssertStats(path, 4, 14);
781}
782
783// Tests what happens when the persistent settings contains the average duration of 2 runs.
784// Data on file is 2 runs and 15 average.
785TEST_F(ProgressTest, ThirdTime) {
786 std::string path = CopyTextFileFixture("stats-two-runs.txt");
787 AssertStats(path, 2, 15); // Sanity check
788
789 Progress run1 = GetInstance(-42, 1.2, path);
790 EXPECT_EQ(0, run1.Get());
791 EXPECT_EQ(15, run1.GetInitialMax());
792 EXPECT_EQ(15, run1.GetMax());
793
794 bool max_increased = run1.Inc(20);
795 EXPECT_EQ(20, run1.Get());
796 EXPECT_EQ(24, run1.GetMax());
797 EXPECT_TRUE(max_increased);
798
799 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
800 run1.Save();
801 AssertStats(path, 3, 16);
802}
803
Felipe Leme46b85da2016-11-21 17:40:45 -0800804class DumpstateUtilTest : public DumpstateBaseTest {
805 public:
806 void SetUp() {
807 DumpstateBaseTest::SetUp();
808 SetDryRun(false);
809 }
810
Felipe Leme46b85da2016-11-21 17:40:45 -0800811 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -0800812 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -0800813 }
814
815 void CreateFd(const std::string& name) {
816 path_ = kTestDataPath + name;
817 MYLOGD("Creating fd for file %s\n", path_.c_str());
818
819 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
820 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
821 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
822 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
823 }
824
825 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -0800826 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -0800827 const CommandOptions& options = CommandOptions::DEFAULT) {
828 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -0800829 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800830 close(fd);
831
832 CaptureFdOut();
833 err = GetCapturedStderr();
834 return status;
835 }
836
837 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -0800838 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800839 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -0800840 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800841 close(fd);
842
843 CaptureFdOut();
844 err = GetCapturedStderr();
845 return status;
846 }
847
848 int fd;
849
850 // 'fd` output and `stderr` from the last command ran.
851 std::string out, err;
852
853 private:
854 std::string path_;
855};
856
857TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -0800858 CreateFd("RunCommandNoArgs.txt");
859 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800860}
861
Felipe Lemef0292972016-11-22 13:57:05 -0800862TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800863 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800864 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800865 EXPECT_THAT(out, StrEq("stdout\n"));
866 EXPECT_THAT(err, StrEq("stderr\n"));
867}
868
Felipe Lemef0292972016-11-22 13:57:05 -0800869TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
870 CreateFd("RunCommandWithNoArgs.txt");
871 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
872 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
873 EXPECT_THAT(err, StrEq("stderr\n"));
874}
875
Felipe Leme46b85da2016-11-21 17:40:45 -0800876TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
877 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800878 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800879 EXPECT_THAT(err, IsEmpty());
880 EXPECT_THAT(out, StrEq("one\n"));
881}
882
883TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
884 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800885 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800886 EXPECT_THAT(err, IsEmpty());
887 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
888}
889
890TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
891 CreateFd("RunCommandWithLoggingMessage.txt");
892 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -0800893 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -0800894 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
895 EXPECT_THAT(out, StrEq("stdout\n"));
896 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
897}
898
899TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
900 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800901 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
902 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -0800903 EXPECT_THAT(out, IsEmpty());
904 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
905}
906
907TEST_F(DumpstateUtilTest, RunCommandDryRun) {
908 CreateFd("RunCommandDryRun.txt");
909 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -0800910 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
911 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
912 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
913 kSimpleCommand.c_str())));
914 EXPECT_THAT(err, IsEmpty());
915}
916
917TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
918 CreateFd("RunCommandDryRun.txt");
919 SetDryRun(true);
920 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800921 EXPECT_THAT(
922 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
923 EXPECT_THAT(err, IsEmpty());
924}
925
926TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
927 CreateFd("RunCommandDryRunAlways.txt");
928 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -0800929 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -0800930 EXPECT_THAT(out, StrEq("stdout\n"));
931 EXPECT_THAT(err, StrEq("stderr\n"));
932}
933
934TEST_F(DumpstateUtilTest, RunCommandNotFound) {
935 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800936 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800937 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
938 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
939}
940
941TEST_F(DumpstateUtilTest, RunCommandFails) {
942 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800943 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800944 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
945 " --exit 42' failed: exit code 42\n"));
946 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
947 " --exit 42' failed: exit code 42\n"));
948}
949
950TEST_F(DumpstateUtilTest, RunCommandCrashes) {
951 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800952 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -0800953 // We don't know the exit code, so check just the prefix.
954 EXPECT_THAT(
955 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
956 EXPECT_THAT(
957 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
958}
959
960TEST_F(DumpstateUtilTest, RunCommandTimesout) {
961 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -0800962 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
963 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -0800964 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
965 " --sleep 2' timed out after 1"));
966 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
967 " --sleep 2' timed out after 1"));
968}
969
970TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
971 CreateFd("RunCommandIsKilled.txt");
972 CaptureStderr();
973
974 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -0800975 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -0800976 CommandOptions::WithTimeout(100).Always().Build()));
977 });
978
979 // Capture pid and pre-sleep output.
980 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
981 std::string err = GetCapturedStderr();
982 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
983
984 CaptureFdOut();
985 std::vector<std::string> lines = android::base::Split(out, "\n");
986 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
987
988 int pid = atoi(lines[0].c_str());
989 EXPECT_THAT(lines[1], StrEq("stdout line1"));
990 EXPECT_THAT(lines[2], IsEmpty()); // \n
991
992 // Then kill the process.
993 CaptureFdOut();
994 CaptureStderr();
995 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
996 t.join();
997
998 // Finally, check output after murder.
999 CaptureFdOut();
1000 err = GetCapturedStderr();
1001
1002 // out starts with the pid, which is an unknown
1003 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1004 " --pid --sleep 20' failed: killed by signal 15\n"));
1005 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1006 " --pid --sleep 20' failed: killed by signal 15\n"));
1007}
1008
1009TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1010 if (!IsStandalone()) {
1011 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1012 // to Shell - need to refactor tests to avoid this problem)
1013 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1014 return;
1015 }
1016 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001017 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001018 // Emulates user build if necessarily.
1019 SetBuildType("user");
1020 }
1021
1022 DropRoot();
1023
Felipe Lemef0292972016-11-22 13:57:05 -08001024 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001025
1026 // We don't know the exact path of su, so we just check for the 'root ...' commands
1027 EXPECT_THAT(out, StartsWith("Skipping"));
1028 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1029 EXPECT_THAT(err, IsEmpty());
1030}
1031
1032TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1033 if (!IsStandalone()) {
1034 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1035 // to Shell - need to refactor tests to avoid this problem)
1036 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1037 return;
1038 }
1039 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001040 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001041 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1042 return;
1043 }
1044
1045 DropRoot();
1046
Felipe Lemef0292972016-11-22 13:57:05 -08001047 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1048 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001049
1050 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1051 EXPECT_THAT(err, StrEq("stderr\n"));
1052}
Felipe Leme46b85da2016-11-21 17:40:45 -08001053
1054TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1055 if (!IsStandalone()) {
1056 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1057 // to Shell - need to refactor tests to avoid this problem)
1058 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1059 return;
1060 }
1061 CreateFd("RunCommandDropRoot.txt");
1062 // First check root case - only available when running with 'adb root'.
1063 uid_t uid = getuid();
1064 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001065 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001066 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1067 EXPECT_THAT(err, StrEq("stderr\n"));
1068 return;
1069 }
1070 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001071 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001072 CommandOptions::WithTimeout(1).DropRoot().Build()));
1073 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1074 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1075}
1076
Felipe Lemef0292972016-11-22 13:57:05 -08001077TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001078 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001079 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001080 EXPECT_THAT(out,
1081 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1082 EXPECT_THAT(err, IsEmpty());
1083}
1084
Felipe Lemef0292972016-11-22 13:57:05 -08001085TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1086 CreateFd("DumpFileNotFound.txt");
1087 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1088 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1089 "file or directory\n"));
1090 EXPECT_THAT(err, IsEmpty());
1091}
1092
Felipe Leme46b85da2016-11-21 17:40:45 -08001093TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1094 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001095 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001096 EXPECT_THAT(err, IsEmpty());
1097 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1098}
1099
1100TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1101 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001102 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001103 EXPECT_THAT(err, IsEmpty());
1104 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1105}
1106
1107TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1108 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001109 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001110 EXPECT_THAT(err, IsEmpty());
1111 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1112}
1113
1114TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1115 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001116 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001117 EXPECT_THAT(err, IsEmpty());
1118 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1119}
1120
Felipe Lemef0292972016-11-22 13:57:05 -08001121TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1122 CreateFd("DumpFileOnDryRun.txt");
1123 SetDryRun(true);
1124 std::string path = kTestDataPath + "single-line.txt";
1125 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1126 EXPECT_THAT(err, IsEmpty());
1127 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1128}
1129
Felipe Leme46b85da2016-11-21 17:40:45 -08001130TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1131 CreateFd("DumpFileOnDryRun.txt");
1132 SetDryRun(true);
1133 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001134 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001135 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001136 EXPECT_THAT(
1137 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1138 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001139}