blob: 7234d419d699e4414eafa2f29cad2a575de40a81 [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.
Jeff Sharkey9df29d52023-02-06 14:26:30 -07001026// TODO: broken test tracked in b/249983726
1027TEST_F(ZippedBugReportStreamTest, DISABLED_StreamLimitedOnlyReport) {
Rhed Jaob8b56172021-04-08 20:14:27 +08001028 std::string out_path = kTestDataPath + "StreamLimitedOnlyReportOut.zip";
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001029 android::base::unique_fd out_fd;
1030 CreateFd(out_path, &out_fd);
Rhed Jaob8b56172021-04-08 20:14:27 +08001031 ds_.options_->limited_only = true;
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001032 ds_.options_->stream_to_socket = true;
1033 RedirectOutputToFd(out_fd);
1034
1035 GenerateBugreport();
1036 OpenArchive(out_path.c_str(), &handle_);
1037
1038 ZipEntry entry;
1039 VerifyEntry(handle_, "main_entry.txt", &entry);
1040 std::string bugreport_txt_name;
1041 bugreport_txt_name.resize(entry.uncompressed_length);
1042 ExtractToMemory(handle_, &entry, reinterpret_cast<uint8_t*>(bugreport_txt_name.data()),
1043 entry.uncompressed_length);
1044 EXPECT_THAT(bugreport_txt_name,
Rhed Jaob8b56172021-04-08 20:14:27 +08001045 testing::ContainsRegex("(bugreport-.+(-[[:digit:]]+){6}\\.txt)"));
Dieter Hsu105ad0c2020-09-29 15:23:33 +08001046 VerifyEntry(handle_, bugreport_txt_name, &entry);
1047}
1048
Felipe Leme7447d7c2016-11-03 18:12:22 -07001049class DumpstateServiceTest : public DumpstateBaseTest {
Felipe Leme75876a22016-10-27 16:31:27 -07001050 public:
1051 DumpstateService dss;
1052};
1053
Felipe Leme7447d7c2016-11-03 18:12:22 -07001054class ProgressTest : public DumpstateBaseTest {
1055 public:
1056 Progress GetInstance(int32_t max, double growth_factor, const std::string& path = "") {
1057 return Progress(max, growth_factor, path);
1058 }
1059
1060 void AssertStats(const std::string& path, int32_t expected_runs, int32_t expected_average) {
1061 std::string expected_content =
1062 android::base::StringPrintf("%d %d\n", expected_runs, expected_average);
1063 std::string actual_content;
Felipe Leme46b85da2016-11-21 17:40:45 -08001064 ReadFileToString(path, &actual_content);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001065 ASSERT_THAT(actual_content, StrEq(expected_content)) << "invalid stats on " << path;
1066 }
1067};
1068
1069TEST_F(ProgressTest, SimpleTest) {
1070 Progress progress;
1071 EXPECT_EQ(0, progress.Get());
1072 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1073 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1074
1075 bool max_increased = progress.Inc(1);
1076 EXPECT_EQ(1, progress.Get());
1077 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1078 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1079 EXPECT_FALSE(max_increased);
1080
1081 // Ignore negative increase.
1082 max_increased = progress.Inc(-1);
1083 EXPECT_EQ(1, progress.Get());
1084 EXPECT_EQ(Progress::kDefaultMax, progress.GetInitialMax());
1085 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1086 EXPECT_FALSE(max_increased);
1087}
1088
1089TEST_F(ProgressTest, MaxGrowsInsideNewRange) {
1090 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1091 EXPECT_EQ(0, progress.Get());
1092 EXPECT_EQ(10, progress.GetInitialMax());
1093 EXPECT_EQ(10, progress.GetMax());
1094
1095 // No increase
1096 bool max_increased = progress.Inc(10);
1097 EXPECT_EQ(10, progress.Get());
1098 EXPECT_EQ(10, progress.GetMax());
1099 EXPECT_FALSE(max_increased);
1100
1101 // Increase, with new value < max*20%
1102 max_increased = progress.Inc(1);
1103 EXPECT_EQ(11, progress.Get());
1104 EXPECT_EQ(13, progress.GetMax()); // 11 average * 20% growth = 13.2 = 13
1105 EXPECT_TRUE(max_increased);
1106}
1107
1108TEST_F(ProgressTest, MaxGrowsOutsideNewRange) {
1109 Progress progress = GetInstance(10, 1.2); // 20% growth factor
1110 EXPECT_EQ(0, progress.Get());
1111 EXPECT_EQ(10, progress.GetInitialMax());
1112 EXPECT_EQ(10, progress.GetMax());
1113
1114 // No increase
1115 bool max_increased = progress.Inc(10);
1116 EXPECT_EQ(10, progress.Get());
1117 EXPECT_EQ(10, progress.GetMax());
1118 EXPECT_FALSE(max_increased);
1119
1120 // Increase, with new value > max*20%
1121 max_increased = progress.Inc(5);
1122 EXPECT_EQ(15, progress.Get());
1123 EXPECT_EQ(18, progress.GetMax()); // 15 average * 20% growth = 18
1124 EXPECT_TRUE(max_increased);
1125}
1126
1127TEST_F(ProgressTest, InvalidPath) {
1128 Progress progress("/devil/null");
1129 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1130}
1131
1132TEST_F(ProgressTest, EmptyFile) {
1133 Progress progress(CopyTextFileFixture("empty-file.txt"));
1134 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1135}
1136
1137TEST_F(ProgressTest, InvalidLine1stEntryNAN) {
1138 Progress progress(CopyTextFileFixture("stats-invalid-1st-NAN.txt"));
1139 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1140}
1141
1142TEST_F(ProgressTest, InvalidLine2ndEntryNAN) {
1143 Progress progress(CopyTextFileFixture("stats-invalid-2nd-NAN.txt"));
1144 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1145}
1146
1147TEST_F(ProgressTest, InvalidLineBothNAN) {
1148 Progress progress(CopyTextFileFixture("stats-invalid-both-NAN.txt"));
1149 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1150}
1151
1152TEST_F(ProgressTest, InvalidLine1stEntryNegative) {
1153 Progress progress(CopyTextFileFixture("stats-invalid-1st-negative.txt"));
1154 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1155}
1156
1157TEST_F(ProgressTest, InvalidLine2ndEntryNegative) {
1158 Progress progress(CopyTextFileFixture("stats-invalid-2nd-negative.txt"));
1159 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1160}
1161
1162TEST_F(ProgressTest, InvalidLine1stEntryTooBig) {
1163 Progress progress(CopyTextFileFixture("stats-invalid-1st-too-big.txt"));
1164 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1165}
1166
1167TEST_F(ProgressTest, InvalidLine2ndEntryTooBig) {
1168 Progress progress(CopyTextFileFixture("stats-invalid-2nd-too-big.txt"));
1169 EXPECT_EQ(Progress::kDefaultMax, progress.GetMax());
1170}
1171
1172// Tests stats are properly saved when the file does not exists.
1173TEST_F(ProgressTest, FirstTime) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001174 if (!IsStandalone()) {
1175 // TODO: temporarily disabled because it's failing when running as suite
1176 MYLOGE("Skipping ProgressTest.FirstTime() on test suite\n")
1177 return;
1178 }
1179
Felipe Leme7447d7c2016-11-03 18:12:22 -07001180 std::string path = kTestDataPath + "FirstTime.txt";
1181 android::base::RemoveFileIfExists(path);
1182
1183 Progress run1(path);
1184 EXPECT_EQ(0, run1.Get());
1185 EXPECT_EQ(Progress::kDefaultMax, run1.GetInitialMax());
1186 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1187
1188 bool max_increased = run1.Inc(20);
1189 EXPECT_EQ(20, run1.Get());
1190 EXPECT_EQ(Progress::kDefaultMax, run1.GetMax());
1191 EXPECT_FALSE(max_increased);
1192
1193 run1.Save();
1194 AssertStats(path, 1, 20);
1195}
1196
1197// Tests what happens when the persistent settings contains the average duration of 1 run.
1198// Data on file is 1 run and 109 average.
1199TEST_F(ProgressTest, SecondTime) {
1200 std::string path = CopyTextFileFixture("stats-one-run-no-newline.txt");
1201
1202 Progress run1 = GetInstance(-42, 1.2, path);
1203 EXPECT_EQ(0, run1.Get());
1204 EXPECT_EQ(10, run1.GetInitialMax());
1205 EXPECT_EQ(10, run1.GetMax());
1206
1207 bool max_increased = run1.Inc(20);
1208 EXPECT_EQ(20, run1.Get());
1209 EXPECT_EQ(24, run1.GetMax());
1210 EXPECT_TRUE(max_increased);
1211
1212 // Average now is 2 runs and (10 + 20)/ 2 = 15
1213 run1.Save();
1214 AssertStats(path, 2, 15);
1215
1216 Progress run2 = GetInstance(-42, 1.2, path);
1217 EXPECT_EQ(0, run2.Get());
1218 EXPECT_EQ(15, run2.GetInitialMax());
1219 EXPECT_EQ(15, run2.GetMax());
1220
1221 max_increased = run2.Inc(25);
1222 EXPECT_EQ(25, run2.Get());
1223 EXPECT_EQ(30, run2.GetMax());
1224 EXPECT_TRUE(max_increased);
1225
1226 // Average now is 3 runs and (15 * 2 + 25)/ 3 = 18.33 = 18
1227 run2.Save();
1228 AssertStats(path, 3, 18);
1229
1230 Progress run3 = GetInstance(-42, 1.2, path);
1231 EXPECT_EQ(0, run3.Get());
1232 EXPECT_EQ(18, run3.GetInitialMax());
1233 EXPECT_EQ(18, run3.GetMax());
1234
1235 // Make sure average decreases as well
1236 max_increased = run3.Inc(5);
1237 EXPECT_EQ(5, run3.Get());
1238 EXPECT_EQ(18, run3.GetMax());
1239 EXPECT_FALSE(max_increased);
1240
1241 // Average now is 4 runs and (18 * 3 + 5)/ 4 = 14.75 = 14
1242 run3.Save();
1243 AssertStats(path, 4, 14);
1244}
1245
1246// Tests what happens when the persistent settings contains the average duration of 2 runs.
1247// Data on file is 2 runs and 15 average.
1248TEST_F(ProgressTest, ThirdTime) {
1249 std::string path = CopyTextFileFixture("stats-two-runs.txt");
1250 AssertStats(path, 2, 15); // Sanity check
1251
1252 Progress run1 = GetInstance(-42, 1.2, path);
1253 EXPECT_EQ(0, run1.Get());
1254 EXPECT_EQ(15, run1.GetInitialMax());
1255 EXPECT_EQ(15, run1.GetMax());
1256
1257 bool max_increased = run1.Inc(20);
1258 EXPECT_EQ(20, run1.Get());
1259 EXPECT_EQ(24, run1.GetMax());
1260 EXPECT_TRUE(max_increased);
1261
1262 // Average now is 3 runs and (15 * 2 + 20)/ 3 = 16.66 = 16
1263 run1.Save();
1264 AssertStats(path, 3, 16);
1265}
1266
Felipe Leme46b85da2016-11-21 17:40:45 -08001267class DumpstateUtilTest : public DumpstateBaseTest {
1268 public:
1269 void SetUp() {
1270 DumpstateBaseTest::SetUp();
1271 SetDryRun(false);
1272 }
1273
Felipe Leme46b85da2016-11-21 17:40:45 -08001274 void CaptureFdOut() {
Felipe Lemef0292972016-11-22 13:57:05 -08001275 ReadFileToString(path_, &out);
Felipe Leme46b85da2016-11-21 17:40:45 -08001276 }
1277
1278 void CreateFd(const std::string& name) {
1279 path_ = kTestDataPath + name;
1280 MYLOGD("Creating fd for file %s\n", path_.c_str());
1281
1282 fd = TEMP_FAILURE_RETRY(open(path_.c_str(),
1283 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1284 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
1285 ASSERT_GE(fd, 0) << "could not create FD for path " << path_;
1286 }
1287
1288 // Runs a command into the `fd` and capture `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001289 int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme46b85da2016-11-21 17:40:45 -08001290 const CommandOptions& options = CommandOptions::DEFAULT) {
1291 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001292 int status = RunCommandToFd(fd, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -08001293 close(fd);
1294
1295 CaptureFdOut();
1296 err = GetCapturedStderr();
1297 return status;
1298 }
1299
1300 // Dumps a file and into the `fd` and `stderr`.
Felipe Lemef0292972016-11-22 13:57:05 -08001301 int DumpFile(const std::string& title, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001302 CaptureStderr();
Felipe Lemef0292972016-11-22 13:57:05 -08001303 int status = DumpFileToFd(fd, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -08001304 close(fd);
1305
1306 CaptureFdOut();
1307 err = GetCapturedStderr();
1308 return status;
1309 }
1310
1311 int fd;
1312
1313 // 'fd` output and `stderr` from the last command ran.
1314 std::string out, err;
1315
1316 private:
1317 std::string path_;
1318};
1319
1320TEST_F(DumpstateUtilTest, RunCommandNoArgs) {
Felipe Lemef0292972016-11-22 13:57:05 -08001321 CreateFd("RunCommandNoArgs.txt");
1322 EXPECT_EQ(-1, RunCommand("", {}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001323}
1324
Felipe Lemef0292972016-11-22 13:57:05 -08001325TEST_F(DumpstateUtilTest, RunCommandNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001326 CreateFd("RunCommandWithNoArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001327 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001328 EXPECT_THAT(out, StrEq("stdout\n"));
1329 EXPECT_THAT(err, StrEq("stderr\n"));
1330}
1331
Felipe Lemef0292972016-11-22 13:57:05 -08001332TEST_F(DumpstateUtilTest, RunCommandWithTitle) {
1333 CreateFd("RunCommandWithNoArgs.txt");
1334 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1335 EXPECT_THAT(out, StrEq("------ I AM GROOT (" + kSimpleCommand + ") ------\nstdout\n"));
1336 EXPECT_THAT(err, StrEq("stderr\n"));
1337}
1338
Felipe Leme46b85da2016-11-21 17:40:45 -08001339TEST_F(DumpstateUtilTest, RunCommandWithOneArg) {
1340 CreateFd("RunCommandWithOneArg.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001341 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001342 EXPECT_THAT(err, IsEmpty());
1343 EXPECT_THAT(out, StrEq("one\n"));
1344}
1345
1346TEST_F(DumpstateUtilTest, RunCommandWithMultipleArgs) {
1347 CreateFd("RunCommandWithMultipleArgs.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001348 EXPECT_EQ(0, RunCommand("", {kEchoCommand, "one", "is", "the", "loniest", "number"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001349 EXPECT_THAT(err, IsEmpty());
1350 EXPECT_THAT(out, StrEq("one is the loniest number\n"));
1351}
1352
1353TEST_F(DumpstateUtilTest, RunCommandWithLoggingMessage) {
1354 CreateFd("RunCommandWithLoggingMessage.txt");
1355 EXPECT_EQ(
Felipe Lemef0292972016-11-22 13:57:05 -08001356 0, RunCommand("", {kSimpleCommand},
Felipe Leme46b85da2016-11-21 17:40:45 -08001357 CommandOptions::WithTimeout(10).Log("COMMAND, Y U NO LOG FIRST?").Build()));
1358 EXPECT_THAT(out, StrEq("stdout\n"));
1359 EXPECT_THAT(err, StrEq("COMMAND, Y U NO LOG FIRST?stderr\n"));
1360}
1361
1362TEST_F(DumpstateUtilTest, RunCommandRedirectStderr) {
1363 CreateFd("RunCommandRedirectStderr.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001364 EXPECT_EQ(0, RunCommand("", {kSimpleCommand},
1365 CommandOptions::WithTimeout(10).RedirectStderr().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001366 EXPECT_THAT(out, IsEmpty());
1367 EXPECT_THAT(err, StrEq("stdout\nstderr\n"));
1368}
1369
1370TEST_F(DumpstateUtilTest, RunCommandDryRun) {
1371 CreateFd("RunCommandDryRun.txt");
1372 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001373 EXPECT_EQ(0, RunCommand("I AM GROOT", {kSimpleCommand}));
1374 EXPECT_THAT(out, StrEq(android::base::StringPrintf(
1375 "------ I AM GROOT (%s) ------\n\t(skipped on dry run)\n",
1376 kSimpleCommand.c_str())));
1377 EXPECT_THAT(err, IsEmpty());
1378}
1379
1380TEST_F(DumpstateUtilTest, RunCommandDryRunNoTitle) {
1381 CreateFd("RunCommandDryRun.txt");
1382 SetDryRun(true);
1383 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001384 EXPECT_THAT(
1385 out, StrEq(android::base::StringPrintf("%s: skipped on dry run\n", kSimpleCommand.c_str())));
1386 EXPECT_THAT(err, IsEmpty());
1387}
1388
1389TEST_F(DumpstateUtilTest, RunCommandDryRunAlways) {
1390 CreateFd("RunCommandDryRunAlways.txt");
1391 SetDryRun(true);
Felipe Lemef0292972016-11-22 13:57:05 -08001392 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(10).Always().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001393 EXPECT_THAT(out, StrEq("stdout\n"));
1394 EXPECT_THAT(err, StrEq("stderr\n"));
1395}
1396
1397TEST_F(DumpstateUtilTest, RunCommandNotFound) {
1398 CreateFd("RunCommandNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001399 EXPECT_NE(0, RunCommand("", {"/there/cannot/be/such/command"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001400 EXPECT_THAT(out, StartsWith("*** command '/there/cannot/be/such/command' failed: exit code"));
1401 EXPECT_THAT(err, StartsWith("execvp on command '/there/cannot/be/such/command' failed"));
1402}
1403
1404TEST_F(DumpstateUtilTest, RunCommandFails) {
1405 CreateFd("RunCommandFails.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001406 EXPECT_EQ(42, RunCommand("", {kSimpleCommand, "--exit", "42"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001407 EXPECT_THAT(out, StrEq("stdout\n*** command '" + kSimpleCommand +
1408 " --exit 42' failed: exit code 42\n"));
1409 EXPECT_THAT(err, StrEq("stderr\n*** command '" + kSimpleCommand +
1410 " --exit 42' failed: exit code 42\n"));
1411}
1412
1413TEST_F(DumpstateUtilTest, RunCommandCrashes) {
1414 CreateFd("RunCommandCrashes.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001415 EXPECT_NE(0, RunCommand("", {kSimpleCommand, "--crash"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001416 // We don't know the exit code, so check just the prefix.
1417 EXPECT_THAT(
1418 out, StartsWith("stdout\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1419 EXPECT_THAT(
1420 err, StartsWith("stderr\n*** command '" + kSimpleCommand + " --crash' failed: exit code"));
1421}
1422
Vishnu Nair6921f802017-11-22 09:17:23 -08001423TEST_F(DumpstateUtilTest, RunCommandTimesoutWithSec) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001424 CreateFd("RunCommandTimesout.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001425 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1426 CommandOptions::WithTimeout(1).Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001427 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1428 " --sleep 2' timed out after 1"));
1429 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1430 " --sleep 2' timed out after 1"));
1431}
1432
Vishnu Nair6921f802017-11-22 09:17:23 -08001433TEST_F(DumpstateUtilTest, RunCommandTimesoutWithMsec) {
1434 CreateFd("RunCommandTimesout.txt");
1435 EXPECT_EQ(-1, RunCommand("", {kSimpleCommand, "--sleep", "2"},
1436 CommandOptions::WithTimeoutInMs(1000).Build()));
1437 EXPECT_THAT(out, StartsWith("stdout line1\n*** command '" + kSimpleCommand +
1438 " --sleep 2' timed out after 1"));
1439 EXPECT_THAT(err, StartsWith("sleeping for 2s\n*** command '" + kSimpleCommand +
1440 " --sleep 2' timed out after 1"));
1441}
1442
1443
Felipe Leme46b85da2016-11-21 17:40:45 -08001444TEST_F(DumpstateUtilTest, RunCommandIsKilled) {
1445 CreateFd("RunCommandIsKilled.txt");
1446 CaptureStderr();
1447
1448 std::thread t([=]() {
Felipe Lemef0292972016-11-22 13:57:05 -08001449 EXPECT_EQ(SIGTERM, RunCommandToFd(fd, "", {kSimpleCommand, "--pid", "--sleep", "20"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001450 CommandOptions::WithTimeout(100).Always().Build()));
1451 });
1452
1453 // Capture pid and pre-sleep output.
1454 sleep(1); // Wait a little bit to make sure pid and 1st line were printed.
1455 std::string err = GetCapturedStderr();
1456 EXPECT_THAT(err, StrEq("sleeping for 20s\n"));
1457
1458 CaptureFdOut();
1459 std::vector<std::string> lines = android::base::Split(out, "\n");
1460 ASSERT_EQ(3, (int)lines.size()) << "Invalid lines before sleep: " << out;
1461
1462 int pid = atoi(lines[0].c_str());
1463 EXPECT_THAT(lines[1], StrEq("stdout line1"));
1464 EXPECT_THAT(lines[2], IsEmpty()); // \n
1465
1466 // Then kill the process.
1467 CaptureFdOut();
1468 CaptureStderr();
1469 ASSERT_EQ(0, kill(pid, SIGTERM)) << "failed to kill pid " << pid;
1470 t.join();
1471
1472 // Finally, check output after murder.
1473 CaptureFdOut();
1474 err = GetCapturedStderr();
1475
1476 // out starts with the pid, which is an unknown
1477 EXPECT_THAT(out, EndsWith("stdout line1\n*** command '" + kSimpleCommand +
1478 " --pid --sleep 20' failed: killed by signal 15\n"));
1479 EXPECT_THAT(err, StrEq("*** command '" + kSimpleCommand +
1480 " --pid --sleep 20' failed: killed by signal 15\n"));
1481}
1482
1483TEST_F(DumpstateUtilTest, RunCommandAsRootUserBuild) {
1484 if (!IsStandalone()) {
1485 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1486 // to Shell - need to refactor tests to avoid this problem)
1487 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootUserBuild() on test suite\n")
1488 return;
1489 }
1490 CreateFd("RunCommandAsRootUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001491 if (!PropertiesHelper::IsUserBuild()) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001492 // Emulates user build if necessarily.
1493 SetBuildType("user");
1494 }
1495
1496 DropRoot();
1497
Felipe Lemef0292972016-11-22 13:57:05 -08001498 EXPECT_EQ(0, RunCommand("", {kSimpleCommand}, CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme46b85da2016-11-21 17:40:45 -08001499
1500 // We don't know the exact path of su, so we just check for the 'root ...' commands
1501 EXPECT_THAT(out, StartsWith("Skipping"));
1502 EXPECT_THAT(out, EndsWith("root " + kSimpleCommand + "' on user build.\n"));
1503 EXPECT_THAT(err, IsEmpty());
1504}
1505
1506TEST_F(DumpstateUtilTest, RunCommandAsRootNonUserBuild) {
1507 if (!IsStandalone()) {
1508 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1509 // to Shell - need to refactor tests to avoid this problem)
1510 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootNonUserBuild() on test suite\n")
1511 return;
1512 }
1513 CreateFd("RunCommandAsRootNonUserBuild.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001514 if (PropertiesHelper::IsUserBuild()) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001515 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1516 return;
1517 }
1518
1519 DropRoot();
1520
Felipe Lemef0292972016-11-22 13:57:05 -08001521 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1522 CommandOptions::WithTimeout(1).AsRoot().Build()));
Felipe Leme7447d7c2016-11-03 18:12:22 -07001523
1524 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1525 EXPECT_THAT(err, StrEq("stderr\n"));
1526}
Felipe Leme46b85da2016-11-21 17:40:45 -08001527
Yifan Hong48e83a12017-10-03 14:10:07 -07001528
1529TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnUserBuild) {
1530 if (!IsStandalone()) {
1531 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1532 // to Shell - need to refactor tests to avoid this problem)
1533 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnUserBuild() on test suite\n")
1534 return;
1535 }
1536 CreateFd("RunCommandAsRootIfAvailableOnUserBuild.txt");
1537 if (!PropertiesHelper::IsUserBuild()) {
1538 // Emulates user build if necessarily.
1539 SetBuildType("user");
1540 }
1541
1542 DropRoot();
1543
1544 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1545 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1546
1547 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1548 EXPECT_THAT(err, StrEq("stderr\n"));
1549}
1550
1551TEST_F(DumpstateUtilTest, RunCommandAsRootIfAvailableOnDebugBuild) {
1552 if (!IsStandalone()) {
1553 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1554 // to Shell - need to refactor tests to avoid this problem)
1555 MYLOGE("Skipping DumpstateUtilTest.RunCommandAsRootIfAvailableOnDebugBuild() on test suite\n")
1556 return;
1557 }
1558 CreateFd("RunCommandAsRootIfAvailableOnDebugBuild.txt");
1559 if (PropertiesHelper::IsUserBuild()) {
1560 ALOGI("Skipping RunCommandAsRootNonUserBuild on user builds\n");
1561 return;
1562 }
1563
1564 DropRoot();
1565
1566 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
1567 CommandOptions::WithTimeout(1).AsRootIfAvailable().Build()));
1568
1569 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1570 EXPECT_THAT(err, StrEq("stderr\n"));
1571}
1572
Felipe Leme46b85da2016-11-21 17:40:45 -08001573TEST_F(DumpstateUtilTest, RunCommandDropRoot) {
1574 if (!IsStandalone()) {
1575 // TODO: temporarily disabled because it might cause other tests to fail after dropping
1576 // to Shell - need to refactor tests to avoid this problem)
1577 MYLOGE("Skipping DumpstateUtilTest.RunCommandDropRoot() on test suite\n")
1578 return;
1579 }
1580 CreateFd("RunCommandDropRoot.txt");
1581 // First check root case - only available when running with 'adb root'.
1582 uid_t uid = getuid();
1583 if (uid == 0) {
Felipe Lemef0292972016-11-22 13:57:05 -08001584 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"}));
Felipe Leme46b85da2016-11-21 17:40:45 -08001585 EXPECT_THAT(out, StrEq("0\nstdout\n"));
1586 EXPECT_THAT(err, StrEq("stderr\n"));
1587 return;
1588 }
1589 // Then run dropping root.
Felipe Lemef0292972016-11-22 13:57:05 -08001590 EXPECT_EQ(0, RunCommand("", {kSimpleCommand, "--uid"},
Felipe Leme46b85da2016-11-21 17:40:45 -08001591 CommandOptions::WithTimeout(1).DropRoot().Build()));
1592 EXPECT_THAT(out, StrEq("2000\nstdout\n"));
1593 EXPECT_THAT(err, StrEq("drop_root_user(): already running as Shell\nstderr\n"));
1594}
1595
Felipe Lemef0292972016-11-22 13:57:05 -08001596TEST_F(DumpstateUtilTest, DumpFileNotFoundNoTitle) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001597 CreateFd("DumpFileNotFound.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001598 EXPECT_EQ(-1, DumpFile("", "/I/cant/believe/I/exist"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001599 EXPECT_THAT(out,
1600 StrEq("*** Error dumping /I/cant/believe/I/exist: No such file or directory\n"));
1601 EXPECT_THAT(err, IsEmpty());
1602}
1603
Felipe Lemef0292972016-11-22 13:57:05 -08001604TEST_F(DumpstateUtilTest, DumpFileNotFoundWithTitle) {
1605 CreateFd("DumpFileNotFound.txt");
1606 EXPECT_EQ(-1, DumpFile("Y U NO EXIST?", "/I/cant/believe/I/exist"));
1607 EXPECT_THAT(out, StrEq("*** Error dumping /I/cant/believe/I/exist (Y U NO EXIST?): No such "
1608 "file or directory\n"));
1609 EXPECT_THAT(err, IsEmpty());
1610}
1611
Felipe Leme46b85da2016-11-21 17:40:45 -08001612TEST_F(DumpstateUtilTest, DumpFileSingleLine) {
1613 CreateFd("DumpFileSingleLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001614 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001615 EXPECT_THAT(err, IsEmpty());
1616 EXPECT_THAT(out, StrEq("I AM LINE1\n")); // dumpstate adds missing newline
1617}
1618
1619TEST_F(DumpstateUtilTest, DumpFileSingleLineWithNewLine) {
1620 CreateFd("DumpFileSingleLineWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001621 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001622 EXPECT_THAT(err, IsEmpty());
1623 EXPECT_THAT(out, StrEq("I AM LINE1\n"));
1624}
1625
1626TEST_F(DumpstateUtilTest, DumpFileMultipleLines) {
1627 CreateFd("DumpFileMultipleLines.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001628 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001629 EXPECT_THAT(err, IsEmpty());
1630 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1631}
1632
1633TEST_F(DumpstateUtilTest, DumpFileMultipleLinesWithNewLine) {
1634 CreateFd("DumpFileMultipleLinesWithNewLine.txt");
Felipe Lemef0292972016-11-22 13:57:05 -08001635 EXPECT_EQ(0, DumpFile("", kTestDataPath + "multiple-lines-with-newline.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001636 EXPECT_THAT(err, IsEmpty());
1637 EXPECT_THAT(out, StrEq("I AM LINE1\nI AM LINE2\nI AM LINE3\n"));
1638}
1639
Felipe Lemef0292972016-11-22 13:57:05 -08001640TEST_F(DumpstateUtilTest, DumpFileOnDryRunNoTitle) {
1641 CreateFd("DumpFileOnDryRun.txt");
1642 SetDryRun(true);
1643 std::string path = kTestDataPath + "single-line.txt";
1644 EXPECT_EQ(0, DumpFile("", kTestDataPath + "single-line.txt"));
1645 EXPECT_THAT(err, IsEmpty());
1646 EXPECT_THAT(out, StrEq(path + ": skipped on dry run\n"));
1647}
1648
Felipe Leme46b85da2016-11-21 17:40:45 -08001649TEST_F(DumpstateUtilTest, DumpFileOnDryRun) {
1650 CreateFd("DumpFileOnDryRun.txt");
1651 SetDryRun(true);
1652 std::string path = kTestDataPath + "single-line.txt";
Felipe Lemef0292972016-11-22 13:57:05 -08001653 EXPECT_EQ(0, DumpFile("Might as well dump. Dump!", kTestDataPath + "single-line.txt"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001654 EXPECT_THAT(err, IsEmpty());
Felipe Lemef0292972016-11-22 13:57:05 -08001655 EXPECT_THAT(
1656 out, StartsWith("------ Might as well dump. Dump! (" + kTestDataPath + "single-line.txt:"));
1657 EXPECT_THAT(out, EndsWith("skipped on dry run\n"));
Felipe Leme46b85da2016-11-21 17:40:45 -08001658}
Ecco Park61ffcf72016-10-27 15:46:26 -07001659
Rhed Jao27077b12020-07-14 18:38:08 +08001660class DumpPoolTest : public DumpstateBaseTest {
1661 public:
1662 void SetUp() {
Rhed Jao1c855122020-07-16 17:37:39 +08001663 dump_pool_ = std::make_unique<DumpPool>(kTestDataPath);
Rhed Jao27077b12020-07-14 18:38:08 +08001664 DumpstateBaseTest::SetUp();
1665 CreateOutputFile();
1666 }
1667
1668 void CreateOutputFile() {
1669 out_path_ = kTestDataPath + "out.txt";
1670 out_fd_.reset(TEMP_FAILURE_RETRY(open(out_path_.c_str(),
1671 O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
1672 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)));
1673 ASSERT_GE(out_fd_.get(), 0) << "could not create FD for path "
1674 << out_path_;
1675 }
1676
1677 int getTempFileCounts(const std::string& folder) {
1678 int count = 0;
1679 std::unique_ptr<DIR, decltype(&closedir)> dir_ptr(opendir(folder.c_str()),
1680 &closedir);
1681 if (!dir_ptr) {
1682 return -1;
1683 }
1684 int dir_fd = dirfd(dir_ptr.get());
1685 if (dir_fd < 0) {
1686 return -1;
1687 }
1688
1689 struct dirent* de;
1690 while ((de = readdir(dir_ptr.get()))) {
1691 if (de->d_type != DT_REG) {
1692 continue;
1693 }
1694 std::string file_name(de->d_name);
1695 if (file_name.find(DumpPool::PREFIX_TMPFILE_NAME) != 0) {
1696 continue;
1697 }
1698 count++;
1699 }
1700 return count;
1701 }
1702
Rhed Jao1c855122020-07-16 17:37:39 +08001703 void setLogDuration(bool log_duration) {
1704 dump_pool_->setLogDuration(log_duration);
1705 }
1706
1707 std::unique_ptr<DumpPool> dump_pool_;
Rhed Jao27077b12020-07-14 18:38:08 +08001708 android::base::unique_fd out_fd_;
1709 std::string out_path_;
1710};
1711
Rhed Jao1c855122020-07-16 17:37:39 +08001712TEST_F(DumpPoolTest, EnqueueTaskWithFd) {
Rhed Jao27077b12020-07-14 18:38:08 +08001713 auto dump_func_1 = [](int out_fd) {
1714 dprintf(out_fd, "A");
1715 };
1716 auto dump_func_2 = [](int out_fd) {
1717 dprintf(out_fd, "B");
1718 sleep(1);
1719 };
1720 auto dump_func_3 = [](int out_fd) {
1721 dprintf(out_fd, "C");
1722 };
Rhed Jao1c855122020-07-16 17:37:39 +08001723 setLogDuration(/* log_duration = */false);
Chris Morinbc223142022-02-04 14:17:11 -08001724 auto t1 = dump_pool_->enqueueTaskWithFd("", dump_func_1, std::placeholders::_1);
1725 auto t2 = dump_pool_->enqueueTaskWithFd("", dump_func_2, std::placeholders::_1);
1726 auto t3 = dump_pool_->enqueueTaskWithFd("", dump_func_3, std::placeholders::_1);
Rhed Jao27077b12020-07-14 18:38:08 +08001727
Chris Morinbc223142022-02-04 14:17:11 -08001728 WaitForTask(std::move(t1), "", out_fd_.get());
1729 WaitForTask(std::move(t2), "", out_fd_.get());
1730 WaitForTask(std::move(t3), "", out_fd_.get());
Rhed Jao27077b12020-07-14 18:38:08 +08001731
1732 std::string result;
1733 ReadFileToString(out_path_, &result);
1734 EXPECT_THAT(result, StrEq("A\nB\nC\n"));
1735 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao1c855122020-07-16 17:37:39 +08001736}
1737
1738TEST_F(DumpPoolTest, EnqueueTask_withDurationLog) {
1739 bool run_1 = false;
1740 auto dump_func_1 = [&]() {
1741 run_1 = true;
1742 };
1743
Chris Morinbc223142022-02-04 14:17:11 -08001744 auto t1 = dump_pool_->enqueueTask(/* duration_title = */"1", dump_func_1);
1745 WaitForTask(std::move(t1), "", out_fd_.get());
Rhed Jao1c855122020-07-16 17:37:39 +08001746
1747 std::string result;
1748 ReadFileToString(out_path_, &result);
1749 EXPECT_TRUE(run_1);
1750 EXPECT_THAT(result, StrEq("------ 0.000s was the duration of '1' ------\n"));
1751 EXPECT_THAT(getTempFileCounts(kTestDataPath), Eq(0));
Rhed Jao27077b12020-07-14 18:38:08 +08001752}
1753
Rhed Jao4875aa62020-07-20 17:46:29 +08001754class TaskQueueTest : public DumpstateBaseTest {
1755public:
1756 void SetUp() {
1757 DumpstateBaseTest::SetUp();
1758 }
1759
1760 TaskQueue task_queue_;
1761};
1762
1763TEST_F(TaskQueueTest, runTask) {
1764 bool is_task1_run = false;
1765 bool is_task2_run = false;
1766 auto task_1 = [&](bool task_cancelled) {
1767 if (task_cancelled) {
1768 return;
1769 }
1770 is_task1_run = true;
1771 };
1772 auto task_2 = [&](bool task_cancelled) {
1773 if (task_cancelled) {
1774 return;
1775 }
1776 is_task2_run = true;
1777 };
1778 task_queue_.add(task_1, std::placeholders::_1);
1779 task_queue_.add(task_2, std::placeholders::_1);
1780
1781 task_queue_.run(/* do_cancel = */false);
1782
1783 EXPECT_TRUE(is_task1_run);
1784 EXPECT_TRUE(is_task2_run);
1785}
1786
1787TEST_F(TaskQueueTest, runTask_withCancelled) {
1788 bool is_task1_cancelled = false;
1789 bool is_task2_cancelled = false;
1790 auto task_1 = [&](bool task_cancelled) {
1791 is_task1_cancelled = task_cancelled;
1792 };
1793 auto task_2 = [&](bool task_cancelled) {
1794 is_task2_cancelled = task_cancelled;
1795 };
1796 task_queue_.add(task_1, std::placeholders::_1);
1797 task_queue_.add(task_2, std::placeholders::_1);
1798
1799 task_queue_.run(/* do_cancel = */true);
1800
1801 EXPECT_TRUE(is_task1_cancelled);
1802 EXPECT_TRUE(is_task2_cancelled);
1803}
1804
Rhed Jao27077b12020-07-14 18:38:08 +08001805
Felipe Leme47e9be22016-12-21 15:37:07 -08001806} // namespace dumpstate
1807} // namespace os
1808} // namespace android