因爲我使用Python 3.6編寫函數和類,所以我嘗試儘快編寫單元測試。我正在寫一個簡單的函數來測試一個文件是否存在於用戶指定的位置,看起來像這樣。如何在Python 3.6單元測試期間防止代碼退出
import os
import sys
import unittest
def verify_file_existance(file_path, file_name):
total_name = file_path + file_name
if os.path.isfile(total_name):
return
sys.exit('{}{}{}'.format('FATAL ERROR: ', file_name, 'does not exist'))
用於上述功能的單元測試看起來像
class InputFileTest(unites.TestCase):
def test_verify_file_existance(self):
file_name = 'Test.csv'
file_path = '../../Data/VandV/Input_Reader/'
verify_file_existance(file_path, file_name)
如果該文件存在在期望的位置中,測試成功通過;但是,如果該文件不存在,程序將以致命警告退出。這是我希望程序在正常操作期間的行爲方式;然而,在單元測試中,我希望能夠有目的地放置一條不正確的路徑並將其註冊爲一個成功的測試,以證明該程序符合我的要求。換句話說,在一個測試案例中,我不希望程序退出。單元測試期間有沒有辦法做到這一點?
你有沒有看着['assertRaises'(https://開頭的文檔.python.org/3 /庫/ unittest.html#unittest.TestCase.assertRaises)? – jedwards
[可能是單元測試可能聲明方法調用sys.exit()](https://stackoverflow.com/questions/15672151/is-it-possible-for-a-unit-test -to-斷言說-A-方法通話-SYS-出口) – wwii