如何进行单元测试和模拟开放功能

时间:2017-08-07 06:35:56

标签: python function mocking python-unittest

我在过去的6个小时里读过很多文章,但我仍然不理解模拟和单元测试。我想对一个开放函数进行单元测试,我该怎么做呢?

我也很担心,因为我的大部分代码都使用外部文件进行数据导入和操作。我知道我需要嘲笑他们进行测试,但我很难理解如何前进。

请一些建议。提前谢谢

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()

1 个答案:

答案 0 :(得分:0)

因此,经验法则是模拟,存根或伪造所有外部依赖关系到被测试的方法/函数。关键是要孤立地测试逻辑。因此,在您的情况下,您要测试它是否可以打开文件或记录错误消息,如果它无法打开。

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()