python - 如何将文件传递给 unittest.mock.mock_open()?

我有一个读取日志文件和过滤结果的函数,我想测试以确保它过滤正确。

我的代码

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 = mock_open, read_data = self.sample_data)

NameError: name 'self' is not defined


我的问题

我应该如何将数据传递给 mock_open()?我觉得在文件顶部有一个 with open() ... read() 是不好的做法,我也不能把它变成一个类变量(我可以吗?),那么什么是我的选择?


文档说了什么

来自 the documentation read_data 接受一个字符串,所以我需要以某种方式将文件读入一个变量并将其传递进来。但是在哪里读取文件合适呢?在模块的顶部,在类的开头,还是在 setUp() 中?

最佳答案

这应该有效。我把 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)

https://stackoverflow.com/questions/57434428/

相关文章:

msbuild - 旧项目格式忽略 PackageReference 条件

python - 如何在 Python 和 web3.py 中获取 Solidity revert/

css - Angular2 查询生成器模块删除按钮布局

python - matplotlib/seaborn : first and last row c

react-native - 使用 wix react native navigation v3 设

python - 在 Tensorflow 2.0 中卡住和导出 TensorFlow 模型

reactjs - Next.js 状态改变不重新渲染 UI

google-chrome - 引用错误 : expect is not defined

r - 在 R 中根据调整后的生存曲线绘制累积事件

r - 如何确定简单回文 R 代码的时间复杂度?