blob: eb8f961bb8058ad56ef16bc329c7258ad98ecb98 [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
20#include "DumpstateService.h"
21#include "android/os/BnDumpstate.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070022#include "dumpstate.h"
23
24#include <gmock/gmock.h>
25#include <gtest/gtest.h>
26
Felipe Leme46b85da2016-11-21 17:40:45 -080027#include <fcntl.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070028#include <libgen.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070029#include <signal.h>
30#include <sys/types.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070031#include <unistd.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070032#include <thread>
Felipe Leme4c2d6632016-09-28 14:32:00 -070033
34#include <android-base/file.h>
Felipe Lemed80e6b62016-10-03 13:08:14 -070035#include <android-base/properties.h>
36#include <android-base/stringprintf.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070037#include <android-base/strings.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070038
Felipe Leme75876a22016-10-27 16:31:27 -070039using namespace android;
Felipe Lemed80e6b62016-10-03 13:08:14 -070040
Felipe Leme4c2d6632016-09-28 14:32:00 -070041using ::testing::EndsWith;
Felipe Leme46b85da2016-11-21 17:40:45 -080042using ::testing::HasSubstr;
Felipe Leme009ecbb2016-11-07 10:18:44 -080043using ::testing::IsNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070044using ::testing::IsEmpty;
Felipe Leme009ecbb2016-11-07 10:18:44 -080045using ::testing::NotNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070046using ::testing::StrEq;
47using ::testing::StartsWith;
48using ::testing::Test;
49using ::testing::internal::CaptureStderr;
50using ::testing::internal::CaptureStdout;
51using ::testing::internal::GetCapturedStderr;
52using ::testing::internal::GetCapturedStdout;
53
Felipe Leme75876a22016-10-27 16:31:27 -070054using os::DumpstateService;
55using os::IDumpstateListener;
Felipe Leme009ecbb2016-11-07 10:18:44 -080056using os::IDumpstateToken;
Felipe Leme75876a22016-10-27 16:31:27 -070057
Felipe Leme4c2d6632016-09-28 14:32:00 -070058// Not used on test cases yet...
59void dumpstate_board(void) {
60}
61
Felipe Leme75876a22016-10-27 16:31:27 -070062class DumpstateListenerMock : public IDumpstateListener {
63 public:
64 MOCK_METHOD1(onProgressUpdated, binder::Status(int32_t progress));
65 MOCK_METHOD1(onMaxProgressUpdated, binder::Status(int32_t max_progress));
66
67 protected:
68 MOCK_METHOD0(onAsBinder, IBinder*());
69};
70
Felipe Leme46b85da2016-11-21 17:40:45 -080071static int calls_;
72
Felipe Leme7447d7c2016-11-03 18:12:22 -070073// Base class for all tests in this file
74class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080075 public:
76 virtual void SetUp() override {
77 calls_++;
78 }
79
80 bool IsStandalone() {
81 return calls_ == 1;
82 }
83
84 bool IsUserBuild() {
85 return "user" == android::base::GetProperty("ro.build.type", "(unknown)");
86 }
87
88 void DropRoot() {
89 drop_root_user();
90 uid_t uid = getuid();
91 ASSERT_EQ(2000, (int)uid);
92 }
93
Felipe Leme7447d7c2016-11-03 18:12:22 -070094 protected:
95 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
96 const std::string kFixturesPath = kTestPath + "/../dumpstate_test_fixture/";
97 const std::string kTestDataPath = kFixturesPath + "/testdata/";
98 const std::string kSimpleCommand = kFixturesPath + "dumpstate_test_fixture";
99 const std::string kEchoCommand = "/system/bin/echo";
100
101 /*
102 * Copies a text file fixture to a temporary file, returning it's path.
103 *
104 * Useful in cases where the test case changes the content of the tile.
105 */
106 std::string CopyTextFileFixture(const std::string& relative_name) {
107 std::string from = kTestDataPath + relative_name;
108 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
109 // around for poking when the test fails.
110 std::string to = kTestDataPath + relative_name + ".tmp";
111 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
112 android::base::RemoveFileIfExists(to);
113 CopyTextFile(from, to);
114 return to.c_str();
115 }
116
Felipe Leme46b85da2016-11-21 17:40:45 -0800117 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700118 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800119 void ReadFileToString(const std::string& path, std::string* content) {
120 ASSERT_TRUE(android::base::ReadFileToString(path, content))
121 << "could not read contents from " << path;
122 }
123 void WriteStringToFile(const std::string& content, const std::string& path) {
124 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
125 << "could not write contents to " << path;
126 }
127
128 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700129 void CopyTextFile(const std::string& from, const std::string& to) {
130 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800131 ReadFileToString(from, &content);
132 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700133 }
134};
135
136class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700137 public:
138 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800139 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700140 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700141 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700142 ds.progress_.reset(new Progress());
Felipe Leme9a523ae2016-10-20 15:10:33 -0700143 ds.update_progress_ = false;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800144 ds.update_progress_threshold_ = 0;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700145 }
146
147 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700148 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700149 const CommandOptions& options = CommandOptions::DEFAULT) {
150 CaptureStdout();
151 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700152 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700153 out = GetCapturedStdout();
154 err = GetCapturedStderr();
155 return status;
156 }
157
Felipe Lemecef02982016-10-03 17:22:22 -0700158 // Dumps a file and capture `stdout` and `stderr`.
159 int DumpFile(const std::string& title, const std::string& path) {
160 CaptureStdout();
161 CaptureStderr();
162 int status = ds.DumpFile(title, path);
163 out = GetCapturedStdout();
164 err = GetCapturedStderr();
165 return status;
166 }
167
Felipe Leme46b85da2016-11-21 17:40:45 -0800168 // TODO: should set the system property directly, rather than messing with Dumpstate variable
Felipe Leme9a523ae2016-10-20 15:10:33 -0700169 void SetDryRun(bool dry_run) {
170 ALOGD("Setting dry_run_ to %s\n", dry_run ? "true" : "false");
171 ds.dry_run_ = dry_run;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700172 }
173
Felipe Leme46b85da2016-11-21 17:40:45 -0800174 // TODO: should set the system property directly, rather than messing with Dumpstate variable
Felipe Leme9a523ae2016-10-20 15:10:33 -0700175 void SetBuildType(const std::string& build_type) {
176 ALOGD("Setting build_type_ to '%s'\n", build_type.c_str());
177 ds.build_type_ = build_type;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700178 }
179
Felipe Leme009ecbb2016-11-07 10:18:44 -0800180 void SetProgress(long progress, long initial_max, long threshold = 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700181 ds.update_progress_ = true;
Felipe Leme009ecbb2016-11-07 10:18:44 -0800182 ds.update_progress_threshold_ = threshold;
183 ds.last_updated_progress_ = 0;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700184 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
185 }
186
Felipe Leme7447d7c2016-11-03 18:12:22 -0700187 std::string GetProgressMessage(const std::string& listener_name, int progress, int max,
Felipe Leme009ecbb2016-11-07 10:18:44 -0800188 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700189 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
190 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700191
Felipe Leme7447d7c2016-11-03 18:12:22 -0700192 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700193
Felipe Leme009ecbb2016-11-07 10:18:44 -0800194 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700195 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800196 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700197 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700198 }
199
Felipe Leme009ecbb2016-11-07 10:18:44 -0800200 if (update_progress) {
201 message += android::base::StringPrintf("Setting progress (%s): %d/%d\n",
202 listener_name.c_str(), progress, max);
203 }
204
205 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700206 }
207
Felipe Leme4c2d6632016-09-28 14:32:00 -0700208 // `stdout` and `stderr` from the last command ran.
209 std::string out, err;
210
Felipe Lemefd8affa2016-09-30 17:38:57 -0700211 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700212};
213
214TEST_F(DumpstateTest, RunCommandNoArgs) {
215 EXPECT_EQ(-1, RunCommand("", {}));
216}
217
218TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700219 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700220 EXPECT_THAT(out, StrEq("stdout\n"));
221 EXPECT_THAT(err, StrEq("stderr\n"));
222}
223
224TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700225 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700226 EXPECT_THAT(err, StrEq("stderr\n"));
227 // We don't know the exact duration, so we check the prefix and suffix
Felipe Lemefd8affa2016-09-30 17:38:57 -0700228 EXPECT_THAT(out,
Felipe Leme7447d7c2016-11-03 18:12:22 -0700229 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n------"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700230 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
231}
232
Felipe Lemefd8affa2016-09-30 17:38:57 -0700233TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700234 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700235 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700236 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
237 EXPECT_THAT(out, StrEq("stdout\n"));
238 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
239}
240
241TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700242 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700243 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700244 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700245 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700246}
247
248TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700249 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700250 EXPECT_THAT(err, IsEmpty());
251 EXPECT_THAT(out, StrEq("one\n"));
252}
253
Felipe Lemefd8affa2016-09-30 17:38:57 -0700254TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700255 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700256 EXPECT_THAT(err, IsEmpty());
257 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
258}
259
260TEST_F(DumpstateTest, RunCommandDryRun) {
261 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700262 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700263 // We don't know the exact duration, so we check the prefix and suffix
Felipe Leme7447d7c2016-11-03 18:12:22 -0700264 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Felipe Leme4c2d6632016-09-28 14:32:00 -0700265 ") ------\n\t(skipped on dry run)\n------"));
266 EXPECT_THAT(out, EndsWith("s was the duration of 'I AM GROOT' ------\n"));
267 EXPECT_THAT(err, IsEmpty());
268}
269
270TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
271 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700272 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700273 EXPECT_THAT(out, IsEmpty());
274 EXPECT_THAT(err, IsEmpty());
275}
276
277TEST_F(DumpstateTest, RunCommandDryRunAlways) {
278 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700279 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700280 EXPECT_THAT(out, StrEq("stdout\n"));
281 EXPECT_THAT(err, StrEq("stderr\n"));
282}
283
Felipe Lemefd8affa2016-09-30 17:38:57 -0700284TEST_F(DumpstateTest, RunCommandNotFound) {
285 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
286 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
287 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
288}
289
290TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700291 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
292 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700293 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700294 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700295 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700296}
297
298TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700299 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700300 // We don't know the exit code, so check just the prefix.
301 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700302 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700303 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700304 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700305}
306
307TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700308 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700309 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700310 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700311 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700312 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700313 " --sleep 2' timed out after 1"));
314}
315
316TEST_F(DumpstateTest, RunCommandIsKilled) {
317 CaptureStdout();
318 CaptureStderr();
319
320 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700321 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700322 CommandOptions::WithTimeout(100).Always().Build()));
323 });
324
325 // Capture pid and pre-sleep output.
326 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
327 std::string err = GetCapturedStderr();
328 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
329
330 std::string out = GetCapturedStdout();
331 std::vector<std::string> lines = android::base::Split(out, "\n");
332 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
333
334 int pid = atoi(lines[0].c_str());
335 EXPECT_THAT(lines[1], StrEq("stdout line1"));
336 EXPECT_THAT(lines[2], IsEmpty()); // \n
337
338 // Then kill the process.
339 CaptureStdout();
340 CaptureStderr();
341 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
342 t.join();
343
344 // Finally, check output after murder.
345 out = GetCapturedStdout();
346 err = GetCapturedStderr();
347
Felipe Leme7447d7c2016-11-03 18:12:22 -0700348 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700349 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700350 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700351 " --pid --sleep 20' failed: killed by signal 15\n"));
352}
353
Felipe Leme75876a22016-10-27 16:31:27 -0700354TEST_F(DumpstateTest, RunCommandProgress) {
355 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
356 ds.listener_ = listener;
357 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700358 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700359
360 EXPECT_CALL(*listener, onProgressUpdated(20));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700361 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700362 std::string progress_message = GetProgressMessage(ds.listener_name_, 20, 30);
363 EXPECT_THAT(out, StrEq("stdout\n"));
364 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
365
366 EXPECT_CALL(*listener, onProgressUpdated(30));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700367 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Build()));
Felipe Leme75876a22016-10-27 16:31:27 -0700368 progress_message = GetProgressMessage(ds.listener_name_, 30, 30);
369 EXPECT_THAT(out, StrEq("stdout\n"));
370 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
371
372 // Run a command that will increase maximum timeout.
373 EXPECT_CALL(*listener, onProgressUpdated(31));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700374 EXPECT_CALL(*listener, onMaxProgressUpdated(37));
375 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
376 progress_message = GetProgressMessage(ds.listener_name_, 31, 37, 30); // 20% increase
Felipe Leme75876a22016-10-27 16:31:27 -0700377 EXPECT_THAT(out, StrEq("stdout\n"));
378 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
379
380 // Make sure command ran while in dry_run is counted.
381 SetDryRun(true);
382 EXPECT_CALL(*listener, onProgressUpdated(35));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700383 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
384 progress_message = GetProgressMessage(ds.listener_name_, 35, 37);
Felipe Leme75876a22016-10-27 16:31:27 -0700385 EXPECT_THAT(out, IsEmpty());
386 EXPECT_THAT(err, StrEq(progress_message));
387
388 ds.listener_.clear();
389}
390
Felipe Leme009ecbb2016-11-07 10:18:44 -0800391TEST_F(DumpstateTest, RunCommandProgressIgnoreThreshold) {
392 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
393 ds.listener_ = listener;
394 ds.listener_name_ = "FoxMulder";
395 SetProgress(0, 8, 5); // 8 max, 5 threshold
396
397 // First update should always be sent.
398 EXPECT_CALL(*listener, onProgressUpdated(1));
399 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
400 std::string progress_message = GetProgressMessage(ds.listener_name_, 1, 8);
401 EXPECT_THAT(out, StrEq("stdout\n"));
402 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
403
404 // Fourth update should be ignored because it's between the threshold (5 -1 = 4 < 5).
405 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
406 EXPECT_THAT(out, StrEq("stdout\n"));
407 EXPECT_THAT(err, StrEq("stderr\n"));
408
409 // Third update should be sent because it reaches threshold (6 - 1 = 5).
410 EXPECT_CALL(*listener, onProgressUpdated(6));
411 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
412 progress_message = GetProgressMessage(ds.listener_name_, 6, 8);
413 EXPECT_THAT(out, StrEq("stdout\n"));
414 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
415
416 // Fourth update should be ignored because it's between the threshold (9 - 6 = 3 < 5).
417 // But max update should be sent.
418 EXPECT_CALL(*listener, onMaxProgressUpdated(10)); // 9 * 120% = 10.8 = 10
419 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
420 progress_message = GetProgressMessage(ds.listener_name_, 9, 10, 8, false);
421 EXPECT_THAT(out, StrEq("stdout\n"));
422 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
423
424 ds.listener_.clear();
425}
426
Felipe Lemed80e6b62016-10-03 13:08:14 -0700427TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800428 if (!IsStandalone()) {
429 // TODO: temporarily disabled because it might cause other tests to fail after dropping
430 // to Shell - need to refactor tests to avoid this problem)
431 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
432 return;
433 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700434 // First check root case - only available when running with 'adb root'.
435 uid_t uid = getuid();
436 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700437 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700438 EXPECT_THAT(out, StrEq("0\nstdout\n"));
439 EXPECT_THAT(err, StrEq("stderr\n"));
440 return;
441 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700442 // Then run dropping root.
443 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700444 CommandOptions::WithTimeout(1).DropRoot().Build()));
445 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700446 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700447}
448
449TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800450 if (!IsStandalone()) {
451 // TODO: temporarily disabled because it might cause other tests to fail after dropping
452 // to Shell - need to refactor tests to avoid this problem)
453 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
454 return;
455 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700456 if (!IsUserBuild()) {
457 // Emulates user build if necessarily.
458 SetBuildType("user");
459 }
460
461 DropRoot();
462
Felipe Leme7447d7c2016-11-03 18:12:22 -0700463 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700464
465 // We don't know the exact path of su, so we just check for the 'root ...' commands
466 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700467 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700468 EXPECT_THAT(err, IsEmpty());
469}
470
Felipe Leme46b85da2016-11-21 17:40:45 -0800471TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
472 if (!IsStandalone()) {
473 // TODO: temporarily disabled because it might cause other tests to fail after dropping
474 // to Shell - need to refactor tests to avoid this problem)
475 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
476 return;
477 }
478 if (IsUserBuild()) {
479 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
480 return;
481 }
482
483 DropRoot();
484
485 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
486 CommandOptions::WithTimeout(1).AsRoot().Build()));
487
488 EXPECT_THAT(out, StrEq("0\nstdout\n"));
489 EXPECT_THAT(err, StrEq("stderr\n"));
490}
491
Felipe Lemecef02982016-10-03 17:22:22 -0700492TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
493 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
494 EXPECT_THAT(out,
495 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
496 EXPECT_THAT(err, IsEmpty());
497}
498
499TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
500 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
501 EXPECT_THAT(err, IsEmpty());
502 // We don't know the exact duration, so we check the prefix and suffix
503 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
504 "such file or directory\n"));
505 EXPECT_THAT(out, EndsWith("s was the duration of 'Y U NO EXIST?' ------\n"));
506}
507
508TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700509 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700510 EXPECT_THAT(err, IsEmpty());
511 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
512}
513
514TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700515 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700516 EXPECT_THAT(err, IsEmpty());
517 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
518}
519
520TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700521 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.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, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700527 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700528 EXPECT_THAT(err, IsEmpty());
529 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
530}
531
532TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
533 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700534 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700535 EXPECT_THAT(err, IsEmpty());
536 EXPECT_THAT(out, IsEmpty());
537}
538
539TEST_F(DumpstateTest, DumpFileOnDryRun) {
540 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700541 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700542 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -0800543 EXPECT_THAT(
544 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
545 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n------"));
Felipe Lemecef02982016-10-03 17:22:22 -0700546 EXPECT_THAT(out, EndsWith("s was the duration of 'Might as well dump. Dump!' ------\n"));
547 EXPECT_THAT(err, IsEmpty());
548}
549
Felipe Leme75876a22016-10-27 16:31:27 -0700550TEST_F(DumpstateTest, DumpFileUpdateProgress) {
551 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
552 ds.listener_ = listener;
553 ds.listener_name_ = "FoxMulder";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700554 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700555
556 EXPECT_CALL(*listener, onProgressUpdated(5));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700557 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -0700558
559 std::string progress_message =
560 GetProgressMessage(ds.listener_name_, 5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
561 EXPECT_THAT(err, StrEq(progress_message));
562 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
563
564 ds.listener_.clear();
565}
566
Felipe Leme7447d7c2016-11-03 18:12:22 -0700567class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -0700568 public:
569 DumpstateService dss;
570};
571
572TEST_F(DumpstateServiceTest, SetListenerNoName) {
573 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800574 sp<IDumpstateToken> token;
575 EXPECT_TRUE(dss.setListener("", listener, &token).isOk());
576 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700577}
578
579TEST_F(DumpstateServiceTest, SetListenerNoPointer) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800580 sp<IDumpstateToken> token;
581 EXPECT_TRUE(dss.setListener("whatever", nullptr, &token).isOk());
582 ASSERT_THAT(token, IsNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700583}
584
585TEST_F(DumpstateServiceTest, SetListenerTwice) {
586 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
Felipe Leme009ecbb2016-11-07 10:18:44 -0800587 sp<IDumpstateToken> token;
588 EXPECT_TRUE(dss.setListener("whatever", listener, &token).isOk());
589 ASSERT_THAT(token, NotNull());
Felipe Leme75876a22016-10-27 16:31:27 -0700590 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
591
Felipe Leme009ecbb2016-11-07 10:18:44 -0800592 token.clear();
593 EXPECT_TRUE(dss.setListener("whatsoever", listener, &token).isOk());
594 ASSERT_THAT(token, IsNull());
595 EXPECT_THAT(Dumpstate::GetInstance().listener_name_, StrEq("whatever"));
Felipe Leme75876a22016-10-27 16:31:27 -0700596}
Felipe Leme7447d7c2016-11-03 18:12:22 -0700597
598class ProgressTest : public DumpstateBaseTest {
599 public:
600 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
601 return Progress(max, growth_factor, path);
602 }
603
604 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
605 std::string expected_content =
606 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
607 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800608 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700609 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
610 }
611};
612
613TEST_F(ProgressTest, SimpleTest) {
614 Progress progress;
615 EXPECT_EQ(0, progress.Get());
616 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
617 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
618
619 bool 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 // Ignore negative increase.
626 max_increased = progress.Inc(-1);
627 EXPECT_EQ(1, progress.Get());
628 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
629 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
630 EXPECT_FALSE(max_increased);
631}
632
633TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
634 Progress progress = GetInstance(10, 1.2); // 20% growth factor
635 EXPECT_EQ(0, progress.Get());
636 EXPECT_EQ(10, progress.GetInitialMax());
637 EXPECT_EQ(10, progress.GetMax());
638
639 // No increase
640 bool max_increased = progress.Inc(10);
641 EXPECT_EQ(10, progress.Get());
642 EXPECT_EQ(10, progress.GetMax());
643 EXPECT_FALSE(max_increased);
644
645 // Increase, with new value < max*20%
646 max_increased = progress.Inc(1);
647 EXPECT_EQ(11, progress.Get());
648 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
649 EXPECT_TRUE(max_increased);
650}
651
652TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
653 Progress progress = GetInstance(10, 1.2); // 20% growth factor
654 EXPECT_EQ(0, progress.Get());
655 EXPECT_EQ(10, progress.GetInitialMax());
656 EXPECT_EQ(10, progress.GetMax());
657
658 // No increase
659 bool max_increased = progress.Inc(10);
660 EXPECT_EQ(10, progress.Get());
661 EXPECT_EQ(10, progress.GetMax());
662 EXPECT_FALSE(max_increased);
663
664 // Increase, with new value > max*20%
665 max_increased = progress.Inc(5);
666 EXPECT_EQ(15, progress.Get());
667 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
668 EXPECT_TRUE(max_increased);
669}
670
671TEST_F(ProgressTest, InvalidPath) {
672 Progress progress("/devil/null");
673 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
674}
675
676TEST_F(ProgressTest, EmptyFile) {
677 Progress progress(CopyTextFileFixture("empty-file.txt"));
678 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
679}
680
681TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
682 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
683 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
684}
685
686TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
687 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
688 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
689}
690
691TEST_F(ProgressTest, InvalidLineBothNAN) {
692 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
693 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
694}
695
696TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
697 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
698 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
699}
700
701TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
702 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
703 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
704}
705
706TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
707 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
708 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
709}
710
711TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
712 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
713 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
714}
715
716// Tests stats are properly saved when the file does not exists.
717TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800718 if (!IsStandalone()) {
719 // TODO: temporarily disabled because it's failing when running as suite
720 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
721 return;
722 }
723
Felipe Leme7447d7c2016-11-03 18:12:22 -0700724 std::string path = kTestDataPath + "FirstTime.txt";
725 android::base::RemoveFileIfExists(path);
726
727 Progress run1(path);
728 EXPECT_EQ(0, run1.Get());
729 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
730 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
731
732 bool max_increased = run1.Inc(20);
733 EXPECT_EQ(20, run1.Get());
734 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
735 EXPECT_FALSE(max_increased);
736
737 run1.Save();
738 AssertStats(path, 1, 20);
739}
740
741// Tests what happens when the persistent settings contains the average duration of 1 run.
742// Data on file is 1 run and 109 average.
743TEST_F(ProgressTest, SecondTime) {
744 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
745
746 Progress run1 = GetInstance(-42, 1.2, path);
747 EXPECT_EQ(0, run1.Get());
748 EXPECT_EQ(10, run1.GetInitialMax());
749 EXPECT_EQ(10, run1.GetMax());
750
751 bool max_increased = run1.Inc(20);
752 EXPECT_EQ(20, run1.Get());
753 EXPECT_EQ(24, run1.GetMax());
754 EXPECT_TRUE(max_increased);
755
756 // Average now is 2 runs and (10 + 20)/ 2 = 15
757 run1.Save();
758 AssertStats(path, 2, 15);
759
760 Progress run2 = GetInstance(-42, 1.2, path);
761 EXPECT_EQ(0, run2.Get());
762 EXPECT_EQ(15, run2.GetInitialMax());
763 EXPECT_EQ(15, run2.GetMax());
764
765 max_increased = run2.Inc(25);
766 EXPECT_EQ(25, run2.Get());
767 EXPECT_EQ(30, run2.GetMax());
768 EXPECT_TRUE(max_increased);
769
770 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
771 run2.Save();
772 AssertStats(path, 3, 18);
773
774 Progress run3 = GetInstance(-42, 1.2, path);
775 EXPECT_EQ(0, run3.Get());
776 EXPECT_EQ(18, run3.GetInitialMax());
777 EXPECT_EQ(18, run3.GetMax());
778
779 // Make sure average decreases as well
780 max_increased = run3.Inc(5);
781 EXPECT_EQ(5, run3.Get());
782 EXPECT_EQ(18, run3.GetMax());
783 EXPECT_FALSE(max_increased);
784
785 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
786 run3.Save();
787 AssertStats(path, 4, 14);
788}
789
790// Tests what happens when the persistent settings contains the average duration of 2 runs.
791// Data on file is 2 runs and 15 average.
792TEST_F(ProgressTest, ThirdTime) {
793 std::string path = CopyTextFileFixture("stats-two-runs.txt");
794 AssertStats(path, 2, 15); // Sanity check
795
796 Progress run1 = GetInstance(-42, 1.2, path);
797 EXPECT_EQ(0, run1.Get());
798 EXPECT_EQ(15, run1.GetInitialMax());
799 EXPECT_EQ(15, run1.GetMax());
800
801 bool max_increased = run1.Inc(20);
802 EXPECT_EQ(20, run1.Get());
803 EXPECT_EQ(24, run1.GetMax());
804 EXPECT_TRUE(max_increased);
805
806 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
807 run1.Save();
808 AssertStats(path, 3, 16);
809}
810
Felipe Leme46b85da2016-11-21 17:40:45 -0800811class DumpstateUtilTest : public DumpstateBaseTest {
812 public:
813 void SetUp() {
814 DumpstateBaseTest::SetUp();
815 SetDryRun(false);
816 }
817
818 // TODO: should set the system property directly, rather than messing with Dumpstate variable
819 void SetDryRun(bool dry_run) {
820 ALOGD("Setting dry_run_ to %s\n", dry_run ? "true" : "false");
821 Dumpstate::GetInstance().dry_run_ = dry_run;
822 }
823
824 // TODO: should set the system property directly, rather than messing with Dumpstate variable
825 void SetBuildType(const std::string& build_type) {
826 ALOGD("Setting build_type_ to '%s'\n", build_type.c_str());
827 Dumpstate::GetInstance().build_type_ = build_type;
828 }
829
830 void CaptureFdOut() {
831 // TODO: for some obscure, black-magic C++ curse, the ASSERT_TRUE assertion inside
832 // ReadFileToString() fails, even though the returned value is true, so it's using the
833 // core library function directly, without checking the result (if the file cannot be read,
834 // the test case will eventually fail anyways because of the contents of out).
835 // ReadFileToString(path_, &out);
836 android::base::ReadFileToString(path_, &out);
837 }
838
839 void CreateFd(const std::string& name) {
840 path_ = kTestDataPath + name;
841 MYLOGD("Creating fd for file %s\n", path_.c_str());
842
843 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
844 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
845 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
846 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
847 }
848
849 // Runs a command into the `fd` and capture `stderr`.
850 int RunCommand(const std::vector<std::string>& full_command,
851 const CommandOptions& options = CommandOptions::DEFAULT) {
852 CaptureStderr();
853 int status = RunCommandToFd(fd, full_command, options);
854 close(fd);
855
856 CaptureFdOut();
857 err = GetCapturedStderr();
858 return status;
859 }
860
861 // Dumps a file and into the `fd` and `stderr`.
862 int DumpFile(const std::string& path) {
863 CaptureStderr();
864 int status = DumpFileToFd(fd, path);
865 close(fd);
866
867 CaptureFdOut();
868 err = GetCapturedStderr();
869 return status;
870 }
871
872 int fd;
873
874 // 'fd` output and `stderr` from the last command ran.
875 std::string out, err;
876
877 private:
878 std::string path_;
879};
880
881TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
882 EXPECT_EQ(-1, RunCommand({}));
883}
884
885TEST_F(DumpstateUtilTest, RunCommandWithNoArgs) {
886 CreateFd("RunCommandWithNoArgs.txt");
887 EXPECT_EQ(0, RunCommand({kSimpleCommand}));
888 EXPECT_THAT(out, StrEq("stdout\n"));
889 EXPECT_THAT(err, StrEq("stderr\n"));
890}
891
892TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
893 CreateFd("RunCommandWithOneArg.txt");
894 EXPECT_EQ(0, RunCommand({kEchoCommand, "one"}));
895 EXPECT_THAT(err, IsEmpty());
896 EXPECT_THAT(out, StrEq("one\n"));
897}
898
899TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
900 CreateFd("RunCommandWithMultipleArgs.txt");
901 EXPECT_EQ(0, RunCommand({kEchoCommand, "one", "is", "the", "loniest", "number"}));
902 EXPECT_THAT(err, IsEmpty());
903 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
904}
905
906TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
907 CreateFd("RunCommandWithLoggingMessage.txt");
908 EXPECT_EQ(
909 0, RunCommand({kSimpleCommand},
910 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
911 EXPECT_THAT(out, StrEq("stdout\n"));
912 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
913}
914
915TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
916 CreateFd("RunCommandRedirectStderr.txt");
917 EXPECT_EQ(
918 0, RunCommand({kSimpleCommand}, CommandOptions::WithTimeout(10).RedirectStderr().Build()));
919 EXPECT_THAT(out, IsEmpty());
920 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
921}
922
923TEST_F(DumpstateUtilTest, RunCommandDryRun) {
924 CreateFd("RunCommandDryRun.txt");
925 SetDryRun(true);
926 EXPECT_EQ(0, RunCommand({kSimpleCommand}));
927 EXPECT_THAT(
928 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
929 EXPECT_THAT(err, IsEmpty());
930}
931
932TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
933 CreateFd("RunCommandDryRunAlways.txt");
934 SetDryRun(true);
935 EXPECT_EQ(0, RunCommand({kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
936 EXPECT_THAT(out, StrEq("stdout\n"));
937 EXPECT_THAT(err, StrEq("stderr\n"));
938}
939
940TEST_F(DumpstateUtilTest, RunCommandNotFound) {
941 CreateFd("RunCommandNotFound.txt");
942 EXPECT_NE(0, RunCommand({"/there/cannot/be/such/command"}));
943 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
944 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
945}
946
947TEST_F(DumpstateUtilTest, RunCommandFails) {
948 CreateFd("RunCommandFails.txt");
949 EXPECT_EQ(42, RunCommand({kSimpleCommand, "--exit", "42"}));
950 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
951 " --exit 42' failed: exit code 42\n"));
952 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
953 " --exit 42' failed: exit code 42\n"));
954}
955
956TEST_F(DumpstateUtilTest, RunCommandCrashes) {
957 CreateFd("RunCommandCrashes.txt");
958 EXPECT_NE(0, RunCommand({kSimpleCommand, "--crash"}));
959 // We don't know the exit code, so check just the prefix.
960 EXPECT_THAT(
961 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
962 EXPECT_THAT(
963 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
964}
965
966TEST_F(DumpstateUtilTest, RunCommandTimesout) {
967 CreateFd("RunCommandTimesout.txt");
968 EXPECT_EQ(-1,
969 RunCommand({kSimpleCommand, "--sleep", "2"}, CommandOptions::WithTimeout(1).Build()));
970 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
971 " --sleep 2' timed out after 1"));
972 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
973 " --sleep 2' timed out after 1"));
974}
975
976TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
977 CreateFd("RunCommandIsKilled.txt");
978 CaptureStderr();
979
980 std::thread t([=]() {
981 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, {kSimpleCommand, "--pid", "--sleep", "20"},
982 CommandOptions::WithTimeout(100).Always().Build()));
983 });
984
985 // Capture pid and pre-sleep output.
986 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
987 std::string err = GetCapturedStderr();
988 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
989
990 CaptureFdOut();
991 std::vector<std::string> lines = android::base::Split(out, "\n");
992 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
993
994 int pid = atoi(lines[0].c_str());
995 EXPECT_THAT(lines[1], StrEq("stdout line1"));
996 EXPECT_THAT(lines[2], IsEmpty()); // \n
997
998 // Then kill the process.
999 CaptureFdOut();
1000 CaptureStderr();
1001 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1002 t.join();
1003
1004 // Finally, check output after murder.
1005 CaptureFdOut();
1006 err = GetCapturedStderr();
1007
1008 // out starts with the pid, which is an unknown
1009 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1010 " --pid --sleep 20' failed: killed by signal 15\n"));
1011 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1012 " --pid --sleep 20' failed: killed by signal 15\n"));
1013}
1014
1015TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1016 if (!IsStandalone()) {
1017 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1018 // to Shell - need to refactor tests to avoid this problem)
1019 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1020 return;
1021 }
1022 CreateFd("RunCommandAsRootUserBuild.txt");
1023 if (!IsUserBuild()) {
1024 // Emulates user build if necessarily.
1025 SetBuildType("user");
1026 }
1027
1028 DropRoot();
1029
1030 EXPECT_EQ(0, RunCommand({kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
1031
1032 // We don't know the exact path of su, so we just check for the 'root ...' commands
1033 EXPECT_THAT(out, StartsWith("Skipping"));
1034 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1035 EXPECT_THAT(err, IsEmpty());
1036}
1037
1038TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1039 if (!IsStandalone()) {
1040 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1041 // to Shell - need to refactor tests to avoid this problem)
1042 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1043 return;
1044 }
1045 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Leme7447d7c2016-11-03 18:12:22 -07001046 if (IsUserBuild()) {
1047 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1048 return;
1049 }
1050
1051 DropRoot();
1052
Felipe Leme46b85da2016-11-21 17:40:45 -08001053 EXPECT_EQ(
1054 0, RunCommand({kSimpleCommand, "--uid"}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001055
1056 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1057 EXPECT_THAT(err, StrEq("stderr\n"));
1058}
Felipe Leme46b85da2016-11-21 17:40:45 -08001059
1060TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1061 if (!IsStandalone()) {
1062 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1063 // to Shell - need to refactor tests to avoid this problem)
1064 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1065 return;
1066 }
1067 CreateFd("RunCommandDropRoot.txt");
1068 // First check root case - only available when running with 'adb root'.
1069 uid_t uid = getuid();
1070 if (uid == 0) {
1071 EXPECT_EQ(0, RunCommand({kSimpleCommand, "--uid"}));
1072 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1073 EXPECT_THAT(err, StrEq("stderr\n"));
1074 return;
1075 }
1076 // Then run dropping root.
1077 EXPECT_EQ(0, RunCommand({kSimpleCommand, "--uid"},
1078 CommandOptions::WithTimeout(1).DropRoot().Build()));
1079 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1080 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1081}
1082
1083TEST_F(DumpstateUtilTest, DumpFileNotFound) {
1084 CreateFd("DumpFileNotFound.txt");
1085 EXPECT_EQ(-1, DumpFile("/I/cant/believe/I/exist"));
1086 EXPECT_THAT(out,
1087 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1088 EXPECT_THAT(err, IsEmpty());
1089}
1090
1091TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1092 CreateFd("DumpFileSingleLine.txt");
1093 EXPECT_EQ(0, DumpFile(kTestDataPath + "single-line.txt"));
1094 EXPECT_THAT(err, IsEmpty());
1095 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1096}
1097
1098TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1099 CreateFd("DumpFileSingleLineWithNewLine.txt");
1100 EXPECT_EQ(0, DumpFile(kTestDataPath + "single-line-with-newline.txt"));
1101 EXPECT_THAT(err, IsEmpty());
1102 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1103}
1104
1105TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1106 CreateFd("DumpFileMultipleLines.txt");
1107 EXPECT_EQ(0, DumpFile(kTestDataPath + "multiple-lines.txt"));
1108 EXPECT_THAT(err, IsEmpty());
1109 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1110}
1111
1112TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1113 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
1114 EXPECT_EQ(0, DumpFile(kTestDataPath + "multiple-lines-with-newline.txt"));
1115 EXPECT_THAT(err, IsEmpty());
1116 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1117}
1118
1119TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1120 CreateFd("DumpFileOnDryRun.txt");
1121 SetDryRun(true);
1122 std::string path = kTestDataPath + "single-line.txt";
1123 EXPECT_EQ(0, DumpFile(kTestDataPath + "single-line.txt"));
1124 EXPECT_THAT(err, IsEmpty());
1125 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1126}