2017-08-07 140 views
0

我在過去的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() 

回答

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