我寫一個Apache日誌分析腳本返回此輸出Pytest誤差字典輸出
'remote_host': '192.168.0.1', 'apache_status': '403', 'data_transfer': '3985'
我們測試這個劇本我寫單元測試使用pytest
import logparsing_apache
def test_final_report():
output = logparsing_apache.final_report('192.168.0.1 - - [23/Apr/2017:05:54:36 -0400] "GET/HTTP/1.1" 403 3985 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"')
assert output == "'remote_host': '192.168.0.1', 'apache_status': '403', 'data_transfer': '3985'"
雖然運行此腳本,與此錯誤
test_logparsing_apache.py:4:
logparsing_apache.py:25: in final_report
line_dict = apache_output(line)
line = '1'
def apache_output(line):
split_line = line.split()
return {'remote_host': split_line[0],
失敗
logparsing_apache.py:18: IndexError
1 failed, in 0.03 seconds
正如我的腳本返回字典如何使用斷言來驗證它的輸出?
腳本:
import sys
def apache_output(line):
split_line = line.split()
return {'remote_host': split_line[0],
'apache_status': split_line[8],
'data_transfer': split_line[9],
}
def final_report(logfile):
for line in logfile:
line_dict = apache_output(line)
print(line_dict)
if __name__ == "__main__":
if not len(sys.argv) > 1:
print (__doc__)
sys.exit(1)
infile_name = sys.argv[1]
try:
infile = open(infile_name, 'r')
except IOError:
print ("You must specify a valid file to parse")
print (__doc__)
sys.exit(1)
log_report = final_report(infile)
print (log_report)
infile.close()
見https://docs.pytest.org/en/latest/ assert.html#assertions-about-expected-exceptions –
可能的重複[如何正確地聲明在pytest中引發異常?](http://stackoverflow.com/questions/23337471/how-to-properly-assert-這是一個異常得到提高pytest) –
你的錯誤和你的問題是不相關的 – jordanm