2017-10-21 46 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)