| # |
| # Copyright (C) 2016 The Android Open Source Project |
| # |
| # Licensed under the Apache License, Version 2.0 (the "License"); |
| # you may not use this file except in compliance with the License. |
| # You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, software |
| # distributed under the License is distributed on an "AS IS" BASIS, |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| # See the License for the specific language governing permissions and |
| # limitations under the License. |
| # |
| |
| """Utility functions and classes to help with unit tests.""" |
| |
| |
| import StringIO |
| import sys |
| |
| |
| class OutputCapture(object): |
| """Captures stdout/stderr for easy access to what was printed. |
| |
| Examples: |
| # Easiest is to use this as a context manager. |
| with stubs.OutputCapture() as output: |
| print('foo') |
| print('bar', file=sys.stderr) |
| self.assertEqual('foo\n', output.stdout) |
| self.assertEqual('bar\n', output.stderr) |
| |
| # Can also be used manually if needed. |
| output = stubs.OutputCapture() |
| output.replace_sys_streams() |
| ... |
| output.restore_sys_streams() |
| """ |
| |
| def __init__(self): |
| self._replacement_streams = StringIO.StringIO(), StringIO.StringIO() |
| self._saved_streams = None, None |
| |
| @property |
| def stdout(self): |
| """Returns the stdout string.""" |
| return self._replacement_streams[0].getvalue() |
| |
| @property |
| def stderr(self): |
| """Returns the stderr string.""" |
| return self._replacement_streams[1].getvalue() |
| |
| def replace_sys_streams(self): |
| """Replaces sys.stdout and sys.stderr.""" |
| self._saved_streams = sys.stdout, sys.stderr |
| sys.stdout, sys.stderr = self._replacement_streams |
| |
| def restore_sys_streams(self): |
| """Restores saved sys.stdout and sys.stderr.""" |
| sys.stdout, sys.stderr = self._saved_streams |
| |
| def __enter__(self): |
| self.replace_sys_streams() |
| return self |
| |
| def __exit__(self, exc_type, value, traceback): |
| self.restore_sys_streams() |