简体   繁体   English

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

[英]How can I pass a file to unittest.mock.mock_open()?

I have a function that reads a log file and filters results, and I want to test to make sure it is filtering correctly. 我有一个读取日志文件并筛选结果的功能,并且我想测试以确保其正确筛选。

My code 我的密码

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)


The error 错误

@patch('builtins.open', new_callable = mock_open, read_data = self.sample_data) @patch('builtins.open',new_callable =模拟打开,read_data = self.sample_data)

NameError: name 'self' is not defined NameError:名称“ self”未定义


My question 我的问题

How am I supposed to pass the data into mock_open() ? 我应该如何将数据传递给mock_open() I feel like it's bad practice to have a with open() ... read() at the top of the file, nor can I make this a class variable (can I?), so what are my options? 我觉得在文件顶部with open() ... read()是一种不好的做法,也不能将其设置为类变量(可以吗?),那我有什么选择呢?


What the documentation says 文件说什么

From the documentation read_data takes in a string, so somehow I need to read the file into a variable and pass it in. But where is it appropriate to read the file? 文档中 read_data接受一个字符串,因此我需要以某种方式将文件读取到一个变量中并传递给它。但是读取文件在哪里合适呢? At the top of the module, at the beginning of the class, or in setUp() ? 在模块的顶部,在类的开头,还是在setUp()

This should work. 这应该工作。 I took the sample_data out of 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM