简体   繁体   中英

how to unittest and mock for open funtion

I have read many article over the last 6 hours and i still don't understand mocking and unit-testing. I want to unit test a open function, how can i do this correctly?

i am also concerned as the bulk of my code is using external files for data import and manipulation. I understand that i need to mock them for testing, but I am struggling to understand how to move forward.

Some advice please. Thank you in advance

prototype5.py

import os
import sys
import io
import pandas
pandas.set_option('display.width', None)

def openSetupConfig (a):
"""
SUMMARY
Read setup file
    setup file will ONLY hold the file path of the working directory
:param a: str
:return: contents of the file stored as str
"""
try:
    setupConfig = open(a, "r")
    return setupConfig.read()

except Exception as ve:
    ve = (str(ve) + "\n\nPlease ensure setup file " + str(a) + " is available")
    sys.exit(ve)
dirPath = openSetupConfig("Setup.dat")

test_prototype5.py

import prototype5
import unittest

class TEST_openSetupConfig (unittest.TestCase):
"""
Test the openSetupConfig function from the prototype 5 library
"""
def test_open_correct_file(self):
   result = prototype5.openSetupConfig("Setup.dat")
   self.assertTrue(result)


if __name__ == '__main__':
unittest.main()

So the rule of thumb is to mock, stub or fake all external dependencies to the method/function under test. The point is to test the logic in isolation. So in your case you want to test that it can open a file or log an error message if it can't be opened.

import unittest
from mock import patch

from prototype5 import openSetupConfig  # you don't want to run the whole file
import __builtin__  # needed to mock open

def test_openSetupConfig_with_valid_file(self):
    """
    It should return file contents when passed a valid file.
    """
    expect = 'fake_contents'
    with patch('__builtin__.open', return_value=expect) as mock_open:
         actual = openSetupConfig("Setup.dat")
         self.assertEqual(expect, actual)
         mock_open.assert_called()

@patch('prototype5.sys.exit')
def test_openSetupConfig_with_invalid_file(self, mock_exit):
    """
    It should log an error and exit when passed an invalid file.
    """
    with patch('__builtin__.open', side_effect=FileNotFoundError) as mock_open:
        openSetupConfig('foo')
        mock_exit.assert_called()

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