0
我想在HTTPServer上單元測試web腳本。如何通過HTTPServer在web腳本中進行mock.patch?
但mock.patch不能通過HTTPServer工作。 它似乎踢在裏面的子過程。
例如,我的網頁腳本有一些外部網頁訪問。
Web腳本:
#!/usr/bin/python3
import requests
class Script:
def main(self):
res = requests.put('http://www.google.co.jp') # get response code 405
print('Content-type: text/html; charset=UTF-8\n')
print(res.content)
if __name__ == '__main__':
Script().main()
而且我的測試腳本似乎不能嘲笑外部網絡訪問。
測試腳本:
import unittest
import requests
from http.server import HTTPServer, CGIHTTPRequestHandler
from threading import Thread
from unittest import TestCase, mock
class MockTreadTest(TestCase):
def test_default(self):
server = HTTPServer(('', 80), CGIHTTPRequestHandler)
server_thread = Thread(target=server.serve_forever)
server_thread.start()
try:
with mock.patch('requests.put', return_value='<html>mocked response</html>') as put:
res = requests.get('http://localhost/cgi-bin/script.py')
self.assertRegex(str(res.content), 'mocked response') # fail
self.assertRegex(put.call_args_list[0][0][0], 'http://www.google.co.jp')
finally:
server.shutdown()
server_thread.join()
if __name__ == "__main__":
unittest.main()
什麼是你想測試中'MockTreadTest'?到目前爲止,它絕對不是測試web腳本。 – Arunmozhi
Web腳本實際上有一些dababase讀/寫。我想完全測試它們,包括HTTPServer的處理,而無需外部網絡訪問。 – isexxx
一般來說,它可能不會被稱爲「單元測試」。 – isexxx