我有一个读取日志文件并过滤结果的功能,我想进行测试以确保其正确过滤。
我的代码
import os
import random
import unittest
from unittest.mock import patch, mock_open
__SAMPLE_LOG__ = os.path.join(settings.BASE_DIR, "apps/tests/log_viewer/sample_logs/sample_manager_log.log")
class FilterLog(unittest.TestCase):
def setUp(self):
with open(__SAMPLE_LOG__) as f:
self.sample_data = f.read()
@patch('builtins.open', new_callable = mock_open, read_data = self.sample_data)
def test_filterDate(self, mock_file):
day = '08'
month = '08'
year = '2019'
results = filter_log(filter_by = 'date', day = day, month = month, year = year)
self.assertEqual(open(settings.ACTIVITY_LOG_FILE).read(), self.sample_data)
错误
@patch('builtins.open',new_callable =模拟_open,read_data = self.sample_data)
NameError:名称'self'未定义
我的问题
我应该如何将数据传递到mock_open()
?我觉得在文件顶部放置一个with open() ... read()
是不好的做法,也不能将其设置为类变量(可以吗?),那我有什么选择?
文档中的内容
从the documentation read_data
接收一个字符串,因此我需要以某种方式将文件读取到一个变量中并传递给它。但是读取文件在哪里合适呢?是在模块顶部,在课程开始时还是在setUp()
中?
答案 0 :(得分:0)
这应该有效。我将sample_data带出课堂。
import os
import random
import unittest
from unittest.mock import patch, mock_open
__SAMPLE_LOG__ = os.path.join(settings.BASE_DIR, "apps/tests/log_viewer/sample_logs/sample_manager_log.log")
# read your test data in sample_data
with open(__SAMPLE_LOG__) as f:
sample_data = f.read()
class FilterLog(unittest.TestCase):
@patch('builtins.open', new_callable = mock_open, read_data = sample_data)
def test_filterDate(self, mock_file):
day = '08'
month = '08'
year = '2019'
results = filter_log(filter_by = 'date', day = day, month = month, year = year)
self.assertEqual(open(settings.ACTIVITY_LOG_FILE).read(), sample_data)