简体   繁体   中英

Python: Mocking a file for unittesting

I am writing a unit test for a function in my script, however I am having trouble creating a mock file. My function takes in a filename and output's it's md5 value.

def md5(file_name):
    #Function to return the md5 value of a file
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

My unittest at the moment:

import mock
class Function_to_test_TestCase(unittest.TestCase):

    def test_filename(self):
        with mock.patch('__main__.open', mock.mock_open(read_data=''), create=True) as m:
            md5_value=my_script.function_to_get_md5_value(m)

However I get the error:

with open(fname, "rb") as f:
TypeError: coercing to Unicode: need string or buffer, MagicMock found

Is this way the correct way to make a mock file with a related mock md5 value? Any advice is appreciated!

May be you should specify read_data as binary? Here is a working example, you can paste it to file and run with unittest:

import hashlib
from unittest import TestCase

import mock


def md5(file_name):
    hash_md5 = hashlib.md5()
    with open(file_name, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


class MD5TestCase(TestCase):
    def test(self):
        with mock.patch('%s.open' % __name__, mock.mock_open(read_data=b'aaa'), create=True) as m:
            result = md5("lalala")
            self.assertEqual(result, '47bce5c74f589f4867dbd57e9ca9f808')

The answer is based on that answer: How do I mock an open used in a with statement (using the Mock framework in Python)?

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