• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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# ==============================================================================
15import os
16import sys
17import tempfile
18from contextlib import contextmanager
19
20class Capture():
21    def start(self):
22        self._old_stdout = sys.stdout
23        self._stdout_fd = self._old_stdout.fileno()
24        self._saved_stdout_fd = os.dup(self._stdout_fd)
25        self._file = sys.stdout = tempfile.TemporaryFile(mode='w+t')
26        self.output = ''
27        os.dup2(self._file.fileno(), self._stdout_fd)
28
29    def stop(self):
30        os.dup2(self._saved_stdout_fd, self._stdout_fd)
31        os.close(self._saved_stdout_fd)
32        sys.stdout = self._old_stdout
33        self._file.seek(0)
34        self.output = self._file.read()
35        self._file.close()
36
37@contextmanager
38def capture(cap):
39    cap.start()
40    try:
41        yield cap
42    finally:
43        cap.stop()
44
45def check_output(output, patterns):
46    assert output, "Capture output failed!"
47    for pattern in patterns:
48        assert output.find(pattern) != -1, "Unexpected output:\n" + output + "\n--- pattern ---\n" + pattern
49