2017-08-07 10 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") 

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

だから親指のルールは、メソッドに、または偽のすべての外部依存関係のスタブを模擬することですtest_prototype5.py /テスト中の機能要点は、ロジックを単独でテストすることです。したがって、あなたのケースでは、ファイルを開くことができるかどうかテストするか、開くことができない場合はエラーメッセージを記録します。

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() 
関連する問題