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