def _mock_output_restore(self):
"""
Mock methods to ensure that stdout and stderr are restored,
after they have been captured.
Return the path to the tempfile that was used to capture the output.
"""
old_stdout = os.dup(1)
old_stderr = os.dup(2)
fd, outfile = tempfile.mkstemp()
mkstemp_patcher = mock.patch("tempfile.mkstemp")
mock_mkstemp = mkstemp_patcher.start()
self.addCleanup(mkstemp_patcher.stop)
mock_mkstemp.return_value = (fd, outfile)
dup_patcher = mock.patch("os.dup")
mock_dup = dup_patcher.start()
self.addCleanup(dup_patcher.stop)
mock_dup.side_effect = lambda fd: {1: old_stdout, 2: old_stderr}[fd]
dup2_patcher = mock.patch("os.dup2", wraps=os.dup2)
mock_dup2 = dup2_patcher.start()
self.addCleanup(dup2_patcher.stop)
return outfile, mock_dup2
评论列表
文章目录