简体   繁体   中英

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)

NameError: name 'self' is not defined


My question

How am I supposed to pass the data into 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?


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? At the top of the module, at the beginning of the class, or in setUp() ?

This should work. I took the sample_data out of class.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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