test_utils.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (C) 2015 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. #include "android-base/test_utils.h"
  17. #include <fcntl.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <sys/stat.h>
  21. #include <unistd.h>
  22. #include <string>
  23. #include <android-base/file.h>
  24. #include <android-base/logging.h>
  25. CapturedStdFd::CapturedStdFd(int std_fd) : std_fd_(std_fd), old_fd_(-1) {
  26. Start();
  27. }
  28. CapturedStdFd::~CapturedStdFd() {
  29. if (old_fd_ != -1) {
  30. Stop();
  31. }
  32. }
  33. int CapturedStdFd::fd() const {
  34. return temp_file_.fd;
  35. }
  36. std::string CapturedStdFd::str() {
  37. std::string result;
  38. CHECK_EQ(0, TEMP_FAILURE_RETRY(lseek(fd(), 0, SEEK_SET)));
  39. android::base::ReadFdToString(fd(), &result);
  40. return result;
  41. }
  42. void CapturedStdFd::Reset() {
  43. // Do not reset while capturing.
  44. CHECK_EQ(-1, old_fd_);
  45. CHECK_EQ(0, TEMP_FAILURE_RETRY(lseek(fd(), 0, SEEK_SET)));
  46. CHECK_EQ(0, ftruncate(fd(), 0));
  47. }
  48. void CapturedStdFd::Start() {
  49. #if defined(_WIN32)
  50. // On Windows, stderr is often buffered, so make sure it is unbuffered so
  51. // that we can immediately read back what was written to stderr.
  52. if (std_fd_ == STDERR_FILENO) CHECK_EQ(0, setvbuf(stderr, nullptr, _IONBF, 0));
  53. #endif
  54. old_fd_ = dup(std_fd_);
  55. CHECK_NE(-1, old_fd_);
  56. CHECK_NE(-1, dup2(fd(), std_fd_));
  57. }
  58. void CapturedStdFd::Stop() {
  59. CHECK_NE(-1, old_fd_);
  60. CHECK_NE(-1, dup2(old_fd_, std_fd_));
  61. close(old_fd_);
  62. old_fd_ = -1;
  63. // Note: cannot restore prior setvbuf() setting.
  64. }