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

How can I pass a file to 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() 是不好的做法,我也不能把它变成一个 class 变量(可以吗?),那么我有什么选择?


文档内容

From the documentation read_data 接受一个字符串,所以我需要以某种方式将文件读入一个变量并传入。但是在哪里读取文件合适?在模块的顶部,在 class 的开头,或者在 setUp()?

这应该有效。我从 class.

中取出 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)