blob: 70b4e5c0d87ff9cbbc7a9ec10b43e5f0ee70866f [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
Dieter Hsu105ad0c2020-09-29 15:23:33 +080017#define LOG_TAG "dumpstate_test"
Felipe Leme75876a22016-10-27 16:31:27 -070018
Felipe Lemef0292972016-11-22 13:57:05 -080019#include "DumpstateInternal.h"
Felipe Leme75876a22016-10-27 16:31:27 -070020#include "DumpstateService.h"
21#include "android/os/BnDumpstate.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070022#include "dumpstate.h"
Rhed Jao27077b12020-07-14 18:38:08 +080023#include "DumpPool.h"
Felipe Leme4c2d6632016-09-28 14:32:00 -070024
25#include <gmock/gmock.h>
Dieter Hsu105ad0c2020-09-29 15:23:33 +080026#include <gmock/gmock-matchers.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070027#include <gtest/gtest.h>
28
Felipe Leme46b85da2016-11-21 17:40:45 -080029#include <fcntl.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070030#include <libgen.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070031#include <signal.h>
32#include <sys/types.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070033#include <unistd.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070034#include <thread>
Felipe Leme4c2d6632016-09-28 14:32:00 -070035
Kedar Chitnis9fd8c052021-11-16 09:09:22 +000036#include <aidl/android/hardware/dumpstate/IDumpstateDevice.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070037#include <android-base/file.h>
Felipe Lemed80e6b62016-10-03 13:08:14 -070038#include <android-base/properties.h>
39#include <android-base/stringprintf.h>
Felipe Lemefd8affa2016-09-30 17:38:57 -070040#include <android-base/strings.h>
Abhijeet Kaure370d682019-10-01 16:49:30 +010041#include <android-base/unique_fd.h>
Hunter Knepshield8540faf2020-02-04 19:47:20 -080042#include <android/hardware/dumpstate/1.1/types.h>
Dieter Hsu105ad0c2020-09-29 15:23:33 +080043#include <cutils/log.h>
Hunter Knepshield8540faf2020-02-04 19:47:20 -080044#include <cutils/properties.h>
Dieter Hsu105ad0c2020-09-29 15:23:33 +080045#include <ziparchive/zip_archive.h>
Felipe Leme4c2d6632016-09-28 14:32:00 -070046
Felipe Leme47e9be22016-12-21 15:37:07 -080047namespace android {
48namespace os {
49namespace dumpstate {
Felipe Lemed80e6b62016-10-03 13:08:14 -070050
Kedar Chitnis9fd8c052021-11-16 09:09:22 +000051using DumpstateDeviceAidl = ::aidl::android::hardware::dumpstate::IDumpstateDevice;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080052using ::android::hardware::dumpstate::V1_1::DumpstateMode;
Felipe Leme4c2d6632016-09-28 14:32:00 -070053using ::testing::EndsWith;
Rhed Jao27077b12020-07-14 18:38:08 +080054using ::testing::Eq;
Felipe Leme46b85da2016-11-21 17:40:45 -080055using ::testing::HasSubstr;
Felipe Leme4c2d6632016-09-28 14:32:00 -070056using ::testing::IsEmpty;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080057using ::testing::IsNull;
Felipe Leme009ecbb2016-11-07 10:18:44 -080058using ::testing::NotNull;
Felipe Leme4c2d6632016-09-28 14:32:00 -070059using ::testing::StartsWith;
Hunter Knepshield8540faf2020-02-04 19:47:20 -080060using ::testing::StrEq;
Felipe Leme4c2d6632016-09-28 14:32:00 -070061using ::testing::Test;
62using ::testing::internal::CaptureStderr;
63using ::testing::internal::CaptureStdout;
64using ::testing::internal::GetCapturedStderr;
65using ::testing::internal::GetCapturedStdout;
66
Nandana Dutt3f8c7172018-09-25 12:01:54 +010067#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
68
Felipe Leme75876a22016-10-27 16:31:27 -070069class DumpstateListenerMock : public IDumpstateListener {
70 public:
Nandana Dutta6a28bd2019-01-14 16:54:38 +000071 MOCK_METHOD1(onProgress, binder::Status(int32_t progress));
72 MOCK_METHOD1(onError, binder::Status(int32_t error_code));
Nandana Duttcc4ead82019-01-23 08:29:23 +000073 MOCK_METHOD0(onFinished, binder::Status());
Paul Chang0d2aad72020-02-13 20:04:03 +080074 MOCK_METHOD1(onScreenshotTaken, binder::Status(bool success));
Paul Chang5702b482020-05-28 22:05:47 +080075 MOCK_METHOD0(onUiIntensiveBugreportDumpsFinished, binder::Status());
Felipe Leme75876a22016-10-27 16:31:27 -070076
77 protected:
78 MOCK_METHOD0(onAsBinder, IBinder*());
79};
80
Felipe Leme46b85da2016-11-21 17:40:45 -080081static int calls_;
82
Felipe Leme7447d7c2016-11-03 18:12:22 -070083// Base class for all tests in this file
84class DumpstateBaseTest : public Test {
Felipe Leme46b85da2016-11-21 17:40:45 -080085 public:
86 virtual void SetUp() override {
87 calls_++;
Felipe Lemef0292972016-11-22 13:57:05 -080088 SetDryRun(false);
Felipe Leme46b85da2016-11-21 17:40:45 -080089 }
90
Felipe Lemef0292972016-11-22 13:57:05 -080091 void SetDryRun(bool dry_run) const {
92 PropertiesHelper::dry_run_ = dry_run;
93 }
94
95 void SetBuildType(const std::string& build_type) const {
96 PropertiesHelper::build_type_ = build_type;
97 }
98
Nandana Dutt4b392be2018-11-02 16:17:05 +000099 void SetUnroot(bool unroot) const {
100 PropertiesHelper::unroot_ = unroot;
101 }
102
Rhed Jao1c855122020-07-16 17:37:39 +0800103 void SetParallelRun(bool parallel_run) const {
104 PropertiesHelper::parallel_run_ = parallel_run;
105 }
106
Felipe Lemef0292972016-11-22 13:57:05 -0800107 bool IsStandalone() const {
Felipe Leme46b85da2016-11-21 17:40:45 -0800108 return calls_ == 1;
109 }
110
Felipe Lemef0292972016-11-22 13:57:05 -0800111 void DropRoot() const {
112 DropRootUser();
Felipe Leme46b85da2016-11-21 17:40:45 -0800113 uid_t uid = getuid();
114 ASSERT_EQ(2000, (int)uid);
115 }
116
Felipe Leme7447d7c2016-11-03 18:12:22 -0700117 protected:
118 const std::string kTestPath = dirname(android::base::GetExecutablePath().c_str());
Dan Shie177e8e2019-06-20 11:08:14 -0700119 const std::string kTestDataPath = kTestPath + "/tests/testdata/";
120 const std::string kSimpleCommand = kTestPath + "/dumpstate_test_fixture";
Felipe Leme7447d7c2016-11-03 18:12:22 -0700121 const std::string kEchoCommand = "/system/bin/echo";
122
123 /*
124 * Copies a text file fixture to a temporary file, returning it's path.
125 *
126 * Useful in cases where the test case changes the content of the tile.
127 */
128 std::string CopyTextFileFixture(const std::string& relative_name) {
129 std::string from = kTestDataPath + relative_name;
130 // Not using TemporaryFile because it's deleted at the end, and it's useful to keep it
131 // around for poking when the test fails.
132 std::string to = kTestDataPath + relative_name + ".tmp";
133 ALOGD("CopyTextFileFixture: from %s to %s\n", from.c_str(), to.c_str());
134 android::base::RemoveFileIfExists(to);
135 CopyTextFile(from, to);
136 return to.c_str();
137 }
138
Felipe Leme46b85da2016-11-21 17:40:45 -0800139 // Need functions that returns void to use assertions -
Felipe Leme7447d7c2016-11-03 18:12:22 -0700140 // https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#assertion-placement
Felipe Leme46b85da2016-11-21 17:40:45 -0800141 void ReadFileToString(const std::string& path, std::string* content) {
142 ASSERT_TRUE(android::base::ReadFileToString(path, content))
143 << "could not read contents from " << path;
144 }
145 void WriteStringToFile(const std::string& content, const std::string& path) {
146 ASSERT_TRUE(android::base::WriteStringToFile(content, path))
147 << "could not write contents to " << path;
148 }
149
150 private:
Felipe Leme7447d7c2016-11-03 18:12:22 -0700151 void CopyTextFile(const std::string& from, const std::string& to) {
152 std::string content;
Felipe Leme46b85da2016-11-21 17:40:45 -0800153 ReadFileToString(from, &content);
154 WriteStringToFile(content, to);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700155 }
156};
157
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100158class DumpOptionsTest : public Test {
159 public:
160 virtual ~DumpOptionsTest() {
161 }
162 virtual void SetUp() {
163 options_ = Dumpstate::DumpOptions();
164 }
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000165 void TearDown() {
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000166 }
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100167 Dumpstate::DumpOptions options_;
Abhijeet Kaure370d682019-10-01 16:49:30 +0100168 android::base::unique_fd fd;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100169};
170
171TEST_F(DumpOptionsTest, InitializeNone) {
172 // clang-format off
173 char* argv[] = {
174 const_cast<char*>("dumpstate")
175 };
176 // clang-format on
177
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100178 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
179
180 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Nandana Dutt58d72e22018-11-16 10:30:48 +0000181
mhasank3a4cfb42020-06-15 18:06:43 -0700182 EXPECT_EQ("", options_.out_dir);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800183 EXPECT_FALSE(options_.stream_to_socket);
184 EXPECT_FALSE(options_.progress_updates_to_socket);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100185 EXPECT_FALSE(options_.show_header_only);
186 EXPECT_TRUE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800187 EXPECT_FALSE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100188 EXPECT_FALSE(options_.do_progress_updates);
189 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700190 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000191}
192
193TEST_F(DumpOptionsTest, InitializeAdbBugreport) {
194 // clang-format off
195 char* argv[] = {
196 const_cast<char*>("dumpstatez"),
197 const_cast<char*>("-S"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000198 };
199 // clang-format on
200
201 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
202
203 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800204 EXPECT_TRUE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000205
206 // Other options retain default values
207 EXPECT_TRUE(options_.do_vibrate);
208 EXPECT_FALSE(options_.show_header_only);
Paul Chang0d2aad72020-02-13 20:04:03 +0800209 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000210 EXPECT_FALSE(options_.do_progress_updates);
211 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800212 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700213 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000214}
215
216TEST_F(DumpOptionsTest, InitializeAdbShellBugreport) {
217 // clang-format off
218 char* argv[] = {
219 const_cast<char*>("dumpstate"),
220 const_cast<char*>("-s"),
221 };
222 // clang-format on
223
224 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
225
226 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800227 EXPECT_TRUE(options_.stream_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000228
229 // Other options retain default values
230 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800231 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000232 EXPECT_FALSE(options_.show_header_only);
Paul Chang0d2aad72020-02-13 20:04:03 +0800233 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000234 EXPECT_FALSE(options_.do_progress_updates);
235 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700236 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000237}
238
239TEST_F(DumpOptionsTest, InitializeFullBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800240 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_FULL, fd, fd, true);
Paul Chang0d2aad72020-02-13 20:04:03 +0800241 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000242
243 // Other options retain default values
244 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800245 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000246 EXPECT_FALSE(options_.show_header_only);
247 EXPECT_FALSE(options_.do_progress_updates);
248 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800249 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700250 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000251}
252
253TEST_F(DumpOptionsTest, InitializeInteractiveBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800254 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE, fd, fd, true);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000255 EXPECT_TRUE(options_.do_progress_updates);
Paul Chang0d2aad72020-02-13 20:04:03 +0800256 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000257
258 // Other options retain default values
259 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800260 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000261 EXPECT_FALSE(options_.show_header_only);
262 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800263 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700264 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000265}
266
267TEST_F(DumpOptionsTest, InitializeRemoteBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800268 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_REMOTE, fd, fd, false);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000269 EXPECT_TRUE(options_.is_remote_mode);
270 EXPECT_FALSE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800271 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000272
273 // Other options retain default values
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800274 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000275 EXPECT_FALSE(options_.show_header_only);
276 EXPECT_FALSE(options_.do_progress_updates);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800277 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700278 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000279}
280
281TEST_F(DumpOptionsTest, InitializeWearBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800282 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WEAR, fd, fd, true);
Paul Chang0d2aad72020-02-13 20:04:03 +0800283 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000284 EXPECT_TRUE(options_.do_progress_updates);
Kedar Chitnis9fd8c052021-11-16 09:09:22 +0000285
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000286
287 // Other options retain default values
288 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800289 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000290 EXPECT_FALSE(options_.show_header_only);
291 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800292 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700293 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000294}
295
296TEST_F(DumpOptionsTest, InitializeTelephonyBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800297 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_TELEPHONY, fd, fd, false);
Paul Chang0d2aad72020-02-13 20:04:03 +0800298 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000299 EXPECT_TRUE(options_.telephony_only);
Hunter Knepshield820f9bc2020-02-05 20:10:53 -0800300 EXPECT_TRUE(options_.do_progress_updates);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000301
302 // Other options retain default values
303 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800304 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000305 EXPECT_FALSE(options_.show_header_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000306 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800307 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700308 EXPECT_FALSE(options_.limited_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000309}
310
311TEST_F(DumpOptionsTest, InitializeWifiBugReport) {
Paul Changf59c2b72020-03-10 02:08:55 +0800312 options_.Initialize(Dumpstate::BugreportMode::BUGREPORT_WIFI, fd, fd, false);
Paul Chang0d2aad72020-02-13 20:04:03 +0800313 EXPECT_FALSE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000314 EXPECT_TRUE(options_.wifi_only);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000315
316 // Other options retain default values
317 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800318 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000319 EXPECT_FALSE(options_.show_header_only);
320 EXPECT_FALSE(options_.do_progress_updates);
321 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800322 EXPECT_FALSE(options_.stream_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700323 EXPECT_FALSE(options_.limited_only);
324}
325
326TEST_F(DumpOptionsTest, InitializeLimitedOnlyBugreport) {
327 // clang-format off
328 char* argv[] = {
329 const_cast<char*>("dumpstatez"),
330 const_cast<char*>("-S"),
mhasankd451a472020-05-26 18:02:39 -0700331 const_cast<char*>("-q"),
mhasank2d75c442020-06-11 15:05:25 -0700332 const_cast<char*>("-L"),
333 const_cast<char*>("-o abc")
mhasankd451a472020-05-26 18:02:39 -0700334 };
335 // clang-format on
336
337 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
338
339 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800340 EXPECT_TRUE(options_.progress_updates_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700341 EXPECT_FALSE(options_.do_vibrate);
342 EXPECT_TRUE(options_.limited_only);
mhasank3a4cfb42020-06-15 18:06:43 -0700343 EXPECT_EQ(" abc", std::string(options_.out_dir));
mhasankd451a472020-05-26 18:02:39 -0700344
345 // Other options retain default values
346 EXPECT_FALSE(options_.show_header_only);
347 EXPECT_FALSE(options_.do_screenshot);
348 EXPECT_FALSE(options_.do_progress_updates);
349 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800350 EXPECT_FALSE(options_.stream_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000351}
352
353TEST_F(DumpOptionsTest, InitializeDefaultBugReport) {
354 // default: commandline options are not overridden
355 // clang-format off
356 char* argv[] = {
357 const_cast<char*>("bugreport"),
358 const_cast<char*>("-d"),
359 const_cast<char*>("-p"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000360 const_cast<char*>("-z"),
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000361 };
362 // clang-format on
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000363 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
364
365 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Paul Chang0d2aad72020-02-13 20:04:03 +0800366 EXPECT_TRUE(options_.do_screenshot);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000367
368 // Other options retain default values
369 EXPECT_TRUE(options_.do_vibrate);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800370 EXPECT_FALSE(options_.progress_updates_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000371 EXPECT_FALSE(options_.show_header_only);
372 EXPECT_FALSE(options_.do_progress_updates);
373 EXPECT_FALSE(options_.is_remote_mode);
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800374 EXPECT_FALSE(options_.stream_to_socket);
Abhijeet Kaur904e0e02018-12-05 14:03:01 +0000375 EXPECT_FALSE(options_.wifi_only);
mhasankd451a472020-05-26 18:02:39 -0700376 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100377}
378
379TEST_F(DumpOptionsTest, InitializePartial1) {
380 // clang-format off
381 char* argv[] = {
382 const_cast<char*>("dumpstate"),
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100383 const_cast<char*>("-s"),
384 const_cast<char*>("-S"),
385
386 };
387 // clang-format on
388
389 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
390
391 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100392 // TODO: Maybe we should trim the filename
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800393 EXPECT_TRUE(options_.stream_to_socket);
394 EXPECT_TRUE(options_.progress_updates_to_socket);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100395
396 // Other options retain default values
397 EXPECT_FALSE(options_.show_header_only);
398 EXPECT_TRUE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800399 EXPECT_FALSE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100400 EXPECT_FALSE(options_.do_progress_updates);
401 EXPECT_FALSE(options_.is_remote_mode);
mhasankd451a472020-05-26 18:02:39 -0700402 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100403}
404
405TEST_F(DumpOptionsTest, InitializePartial2) {
406 // clang-format off
407 char* argv[] = {
408 const_cast<char*>("dumpstate"),
409 const_cast<char*>("-v"),
410 const_cast<char*>("-q"),
411 const_cast<char*>("-p"),
412 const_cast<char*>("-P"),
413 const_cast<char*>("-R"),
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100414 };
415 // clang-format on
416
417 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
418
419 EXPECT_EQ(status, Dumpstate::RunStatus::OK);
420 EXPECT_TRUE(options_.show_header_only);
421 EXPECT_FALSE(options_.do_vibrate);
Paul Chang0d2aad72020-02-13 20:04:03 +0800422 EXPECT_TRUE(options_.do_screenshot);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100423 EXPECT_TRUE(options_.do_progress_updates);
424 EXPECT_TRUE(options_.is_remote_mode);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100425
426 // Other options retain default values
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800427 EXPECT_FALSE(options_.stream_to_socket);
428 EXPECT_FALSE(options_.progress_updates_to_socket);
mhasankd451a472020-05-26 18:02:39 -0700429 EXPECT_FALSE(options_.limited_only);
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100430}
431
432TEST_F(DumpOptionsTest, InitializeHelp) {
433 // clang-format off
434 char* argv[] = {
435 const_cast<char*>("dumpstate"),
436 const_cast<char*>("-h")
437 };
438 // clang-format on
439
440 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
441
442 // -h is for help.
443 EXPECT_EQ(status, Dumpstate::RunStatus::HELP);
444}
445
446TEST_F(DumpOptionsTest, InitializeUnknown) {
447 // clang-format off
448 char* argv[] = {
449 const_cast<char*>("dumpstate"),
450 const_cast<char*>("-u") // unknown flag
451 };
452 // clang-format on
453
454 Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
455
456 // -u is unknown.
457 EXPECT_EQ(status, Dumpstate::RunStatus::INVALID_INPUT);
458}
459
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800460TEST_F(DumpOptionsTest, ValidateOptionsSocketUsage1) {
461 options_.progress_updates_to_socket = true;
462 options_.stream_to_socket = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100463 EXPECT_FALSE(options_.ValidateOptions());
Nandana Dutt9a76d202019-01-21 15:56:48 +0000464
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800465 options_.stream_to_socket = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100466 EXPECT_TRUE(options_.ValidateOptions());
467}
468
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800469TEST_F(DumpOptionsTest, ValidateOptionsSocketUsage2) {
Abhijeet Kaure370d682019-10-01 16:49:30 +0100470 options_.do_progress_updates = true;
Nandana Dutt9a76d202019-01-21 15:56:48 +0000471 // Writing to socket = !writing to file.
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800472 options_.stream_to_socket = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100473 EXPECT_FALSE(options_.ValidateOptions());
Nandana Dutt9a76d202019-01-21 15:56:48 +0000474
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800475 options_.stream_to_socket = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100476 EXPECT_TRUE(options_.ValidateOptions());
477}
478
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100479TEST_F(DumpOptionsTest, ValidateOptionsRemoteMode) {
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800480 options_.do_progress_updates = true;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100481 options_.is_remote_mode = true;
482 EXPECT_FALSE(options_.ValidateOptions());
483
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800484 options_.do_progress_updates = false;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100485 EXPECT_TRUE(options_.ValidateOptions());
486}
487
Felipe Leme7447d7c2016-11-03 18:12:22 -0700488class DumpstateTest : public DumpstateBaseTest {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700489 public:
490 void SetUp() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800491 DumpstateBaseTest::SetUp();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700492 SetDryRun(false);
Felipe Lemed80e6b62016-10-03 13:08:14 -0700493 SetBuildType(android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700494 ds.progress_.reset(new Progress());
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100495 ds.options_.reset(new Dumpstate::DumpOptions());
Felipe Leme4c2d6632016-09-28 14:32:00 -0700496 }
497
Rhed Jao1c855122020-07-16 17:37:39 +0800498 void TearDown() {
499 ds.ShutdownDumpPool();
500 }
501
Felipe Leme4c2d6632016-09-28 14:32:00 -0700502 // Runs a command and capture `stdout` and `stderr`.
Felipe Leme9a523ae2016-10-20 15:10:33 -0700503 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme4c2d6632016-09-28 14:32:00 -0700504 const CommandOptions& options = CommandOptions::DEFAULT) {
505 CaptureStdout();
506 CaptureStderr();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700507 int status = ds.RunCommand(title, full_command, options);
Felipe Leme4c2d6632016-09-28 14:32:00 -0700508 out = GetCapturedStdout();
509 err = GetCapturedStderr();
510 return status;
511 }
512
Felipe Lemecef02982016-10-03 17:22:22 -0700513 // Dumps a file and capture `stdout` and `stderr`.
514 int DumpFile(const std::string& title, const std::string& path) {
515 CaptureStdout();
516 CaptureStderr();
517 int status = ds.DumpFile(title, path);
518 out = GetCapturedStdout();
519 err = GetCapturedStderr();
520 return status;
521 }
522
Nandana Dutt402a8392019-06-14 14:25:13 +0100523 void SetProgress(long progress, long initial_max) {
524 ds.last_reported_percent_progress_ = 0;
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100525 ds.options_->do_progress_updates = true;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700526 ds.progress_.reset(new Progress(initial_max, progress, 1.2));
527 }
528
Rhed Jao1c855122020-07-16 17:37:39 +0800529 void EnableParallelRunIfNeeded() {
530 ds.EnableParallelRunIfNeeded();
531 }
532
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100533 std::string GetProgressMessage(int progress, int max,
534 int old_max = 0, bool update_progress = true) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700535 EXPECT_EQ(progress, ds.progress_->Get()) << "invalid progress";
536 EXPECT_EQ(max, ds.progress_->GetMax()) << "invalid max";
Felipe Leme75876a22016-10-27 16:31:27 -0700537
Felipe Leme7447d7c2016-11-03 18:12:22 -0700538 bool max_increased = old_max > 0;
Felipe Leme75876a22016-10-27 16:31:27 -0700539
Felipe Leme009ecbb2016-11-07 10:18:44 -0800540 std::string message = "";
Felipe Leme75876a22016-10-27 16:31:27 -0700541 if (max_increased) {
Felipe Leme009ecbb2016-11-07 10:18:44 -0800542 message =
Felipe Leme7447d7c2016-11-03 18:12:22 -0700543 android::base::StringPrintf("Adjusting max progress from %d to %d\n", old_max, max);
Felipe Leme75876a22016-10-27 16:31:27 -0700544 }
545
Felipe Leme009ecbb2016-11-07 10:18:44 -0800546 if (update_progress) {
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100547 message += android::base::StringPrintf("Setting progress: %d/%d (%d%%)\n",
548 progress, max, (100 * progress / max));
Felipe Leme009ecbb2016-11-07 10:18:44 -0800549 }
550
551 return message;
Felipe Lemed80e6b62016-10-03 13:08:14 -0700552 }
553
Felipe Leme4c2d6632016-09-28 14:32:00 -0700554 // `stdout` and `stderr` from the last command ran.
555 std::string out, err;
556
Felipe Lemefd8affa2016-09-30 17:38:57 -0700557 Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme4c2d6632016-09-28 14:32:00 -0700558};
559
560TEST_F(DumpstateTest, RunCommandNoArgs) {
561 EXPECT_EQ(-1, RunCommand("", {}));
562}
563
564TEST_F(DumpstateTest, RunCommandNoTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700565 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700566 EXPECT_THAT(out, StrEq("stdout\n"));
567 EXPECT_THAT(err, StrEq("stderr\n"));
568}
569
570TEST_F(DumpstateTest, RunCommandWithTitle) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700571 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700572 EXPECT_THAT(err, StrEq("stderr\n"));
Greg Kaiser3a811c12019-05-21 12:48:59 -0700573 // The duration may not get output, depending on how long it takes,
574 // so we just check the prefix.
Felipe Lemefd8affa2016-09-30 17:38:57 -0700575 EXPECT_THAT(out,
Nandana Dutt47527b52019-03-29 15:34:36 +0000576 StartsWith("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700577}
578
Felipe Lemefd8affa2016-09-30 17:38:57 -0700579TEST_F(DumpstateTest, RunCommandWithLoggingMessage) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700580 EXPECT_EQ(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700581 0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700582 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
583 EXPECT_THAT(out, StrEq("stdout\n"));
584 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
585}
586
587TEST_F(DumpstateTest, RunCommandRedirectStderr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700588 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700589 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700590 EXPECT_THAT(out, IsEmpty());
Felipe Lemefd8affa2016-09-30 17:38:57 -0700591 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700592}
593
594TEST_F(DumpstateTest, RunCommandWithOneArg) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700595 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700596 EXPECT_THAT(err, IsEmpty());
597 EXPECT_THAT(out, StrEq("one\n"));
598}
599
Felipe Lemefd8affa2016-09-30 17:38:57 -0700600TEST_F(DumpstateTest, RunCommandWithMultipleArgs) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700601 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700602 EXPECT_THAT(err, IsEmpty());
603 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
604}
605
606TEST_F(DumpstateTest, RunCommandDryRun) {
607 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700608 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
Greg Kaiser3a811c12019-05-21 12:48:59 -0700609 // The duration may not get output, depending on how long it takes,
610 // so we just check the prefix.
Felipe Leme7447d7c2016-11-03 18:12:22 -0700611 EXPECT_THAT(out, StartsWith("------ I AM GROOT (" + kSimpleCommand +
Nandana Dutt47527b52019-03-29 15:34:36 +0000612 ") ------\n\t(skipped on dry run)\n"));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700613 EXPECT_THAT(err, IsEmpty());
614}
615
616TEST_F(DumpstateTest, RunCommandDryRunNoTitle) {
617 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700618 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700619 EXPECT_THAT(out, IsEmpty());
620 EXPECT_THAT(err, IsEmpty());
621}
622
623TEST_F(DumpstateTest, RunCommandDryRunAlways) {
624 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700625 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme4c2d6632016-09-28 14:32:00 -0700626 EXPECT_THAT(out, StrEq("stdout\n"));
627 EXPECT_THAT(err, StrEq("stderr\n"));
628}
629
Felipe Lemefd8affa2016-09-30 17:38:57 -0700630TEST_F(DumpstateTest, RunCommandNotFound) {
631 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
632 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
633 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
634}
635
636TEST_F(DumpstateTest, RunCommandFails) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700637 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
638 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700639 " --exit 42' failed: exit code 42\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700640 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
Felipe Leme9a523ae2016-10-20 15:10:33 -0700641 " --exit 42' failed: exit code 42\n"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700642}
643
644TEST_F(DumpstateTest, RunCommandCrashes) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700645 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700646 // We don't know the exit code, so check just the prefix.
647 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700648 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700649 EXPECT_THAT(
Felipe Leme7447d7c2016-11-03 18:12:22 -0700650 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
Felipe Lemefd8affa2016-09-30 17:38:57 -0700651}
652
653TEST_F(DumpstateTest, RunCommandTimesout) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700654 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700655 CommandOptions::WithTimeout(1).Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700656 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700657 " --sleep 2' timed out after 1"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700658 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700659 " --sleep 2' timed out after 1"));
660}
661
662TEST_F(DumpstateTest, RunCommandIsKilled) {
663 CaptureStdout();
664 CaptureStderr();
665
666 std::thread t([=]() {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700667 EXPECT_EQ(SIGTERM, ds.RunCommand("", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Lemefd8affa2016-09-30 17:38:57 -0700668 CommandOptions::WithTimeout(100).Always().Build()));
669 });
670
671 // Capture pid and pre-sleep output.
672 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
673 std::string err = GetCapturedStderr();
674 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
675
676 std::string out = GetCapturedStdout();
677 std::vector<std::string> lines = android::base::Split(out, "\n");
678 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
679
680 int pid = atoi(lines[0].c_str());
681 EXPECT_THAT(lines[1], StrEq("stdout line1"));
682 EXPECT_THAT(lines[2], IsEmpty()); // \n
683
684 // Then kill the process.
685 CaptureStdout();
686 CaptureStderr();
687 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
688 t.join();
689
690 // Finally, check output after murder.
691 out = GetCapturedStdout();
692 err = GetCapturedStderr();
693
Felipe Leme7447d7c2016-11-03 18:12:22 -0700694 EXPECT_THAT(out, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700695 " --pid --sleep 20' failed: killed by signal 15\n"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700696 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
Felipe Lemefd8affa2016-09-30 17:38:57 -0700697 " --pid --sleep 20' failed: killed by signal 15\n"));
698}
699
Felipe Leme75876a22016-10-27 16:31:27 -0700700TEST_F(DumpstateTest, RunCommandProgress) {
701 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
702 ds.listener_ = listener;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700703 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700704
Nandana Duttbabf6c72019-01-15 14:11:12 +0000705 EXPECT_CALL(*listener, onProgress(66)); // 20/30 %
Felipe Leme7447d7c2016-11-03 18:12:22 -0700706 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(20).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100707 std::string progress_message = GetProgressMessage(20, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700708 EXPECT_THAT(out, StrEq("stdout\n"));
709 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
710
Nandana Dutt402a8392019-06-14 14:25:13 +0100711 EXPECT_CALL(*listener, onProgress(80)); // 24/30 %
712 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(4).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100713 progress_message = GetProgressMessage(24, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700714 EXPECT_THAT(out, StrEq("stdout\n"));
715 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
716
717 // Make sure command ran while in dry_run is counted.
718 SetDryRun(true);
Nandana Dutt402a8392019-06-14 14:25:13 +0100719 EXPECT_CALL(*listener, onProgress(90)); // 27/30 %
720 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(3).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100721 progress_message = GetProgressMessage(27, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700722 EXPECT_THAT(out, IsEmpty());
723 EXPECT_THAT(err, StrEq(progress_message));
724
Nandana Dutt402a8392019-06-14 14:25:13 +0100725 SetDryRun(false);
726 EXPECT_CALL(*listener, onProgress(96)); // 29/30 %
727 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(2).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100728 progress_message = GetProgressMessage(29, 30);
Felipe Leme009ecbb2016-11-07 10:18:44 -0800729 EXPECT_THAT(out, StrEq("stdout\n"));
730 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
731
Nandana Dutt402a8392019-06-14 14:25:13 +0100732 EXPECT_CALL(*listener, onProgress(100)); // 30/30 %
Felipe Leme009ecbb2016-11-07 10:18:44 -0800733 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).Build()));
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100734 progress_message = GetProgressMessage(30, 30);
Felipe Leme009ecbb2016-11-07 10:18:44 -0800735 EXPECT_THAT(out, StrEq("stdout\n"));
736 EXPECT_THAT(err, StrEq("stderr\n" + progress_message));
737
738 ds.listener_.clear();
739}
740
Felipe Lemed80e6b62016-10-03 13:08:14 -0700741TEST_F(DumpstateTest, RunCommandDropRoot) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800742 if (!IsStandalone()) {
743 // TODO: temporarily disabled because it might cause other tests to fail after dropping
744 // to Shell - need to refactor tests to avoid this problem)
745 MYLOGE("Skipping DumpstateTest.RunCommandDropRoot() on test suite\n")
746 return;
747 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700748 // First check root case - only available when running with 'adb root'.
749 uid_t uid = getuid();
750 if (uid == 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700751 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700752 EXPECT_THAT(out, StrEq("0\nstdout\n"));
753 EXPECT_THAT(err, StrEq("stderr\n"));
754 return;
755 }
Felipe Leme7447d7c2016-11-03 18:12:22 -0700756 // Then run dropping root.
757 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Lemed80e6b62016-10-03 13:08:14 -0700758 CommandOptions::WithTimeout(1).DropRoot().Build()));
759 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
Felipe Leme26c41572016-10-06 14:34:43 -0700760 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700761}
762
763TEST_F(DumpstateTest, RunCommandAsRootUserBuild) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800764 if (!IsStandalone()) {
765 // TODO: temporarily disabled because it might cause other tests to fail after dropping
766 // to Shell - need to refactor tests to avoid this problem)
767 MYLOGE("Skipping DumpstateTest.RunCommandAsRootUserBuild() on test suite\n")
768 return;
769 }
Felipe Lemef0292972016-11-22 13:57:05 -0800770 if (!PropertiesHelper::IsUserBuild()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700771 // Emulates user build if necessarily.
772 SetBuildType("user");
773 }
774
775 DropRoot();
776
Felipe Leme7447d7c2016-11-03 18:12:22 -0700777 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700778
779 // We don't know the exact path of su, so we just check for the 'root ...' commands
780 EXPECT_THAT(out, StartsWith("Skipping"));
Felipe Leme7447d7c2016-11-03 18:12:22 -0700781 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
Felipe Lemed80e6b62016-10-03 13:08:14 -0700782 EXPECT_THAT(err, IsEmpty());
783}
784
Felipe Leme46b85da2016-11-21 17:40:45 -0800785TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild) {
786 if (!IsStandalone()) {
787 // TODO: temporarily disabled because it might cause other tests to fail after dropping
788 // to Shell - need to refactor tests to avoid this problem)
789 MYLOGE("Skipping DumpstateTest.RunCommandAsRootNonUserBuild() on test suite\n")
790 return;
791 }
Felipe Lemef0292972016-11-22 13:57:05 -0800792 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800793 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
794 return;
795 }
796
797 DropRoot();
798
799 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
800 CommandOptions::WithTimeout(1).AsRoot().Build()));
801
802 EXPECT_THAT(out, StrEq("0\nstdout\n"));
803 EXPECT_THAT(err, StrEq("stderr\n"));
804}
805
Nandana Dutt4b392be2018-11-02 16:17:05 +0000806TEST_F(DumpstateTest, RunCommandAsRootNonUserBuild_withUnroot) {
807 if (!IsStandalone()) {
808 // TODO: temporarily disabled because it might cause other tests to fail after dropping
809 // to Shell - need to refactor tests to avoid this problem)
810 MYLOGE(
811 "Skipping DumpstateTest.RunCommandAsRootNonUserBuild_withUnroot() "
812 "on test suite\n")
813 return;
814 }
815 if (PropertiesHelper::IsUserBuild()) {
816 ALOGI("Skipping RunCommandAsRootNonUserBuild_withUnroot on user builds\n");
817 return;
818 }
819
820 // Same test as above, but with unroot property set, which will override su availability.
821 SetUnroot(true);
822 DropRoot();
823
824 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
825 CommandOptions::WithTimeout(1).AsRoot().Build()));
826
827 // AsRoot is ineffective.
828 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
829 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
830}
831
Yifan Hong48e83a12017-10-03 14:10:07 -0700832TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnUserBuild) {
833 if (!IsStandalone()) {
834 // TODO: temporarily disabled because it might cause other tests to fail after dropping
835 // to Shell - need to refactor tests to avoid this problem)
836 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
837 return;
838 }
839 if (!PropertiesHelper::IsUserBuild()) {
840 // Emulates user build if necessarily.
841 SetBuildType("user");
842 }
843
844 DropRoot();
845
846 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
847 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
848
849 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
850 EXPECT_THAT(err, StrEq("stderr\n"));
851}
852
853TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild) {
854 if (!IsStandalone()) {
855 // TODO: temporarily disabled because it might cause other tests to fail after dropping
856 // to Shell - need to refactor tests to avoid this problem)
857 MYLOGE("Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
858 return;
859 }
860 if (PropertiesHelper::IsUserBuild()) {
861 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
862 return;
863 }
864
865 DropRoot();
866
867 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
868 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
869
870 EXPECT_THAT(out, StrEq("0\nstdout\n"));
871 EXPECT_THAT(err, StrEq("stderr\n"));
872}
873
Nandana Dutt4b392be2018-11-02 16:17:05 +0000874TEST_F(DumpstateTest, RunCommandAsRootIfAvailableOnDebugBuild_withUnroot) {
875 if (!IsStandalone()) {
876 // TODO: temporarily disabled because it might cause other tests to fail after dropping
877 // to Shell - need to refactor tests to avoid this problem)
878 MYLOGE(
879 "Skipping DumpstateTest.RunCommandAsRootIfAvailableOnDebugBuild_withUnroot() "
880 "on test suite\n")
881 return;
882 }
883 if (PropertiesHelper::IsUserBuild()) {
884 ALOGI("Skipping RunCommandAsRootIfAvailableOnDebugBuild_withUnroot on user builds\n");
885 return;
886 }
887 // Same test as above, but with unroot property set, which will override su availability.
888 SetUnroot(true);
889
890 DropRoot();
891
892 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
893 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
894
895 // It's a userdebug build, so "su root" should be available, but unroot=true overrides it.
896 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
897 EXPECT_THAT(err, StrEq("stderr\n"));
898}
899
Felipe Lemecef02982016-10-03 17:22:22 -0700900TEST_F(DumpstateTest, DumpFileNotFoundNoTitle) {
901 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
902 EXPECT_THAT(out,
903 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
904 EXPECT_THAT(err, IsEmpty());
905}
906
907TEST_F(DumpstateTest, DumpFileNotFoundWithTitle) {
908 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
909 EXPECT_THAT(err, IsEmpty());
Greg Kaiser3a811c12019-05-21 12:48:59 -0700910 // The duration may not get output, depending on how long it takes,
911 // so we just check the prefix.
Felipe Lemecef02982016-10-03 17:22:22 -0700912 EXPECT_THAT(out, StartsWith("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No "
913 "such file or directory\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700914}
915
916TEST_F(DumpstateTest, DumpFileSingleLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700917 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700918 EXPECT_THAT(err, IsEmpty());
919 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
920}
921
922TEST_F(DumpstateTest, DumpFileSingleLineWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700923 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700924 EXPECT_THAT(err, IsEmpty());
925 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
926}
927
928TEST_F(DumpstateTest, DumpFileMultipleLines) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700929 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700930 EXPECT_THAT(err, IsEmpty());
931 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
932}
933
934TEST_F(DumpstateTest, DumpFileMultipleLinesWithNewLine) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700935 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700936 EXPECT_THAT(err, IsEmpty());
937 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
938}
939
940TEST_F(DumpstateTest, DumpFileOnDryRunNoTitle) {
941 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700942 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700943 EXPECT_THAT(err, IsEmpty());
944 EXPECT_THAT(out, IsEmpty());
945}
946
947TEST_F(DumpstateTest, DumpFileOnDryRun) {
948 SetDryRun(true);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700949 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Lemecef02982016-10-03 17:22:22 -0700950 EXPECT_THAT(err, IsEmpty());
Felipe Leme46b85da2016-11-21 17:40:45 -0800951 EXPECT_THAT(
952 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
Nandana Dutt47527b52019-03-29 15:34:36 +0000953 EXPECT_THAT(out, HasSubstr("\n\t(skipped on dry run)\n"));
Felipe Lemecef02982016-10-03 17:22:22 -0700954}
955
Felipe Leme75876a22016-10-27 16:31:27 -0700956TEST_F(DumpstateTest, DumpFileUpdateProgress) {
957 sp<DumpstateListenerMock> listener(new DumpstateListenerMock());
958 ds.listener_ = listener;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700959 SetProgress(0, 30);
Felipe Leme75876a22016-10-27 16:31:27 -0700960
Nandana Duttbabf6c72019-01-15 14:11:12 +0000961 EXPECT_CALL(*listener, onProgress(16)); // 5/30 %
Felipe Leme7447d7c2016-11-03 18:12:22 -0700962 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme75876a22016-10-27 16:31:27 -0700963
Abhijeet Kaured5d6a62019-10-07 15:02:05 +0100964 std::string progress_message = GetProgressMessage(5, 30); // TODO: unhardcode WEIGHT_FILE (5)?
Felipe Leme75876a22016-10-27 16:31:27 -0700965 EXPECT_THAT(err, StrEq(progress_message));
966 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
967
968 ds.listener_.clear();
969}
970
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800971TEST_F(DumpstateTest, DumpPool_withParallelRunEnabled_notNull) {
Rhed Jao1c855122020-07-16 17:37:39 +0800972 SetParallelRun(true);
973 EnableParallelRunIfNeeded();
Rhed Jao4875aa62020-07-20 17:46:29 +0800974 EXPECT_TRUE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +0800975 EXPECT_TRUE(ds.dump_pool_);
976}
977
Rhed Jao1c855122020-07-16 17:37:39 +0800978TEST_F(DumpstateTest, DumpPool_withParallelRunDisabled_isNull) {
979 SetParallelRun(false);
980 EnableParallelRunIfNeeded();
Rhed Jao4875aa62020-07-20 17:46:29 +0800981 EXPECT_FALSE(ds.zip_entry_tasks_);
Rhed Jao1c855122020-07-16 17:37:39 +0800982 EXPECT_FALSE(ds.dump_pool_);
983}
984
Dieter Hsu105ad0c2020-09-29 15:23:33 +0800985class ZippedBugReportStreamTest : public DumpstateBaseTest {
986 public:
987 void SetUp() {
988 DumpstateBaseTest::SetUp();
989 ds_.options_.reset(new Dumpstate::DumpOptions());
990 }
991 void TearDown() {
992 CloseArchive(handle_);
993 }
994
995 // Set bugreport mode and options before here.
996 void GenerateBugreport() {
997 ds_.Initialize();
998 EXPECT_EQ(Dumpstate::RunStatus::OK, ds_.Run(/*calling_uid=*/-1, /*calling_package=*/""));
999 }
1000
1001 // Most bugreports droproot, ensure the file can be opened by shell to verify file content.
1002 void CreateFd(const std::string& path, android::base::unique_fd* out_fd) {
1003 out_fd->reset(TEMP_FAILURE_RETRY(open(path.c_str(),
1004 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1005 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1006 ASSERT_GE(out_fd->get(), 0) << "could not create FD for path " << path;
1007 }
1008
1009 void VerifyEntry(const ZipArchiveHandle archive, const std::string_view entry_name,
1010 ZipEntry* data) {
1011 int32_t e = FindEntry(archive, entry_name, data);
1012 EXPECT_EQ(0, e) << ErrorCodeString(e) << " entry name: " << entry_name;
1013 }
1014
1015 // While testing dumpstate in process, using STDOUT may get confused about
1016 // the internal fd redirection. Redirect to a dedicate fd to save content.
1017 void RedirectOutputToFd(android::base::unique_fd& ufd) {
1018 ds_.open_socket_fn_ = [&](const char*) -> int { return ufd.release(); };
1019 };
1020
1021 Dumpstate& ds_ = Dumpstate::GetInstance();
1022 ZipArchiveHandle handle_;
1023};
1024
Rhed Jaob8b56172021-04-08 20:14:27 +08001025// Generate a quick LimitedOnly report redirected to a file, open it and verify entry exist.
1026TEST_F(ZippedBugReportStreamTest, StreamLimitedOnlyReport) {
1027 std::string out_path = kTestDataPath + "StreamLimitedOnlyReportOut.zip";
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001028 android::base::unique_fd out_fd;
1029 CreateFd(out_path, &out_fd);
Rhed Jaob8b56172021-04-08 20:14:27 +08001030 ds_.options_->limited_only = true;
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001031 ds_.options_->stream_to_socket = true;
1032 RedirectOutputToFd(out_fd);
1033
1034 GenerateBugreport();
1035 OpenArchive(out_path.c_str(), &handle_);
1036
1037 ZipEntry entry;
1038 VerifyEntry(handle_, "main_entry.txt", &entry);
1039 std::string bugreport_txt_name;
1040 bugreport_txt_name.resize(entry.uncompressed_length);
1041 ExtractToMemory(handle_, &entry, reinterpret_cast<uint8_t*>(bugreport_txt_name.data()),
1042 entry.uncompressed_length);
1043 EXPECT_THAT(bugreport_txt_name,
Rhed Jaob8b56172021-04-08 20:14:27 +08001044 testing::ContainsRegex("(bugreport-.+(-[[:digit:]]+){6}\\.txt)"));
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001045 VerifyEntry(handle_, bugreport_txt_name, &entry);
1046}
1047
Felipe Leme7447d7c2016-11-03 18:12:22 -07001048class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -07001049 public:
1050 DumpstateService dss;
1051};
1052
Felipe Leme7447d7c2016-11-03 18:12:22 -07001053class ProgressTest : public DumpstateBaseTest {
1054 public:
1055 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
1056 return Progress(max, growth_factor, path);
1057 }
1058
1059 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
1060 std::string expected_content =
1061 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
1062 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -08001063 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001064 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
1065 }
1066};
1067
1068TEST_F(ProgressTest, SimpleTest) {
1069 Progress progress;
1070 EXPECT_EQ(0, progress.Get());
1071 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1072 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1073
1074 bool max_increased = progress.Inc(1);
1075 EXPECT_EQ(1, progress.Get());
1076 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1077 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1078 EXPECT_FALSE(max_increased);
1079
1080 // Ignore negative increase.
1081 max_increased = progress.Inc(-1);
1082 EXPECT_EQ(1, progress.Get());
1083 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1084 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1085 EXPECT_FALSE(max_increased);
1086}
1087
1088TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
1089 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1090 EXPECT_EQ(0, progress.Get());
1091 EXPECT_EQ(10, progress.GetInitialMax());
1092 EXPECT_EQ(10, progress.GetMax());
1093
1094 // No increase
1095 bool max_increased = progress.Inc(10);
1096 EXPECT_EQ(10, progress.Get());
1097 EXPECT_EQ(10, progress.GetMax());
1098 EXPECT_FALSE(max_increased);
1099
1100 // Increase, with new value < max*20%
1101 max_increased = progress.Inc(1);
1102 EXPECT_EQ(11, progress.Get());
1103 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
1104 EXPECT_TRUE(max_increased);
1105}
1106
1107TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
1108 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1109 EXPECT_EQ(0, progress.Get());
1110 EXPECT_EQ(10, progress.GetInitialMax());
1111 EXPECT_EQ(10, progress.GetMax());
1112
1113 // No increase
1114 bool max_increased = progress.Inc(10);
1115 EXPECT_EQ(10, progress.Get());
1116 EXPECT_EQ(10, progress.GetMax());
1117 EXPECT_FALSE(max_increased);
1118
1119 // Increase, with new value > max*20%
1120 max_increased = progress.Inc(5);
1121 EXPECT_EQ(15, progress.Get());
1122 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
1123 EXPECT_TRUE(max_increased);
1124}
1125
1126TEST_F(ProgressTest, InvalidPath) {
1127 Progress progress("/devil/null");
1128 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1129}
1130
1131TEST_F(ProgressTest, EmptyFile) {
1132 Progress progress(CopyTextFileFixture("empty-file.txt"));
1133 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1134}
1135
1136TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
1137 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
1138 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1139}
1140
1141TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
1142 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
1143 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1144}
1145
1146TEST_F(ProgressTest, InvalidLineBothNAN) {
1147 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
1148 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1149}
1150
1151TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
1152 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
1153 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1154}
1155
1156TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
1157 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
1158 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1159}
1160
1161TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
1162 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
1163 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1164}
1165
1166TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
1167 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
1168 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1169}
1170
1171// Tests stats are properly saved when the file does not exists.
1172TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001173 if (!IsStandalone()) {
1174 // TODO: temporarily disabled because it's failing when running as suite
1175 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
1176 return;
1177 }
1178
Felipe Leme7447d7c2016-11-03 18:12:22 -07001179 std::string path = kTestDataPath + "FirstTime.txt";
1180 android::base::RemoveFileIfExists(path);
1181
1182 Progress run1(path);
1183 EXPECT_EQ(0, run1.Get());
1184 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
1185 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1186
1187 bool max_increased = run1.Inc(20);
1188 EXPECT_EQ(20, run1.Get());
1189 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1190 EXPECT_FALSE(max_increased);
1191
1192 run1.Save();
1193 AssertStats(path, 1, 20);
1194}
1195
1196// Tests what happens when the persistent settings contains the average duration of 1 run.
1197// Data on file is 1 run and 109 average.
1198TEST_F(ProgressTest, SecondTime) {
1199 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
1200
1201 Progress run1 = GetInstance(-42, 1.2, path);
1202 EXPECT_EQ(0, run1.Get());
1203 EXPECT_EQ(10, run1.GetInitialMax());
1204 EXPECT_EQ(10, run1.GetMax());
1205
1206 bool max_increased = run1.Inc(20);
1207 EXPECT_EQ(20, run1.Get());
1208 EXPECT_EQ(24, run1.GetMax());
1209 EXPECT_TRUE(max_increased);
1210
1211 // Average now is 2 runs and (10 + 20)/ 2 = 15
1212 run1.Save();
1213 AssertStats(path, 2, 15);
1214
1215 Progress run2 = GetInstance(-42, 1.2, path);
1216 EXPECT_EQ(0, run2.Get());
1217 EXPECT_EQ(15, run2.GetInitialMax());
1218 EXPECT_EQ(15, run2.GetMax());
1219
1220 max_increased = run2.Inc(25);
1221 EXPECT_EQ(25, run2.Get());
1222 EXPECT_EQ(30, run2.GetMax());
1223 EXPECT_TRUE(max_increased);
1224
1225 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
1226 run2.Save();
1227 AssertStats(path, 3, 18);
1228
1229 Progress run3 = GetInstance(-42, 1.2, path);
1230 EXPECT_EQ(0, run3.Get());
1231 EXPECT_EQ(18, run3.GetInitialMax());
1232 EXPECT_EQ(18, run3.GetMax());
1233
1234 // Make sure average decreases as well
1235 max_increased = run3.Inc(5);
1236 EXPECT_EQ(5, run3.Get());
1237 EXPECT_EQ(18, run3.GetMax());
1238 EXPECT_FALSE(max_increased);
1239
1240 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
1241 run3.Save();
1242 AssertStats(path, 4, 14);
1243}
1244
1245// Tests what happens when the persistent settings contains the average duration of 2 runs.
1246// Data on file is 2 runs and 15 average.
1247TEST_F(ProgressTest, ThirdTime) {
1248 std::string path = CopyTextFileFixture("stats-two-runs.txt");
1249 AssertStats(path, 2, 15); // Sanity check
1250
1251 Progress run1 = GetInstance(-42, 1.2, path);
1252 EXPECT_EQ(0, run1.Get());
1253 EXPECT_EQ(15, run1.GetInitialMax());
1254 EXPECT_EQ(15, run1.GetMax());
1255
1256 bool max_increased = run1.Inc(20);
1257 EXPECT_EQ(20, run1.Get());
1258 EXPECT_EQ(24, run1.GetMax());
1259 EXPECT_TRUE(max_increased);
1260
1261 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
1262 run1.Save();
1263 AssertStats(path, 3, 16);
1264}
1265
Felipe Leme46b85da2016-11-21 17:40:45 -08001266class DumpstateUtilTest : public DumpstateBaseTest {
1267 public:
1268 void SetUp() {
1269 DumpstateBaseTest::SetUp();
1270 SetDryRun(false);
1271 }
1272
Felipe Leme46b85da2016-11-21 17:40:45 -08001273 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -08001274 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -08001275 }
1276
1277 void CreateFd(const std::string& name) {
1278 path_ = kTestDataPath + name;
1279 MYLOGD("Creating fd for file %s\n", path_.c_str());
1280
1281 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
1282 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1283 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
1284 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
1285 }
1286
1287 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001288 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -08001289 const CommandOptions& options = CommandOptions::DEFAULT) {
1290 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001291 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -08001292 close(fd);
1293
1294 CaptureFdOut();
1295 err = GetCapturedStderr();
1296 return status;
1297 }
1298
1299 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001300 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001301 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001302 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -08001303 close(fd);
1304
1305 CaptureFdOut();
1306 err = GetCapturedStderr();
1307 return status;
1308 }
1309
1310 int fd;
1311
1312 // 'fd` output and `stderr` from the last command ran.
1313 std::string out, err;
1314
1315 private:
1316 std::string path_;
1317};
1318
1319TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -08001320 CreateFd("RunCommandNoArgs.txt");
1321 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001322}
1323
Felipe Lemef0292972016-11-22 13:57:05 -08001324TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001325 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001326 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001327 EXPECT_THAT(out, StrEq("stdout\n"));
1328 EXPECT_THAT(err, StrEq("stderr\n"));
1329}
1330
Felipe Lemef0292972016-11-22 13:57:05 -08001331TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
1332 CreateFd("RunCommandWithNoArgs.txt");
1333 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1334 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
1335 EXPECT_THAT(err, StrEq("stderr\n"));
1336}
1337
Felipe Leme46b85da2016-11-21 17:40:45 -08001338TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
1339 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001340 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001341 EXPECT_THAT(err, IsEmpty());
1342 EXPECT_THAT(out, StrEq("one\n"));
1343}
1344
1345TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
1346 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001347 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001348 EXPECT_THAT(err, IsEmpty());
1349 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
1350}
1351
1352TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
1353 CreateFd("RunCommandWithLoggingMessage.txt");
1354 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -08001355 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -08001356 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
1357 EXPECT_THAT(out, StrEq("stdout\n"));
1358 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
1359}
1360
1361TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
1362 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001363 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
1364 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001365 EXPECT_THAT(out, IsEmpty());
1366 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
1367}
1368
1369TEST_F(DumpstateUtilTest, RunCommandDryRun) {
1370 CreateFd("RunCommandDryRun.txt");
1371 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001372 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1373 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
1374 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
1375 kSimpleCommand.c_str())));
1376 EXPECT_THAT(err, IsEmpty());
1377}
1378
1379TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
1380 CreateFd("RunCommandDryRun.txt");
1381 SetDryRun(true);
1382 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001383 EXPECT_THAT(
1384 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
1385 EXPECT_THAT(err, IsEmpty());
1386}
1387
1388TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
1389 CreateFd("RunCommandDryRunAlways.txt");
1390 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001391 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001392 EXPECT_THAT(out, StrEq("stdout\n"));
1393 EXPECT_THAT(err, StrEq("stderr\n"));
1394}
1395
1396TEST_F(DumpstateUtilTest, RunCommandNotFound) {
1397 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001398 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001399 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
1400 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
1401}
1402
1403TEST_F(DumpstateUtilTest, RunCommandFails) {
1404 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001405 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001406 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
1407 " --exit 42' failed: exit code 42\n"));
1408 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
1409 " --exit 42' failed: exit code 42\n"));
1410}
1411
1412TEST_F(DumpstateUtilTest, RunCommandCrashes) {
1413 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001414 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001415 // We don't know the exit code, so check just the prefix.
1416 EXPECT_THAT(
1417 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1418 EXPECT_THAT(
1419 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1420}
1421
Vishnu Nair6921f802017-11-22 09:17:23 -08001422TEST_F(DumpstateUtilTest, RunCommandTimesoutWithSec) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001423 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001424 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1425 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001426 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1427 " --sleep 2' timed out after 1"));
1428 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1429 " --sleep 2' timed out after 1"));
1430}
1431
Vishnu Nair6921f802017-11-22 09:17:23 -08001432TEST_F(DumpstateUtilTest, RunCommandTimesoutWithMsec) {
1433 CreateFd("RunCommandTimesout.txt");
1434 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1435 CommandOptions::WithTimeoutInMs(1000).Build()));
1436 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1437 " --sleep 2' timed out after 1"));
1438 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1439 " --sleep 2' timed out after 1"));
1440}
1441
1442
Felipe Leme46b85da2016-11-21 17:40:45 -08001443TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
1444 CreateFd("RunCommandIsKilled.txt");
1445 CaptureStderr();
1446
1447 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -08001448 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001449 CommandOptions::WithTimeout(100).Always().Build()));
1450 });
1451
1452 // Capture pid and pre-sleep output.
1453 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
1454 std::string err = GetCapturedStderr();
1455 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
1456
1457 CaptureFdOut();
1458 std::vector<std::string> lines = android::base::Split(out, "\n");
1459 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
1460
1461 int pid = atoi(lines[0].c_str());
1462 EXPECT_THAT(lines[1], StrEq("stdout line1"));
1463 EXPECT_THAT(lines[2], IsEmpty()); // \n
1464
1465 // Then kill the process.
1466 CaptureFdOut();
1467 CaptureStderr();
1468 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1469 t.join();
1470
1471 // Finally, check output after murder.
1472 CaptureFdOut();
1473 err = GetCapturedStderr();
1474
1475 // out starts with the pid, which is an unknown
1476 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1477 " --pid --sleep 20' failed: killed by signal 15\n"));
1478 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1479 " --pid --sleep 20' failed: killed by signal 15\n"));
1480}
1481
1482TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1483 if (!IsStandalone()) {
1484 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1485 // to Shell - need to refactor tests to avoid this problem)
1486 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1487 return;
1488 }
1489 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001490 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001491 // Emulates user build if necessarily.
1492 SetBuildType("user");
1493 }
1494
1495 DropRoot();
1496
Felipe Lemef0292972016-11-22 13:57:05 -08001497 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001498
1499 // We don't know the exact path of su, so we just check for the 'root ...' commands
1500 EXPECT_THAT(out, StartsWith("Skipping"));
1501 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1502 EXPECT_THAT(err, IsEmpty());
1503}
1504
1505TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1506 if (!IsStandalone()) {
1507 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1508 // to Shell - need to refactor tests to avoid this problem)
1509 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1510 return;
1511 }
1512 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001513 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001514 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1515 return;
1516 }
1517
1518 DropRoot();
1519
Felipe Lemef0292972016-11-22 13:57:05 -08001520 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1521 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001522
1523 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1524 EXPECT_THAT(err, StrEq("stderr\n"));
1525}
Felipe Leme46b85da2016-11-21 17:40:45 -08001526
Yifan Hong48e83a12017-10-03 14:10:07 -07001527
1528TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnUserBuild) {
1529 if (!IsStandalone()) {
1530 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1531 // to Shell - need to refactor tests to avoid this problem)
1532 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
1533 return;
1534 }
1535 CreateFd("RunCommandAsRootIfAvailableOnUserBuild.txt");
1536 if (!PropertiesHelper::IsUserBuild()) {
1537 // Emulates user build if necessarily.
1538 SetBuildType("user");
1539 }
1540
1541 DropRoot();
1542
1543 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1544 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1545
1546 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1547 EXPECT_THAT(err, StrEq("stderr\n"));
1548}
1549
1550TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnDebugBuild) {
1551 if (!IsStandalone()) {
1552 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1553 // to Shell - need to refactor tests to avoid this problem)
1554 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
1555 return;
1556 }
1557 CreateFd("RunCommandAsRootIfAvailableOnDebugBuild.txt");
1558 if (PropertiesHelper::IsUserBuild()) {
1559 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1560 return;
1561 }
1562
1563 DropRoot();
1564
1565 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1566 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1567
1568 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1569 EXPECT_THAT(err, StrEq("stderr\n"));
1570}
1571
Felipe Leme46b85da2016-11-21 17:40:45 -08001572TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1573 if (!IsStandalone()) {
1574 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1575 // to Shell - need to refactor tests to avoid this problem)
1576 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1577 return;
1578 }
1579 CreateFd("RunCommandDropRoot.txt");
1580 // First check root case - only available when running with 'adb root'.
1581 uid_t uid = getuid();
1582 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001583 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001584 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1585 EXPECT_THAT(err, StrEq("stderr\n"));
1586 return;
1587 }
1588 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001589 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001590 CommandOptions::WithTimeout(1).DropRoot().Build()));
1591 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1592 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1593}
1594
Felipe Lemef0292972016-11-22 13:57:05 -08001595TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001596 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001597 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001598 EXPECT_THAT(out,
1599 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1600 EXPECT_THAT(err, IsEmpty());
1601}
1602
Felipe Lemef0292972016-11-22 13:57:05 -08001603TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1604 CreateFd("DumpFileNotFound.txt");
1605 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1606 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1607 "file or directory\n"));
1608 EXPECT_THAT(err, IsEmpty());
1609}
1610
Felipe Leme46b85da2016-11-21 17:40:45 -08001611TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1612 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001613 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001614 EXPECT_THAT(err, IsEmpty());
1615 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1616}
1617
1618TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1619 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001620 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001621 EXPECT_THAT(err, IsEmpty());
1622 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1623}
1624
1625TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1626 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001627 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001628 EXPECT_THAT(err, IsEmpty());
1629 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1630}
1631
1632TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1633 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001634 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001635 EXPECT_THAT(err, IsEmpty());
1636 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1637}
1638
Felipe Lemef0292972016-11-22 13:57:05 -08001639TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1640 CreateFd("DumpFileOnDryRun.txt");
1641 SetDryRun(true);
1642 std::string path = kTestDataPath + "single-line.txt";
1643 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1644 EXPECT_THAT(err, IsEmpty());
1645 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1646}
1647
Felipe Leme46b85da2016-11-21 17:40:45 -08001648TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1649 CreateFd("DumpFileOnDryRun.txt");
1650 SetDryRun(true);
1651 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001652 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001653 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001654 EXPECT_THAT(
1655 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1656 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001657}
Ecco Park61ffcf72016-10-27 15:46:26 -07001658
Rhed Jao27077b12020-07-14 18:38:08 +08001659class DumpPoolTest : public DumpstateBaseTest {
1660 public:
1661 void SetUp() {
Rhed Jao1c855122020-07-16 17:37:39 +08001662 dump_pool_ = std::make_unique<DumpPool>(kTestDataPath);
Rhed Jao27077b12020-07-14 18:38:08 +08001663 DumpstateBaseTest::SetUp();
1664 CreateOutputFile();
1665 }
1666
1667 void CreateOutputFile() {
1668 out_path_ = kTestDataPath + "out.txt";
1669 out_fd_.reset(TEMP_FAILURE_RETRY(open(out_path_.c_str(),
1670 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1671 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1672 ASSERT_GE(out_fd_.get(), 0) << "could not create FD for path "
1673 << out_path_;
1674 }
1675
1676 int getTempFileCounts(const std::string& folder) {
1677 int count = 0;
1678 std::unique_ptr<DIR, decltype(&closedir)> dir_ptr(opendir(folder.c_str()),
1679 &closedir);
1680 if (!dir_ptr) {
1681 return -1;
1682 }
1683 int dir_fd = dirfd(dir_ptr.get());
1684 if (dir_fd < 0) {
1685 return -1;
1686 }
1687
1688 struct dirent* de;
1689 while ((de = readdir(dir_ptr.get()))) {
1690 if (de->d_type != DT_REG) {
1691 continue;
1692 }
1693 std::string file_name(de->d_name);
1694 if (file_name.find(DumpPool::PREFIX_TMPFILE_NAME) != 0) {
1695 continue;
1696 }
1697 count++;
1698 }
1699 return count;
1700 }
1701
Rhed Jao1c855122020-07-16 17:37:39 +08001702 void setLogDuration(bool log_duration) {
1703 dump_pool_->setLogDuration(log_duration);
1704 }
1705
1706 std::unique_ptr<DumpPool> dump_pool_;
Rhed Jao27077b12020-07-14 18:38:08 +08001707 android::base::unique_fd out_fd_;
1708 std::string out_path_;
1709};
1710
Rhed Jao1c855122020-07-16 17:37:39 +08001711TEST_F(DumpPoolTest, EnqueueTaskWithFd) {
Rhed Jao27077b12020-07-14 18:38:08 +08001712 auto dump_func_1 = [](int out_fd) {
1713 dprintf(out_fd, "A");
1714 };
1715 auto dump_func_2 = [](int out_fd) {
1716 dprintf(out_fd, "B");
1717 sleep(1);
1718 };
1719 auto dump_func_3 = [](int out_fd) {
1720 dprintf(out_fd, "C");
1721 };
Rhed Jao1c855122020-07-16 17:37:39 +08001722 setLogDuration(/* log_duration = */false);
Chris Morinbc223142022-02-04 14:17:11 -08001723 auto t1 = dump_pool_->enqueueTaskWithFd("", dump_func_1, std::placeholders::_1);
1724 auto t2 = dump_pool_->enqueueTaskWithFd("", dump_func_2, std::placeholders::_1);
1725 auto t3 = dump_pool_->enqueueTaskWithFd("", dump_func_3, std::placeholders::_1);
Rhed Jao27077b12020-07-14 18:38:08 +08001726
Chris Morinbc223142022-02-04 14:17:11 -08001727 WaitForTask(std::move(t1), "", out_fd_.get());
1728 WaitForTask(std::move(t2), "", out_fd_.get());
1729 WaitForTask(std::move(t3), "", out_fd_.get());
Rhed Jao27077b12020-07-14 18:38:08 +08001730
1731 std::string result;
1732 ReadFileToString(out_path_, &result);
1733 EXPECT_THAT(result, StrEq("A\nB\nC\n"));
1734 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao1c855122020-07-16 17:37:39 +08001735}
1736
1737TEST_F(DumpPoolTest, EnqueueTask_withDurationLog) {
1738 bool run_1 = false;
1739 auto dump_func_1 = [&]() {
1740 run_1 = true;
1741 };
1742
Chris Morinbc223142022-02-04 14:17:11 -08001743 auto t1 = dump_pool_->enqueueTask(/* duration_title = */"1", dump_func_1);
1744 WaitForTask(std::move(t1), "", out_fd_.get());
Rhed Jao1c855122020-07-16 17:37:39 +08001745
1746 std::string result;
1747 ReadFileToString(out_path_, &result);
1748 EXPECT_TRUE(run_1);
1749 EXPECT_THAT(result, StrEq("------ 0.000s was the duration of '1' ------\n"));
1750 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao27077b12020-07-14 18:38:08 +08001751}
1752
Rhed Jao4875aa62020-07-20 17:46:29 +08001753class TaskQueueTest : public DumpstateBaseTest {
1754public:
1755 void SetUp() {
1756 DumpstateBaseTest::SetUp();
1757 }
1758
1759 TaskQueue task_queue_;
1760};
1761
1762TEST_F(TaskQueueTest, runTask) {
1763 bool is_task1_run = false;
1764 bool is_task2_run = false;
1765 auto task_1 = [&](bool task_cancelled) {
1766 if (task_cancelled) {
1767 return;
1768 }
1769 is_task1_run = true;
1770 };
1771 auto task_2 = [&](bool task_cancelled) {
1772 if (task_cancelled) {
1773 return;
1774 }
1775 is_task2_run = true;
1776 };
1777 task_queue_.add(task_1, std::placeholders::_1);
1778 task_queue_.add(task_2, std::placeholders::_1);
1779
1780 task_queue_.run(/* do_cancel = */false);
1781
1782 EXPECT_TRUE(is_task1_run);
1783 EXPECT_TRUE(is_task2_run);
1784}
1785
1786TEST_F(TaskQueueTest, runTask_withCancelled) {
1787 bool is_task1_cancelled = false;
1788 bool is_task2_cancelled = false;
1789 auto task_1 = [&](bool task_cancelled) {
1790 is_task1_cancelled = task_cancelled;
1791 };
1792 auto task_2 = [&](bool task_cancelled) {
1793 is_task2_cancelled = task_cancelled;
1794 };
1795 task_queue_.add(task_1, std::placeholders::_1);
1796 task_queue_.add(task_2, std::placeholders::_1);
1797
1798 task_queue_.run(/* do_cancel = */true);
1799
1800 EXPECT_TRUE(is_task1_cancelled);
1801 EXPECT_TRUE(is_task2_cancelled);
1802}
1803
Rhed Jao27077b12020-07-14 18:38:08 +08001804
Felipe Leme47e9be22016-12-21 15:37:07 -08001805} // namespace dumpstate
1806} // namespace os
1807} // namespace android