You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

capture.py 1.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. import os
  16. import sys
  17. import tempfile
  18. from contextlib import contextmanager
  19. class Capture():
  20. def start(self):
  21. self._old_stdout = sys.stdout
  22. self._stdout_fd = self._old_stdout.fileno()
  23. self._saved_stdout_fd = os.dup(self._stdout_fd)
  24. self._file = sys.stdout = tempfile.TemporaryFile(mode='w+t')
  25. self.output = ''
  26. os.dup2(self._file.fileno(), self._stdout_fd)
  27. def stop(self):
  28. os.dup2(self._saved_stdout_fd, self._stdout_fd)
  29. os.close(self._saved_stdout_fd)
  30. sys.stdout = self._old_stdout
  31. self._file.seek(0)
  32. self.output = self._file.read()
  33. self._file.close()
  34. @contextmanager
  35. def capture(cap):
  36. cap.start()
  37. try:
  38. yield cap
  39. finally:
  40. cap.stop()
  41. def check_output(output, patterns):
  42. assert output, "Capture output failed!"
  43. for pattern in patterns:
  44. assert output.find(pattern) != -1, "Unexpected output:\n" + output + "\n--- pattern ---\n" + pattern