로깅 모듈을 테스트하고 싶습니다. 나는 선을 생성하고 파일에 쓰는 함수가있다. 나는 다음과 같은 코드가 있습니다 :Python의 모의 파일 스트림
class Unit_test(unittest.TestCase):
@patch('my_logger.generate_line', return_value='abc')
def test_write_line_to_log_file(self, arg1):
with patch('my_logger.open_file_stream', return_value=StringIO.StringIO()) as f:
my_logger.write_line_to_log_file(message='message123', pid=1234,
module='abc/def', state='OK',
data={'test_key': 'test_value'})
should_be = 'abc'
f.seek(0)
self.assertEqual(f.readline(), should_be)
가 나는 그것이 파일 스트림에 콘텐츠를 쓰는 경우 패치가 내가 읽고 확인할 수 있습니다 실제 개체를 만들 것이라고 생각 : 나는 다음과 같은 코드로 테스트 기능 write_line_to_log_file
을 시도
def open_file_stream(filename, opt):
return open(filename, opt)
def close_file_stream(f):
f.close()
def write_line_to_log_file(message, pid, module, state, data={}, datatype='AKV'):
file_path = '/path/to/file'
try:
f = open_file_stream(file_path, 'a')
# generate_line only takes the arguments and formats it to string
f.write(generate_line(message, pid, module, state, data, 'AKV') + '\n')
except Exception as e:
raise RuntimeError('Failed to write log line to %s: %s' % (file_path, str(e)))
finally:
f.close()
예상대로 대신 :
AssertionError: <MagicMock name='open_file_stream.readline()' id='3066213676'> != 'abc'
어떻게 수정해야합니까? 또는 콘텐츠가이 MagicMock
개체에 있다면 어떻게 읽어야합니까?
''w''이 적용될 때 마지막 행의 Assert가 작동하지 않지만 모든 것이 작동합니다. 감사! – thecoparyew