2017-10-21 47 views
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() 
+0

什么是你想测试中'MockTreadTest'?到目前为止,它绝对不是测试web脚本。 – Arunmozhi

+0

Web脚本实际上有一些dababase读/写。我想完全测试它们,包括HTTPServer的处理,而无需外部网络访问。 – isexxx

+0

一般来说,它可能不会被称为“单元测试”。 – isexxx

回答

0

MockTreadTest目前没有测试webscript。它现在正在启动一个WSGI服务器,它看起来像try块正在调用一个不存在的脚本。我建议阅读更多关于测试和嘲笑的内容。我认为你正试图在Script类中测试main()函数。这里有一个测试功能来帮助你:

from unittest.mock import TestCase, patch 

# replace `your_script` with the name of your script 
from your_script import Script 

# import the requests object from your script. IMPORTANT, do not do import request 
from your_script import requests 

class ScriptTestCase(TestCase): 
    def test_main(self): 
     script = Script() 
     # Now patch the requests.put function call going to the server 
     with patch('requests.put', return_value="<html>mocked response</html>") as mockput: 
      script.main() # now call the main function <-- this is what we are testing 
      mockput.assert_called_with('http://www.google.co.jp') 

目前,你只是在你的脚本中的响应打印。所以没有办法测试返回值。使用main()函数中的return语句来实现它。然后,您可以按照with区块中的说明进行操作。

response = script.main() 
self.assertIn('mocked response', response.content)