pytest - 模拟过程和时间

XWi*_*ard 0 python mocking pytest

我有以下方法来测试正确的日志格式。

@patch('sys.stderr', new_callable=StringIO)
    @mock.patch('socket.gethostname', return_value='testing')
    def test_logging(self, gethostname_function, mock_stderr):
        logger = logging.getLogger('project.logging')
        app_logging.init_logging()

        logger.info('testing mesage')


        assert mock_stderr.getvalue() == '{"message": "testing mesage", "levelname": "INFO", "process": 37284, "asctime": "2018-03-01 13:23:33,968", "hostname": "testing"}\n'
Run Code Online (Sandbox Code Playgroud)

格式化程序如下所示:

(message) (levelname) (process) (asctime)
Run Code Online (Sandbox Code Playgroud)

如何模拟日期时间和进程 ID?谢谢

XWi*_*ard 5

好的,

@patch('time.time', mock_time)
@patch('os.getpid', mock_os_pid)
Run Code Online (Sandbox Code Playgroud)

是解决方案。对不起,浪费你的时间:)