mock server —— 用於自動化測試

來源:互聯網
上載者:User

我們在測試某個模組的時候,該模組會依賴很多外部http server,真實搭建這樣的server有兩個缺點:1、部署維護成本較大,太重不適合自動化測試,2、網路異常、逾時、返回部分結果等特殊情況很難測試到,這時候如果用到mock就很方便了,這裡來介紹一個簡單的mock server。

功能描述

類比http服務, 同時支援get及post訪問方式
提供兩種set方法供使用者自訂http服務response_code及response_content

介面說明

set_code_handler_func(self, func) #設定code處理方法,func接受參數為path,返回狀態代碼,如:path:/index.jsp?galaxy=test return:200
set_content_handler_func(self, func) #設定content處理方法,func接受參數為path,返回page content,如:path:/index.html return:"hello world!"
start(self) # 啟動服務
stop(self) # 停止服務

測試範例

from galaxy.mock_server import http ## initserver = http.MockHTTPServer(port=8000) # 預設使用8000連接埠 ## set handler func'''類比http服務response_code及response_content,對應提供如下兩種set方法,eg:func_code = lambda path: 504func_content = lambda path: "hello world = " + path 以上func接受參數為path,當以post方式請求時path=path + “?” + data'''server.set_code_handler_func(func_code)server.set_content_handler_func(func_content) ## start serverserver.start() ## request code eg:url = "http://10.250.11.57:8000/"query = "url=http://www.taobao.com"try:    req = urllib2.Request(url + urllib.quote(query))    response = urllib2.urlopen(req)    print response.read()    response.close()except Exception, err:    print str(err) ## stop serverserver.stop()

mock_server_http.py

"""Mock HTTP Server.This module builds on BaseHTTPServer by implementing the standard GET and POSTrequests in a fairly straightforward manner."""__version__ = "1.0"__all__ = ["MockHTTPRequestHandler", "MockHTTPServer"]import osimport cgiimport timeimport BaseHTTPServerimport SocketServerimport urllibimport shutiltry:    from cStringIO import StringIOexcept ImportError:    from StringIO import StringIOimport syssys.path.append("/usr/local/atest/atest-1.1.5/lib/")import atest.log as logclass MockHTTPRequestHandler(SocketServer.ThreadingMixIn, BaseHTTPServer.BaseHTTPRequestHandler):    server_version = "MockHTTP/" + __version__    code_handler_func = None    content_handler_func = None    read_timeout = 0    def log_message(self, format, *args):        """override for ignore any log."""        pass    def do_GET(self):        path = urllib.unquote(self.path)        log.debug("path: %s" % path)        self.__response(path)    def do_POST(self):        # Parse the form data posted                form = cgi.FieldStorage(            fp=self.rfile,            headers=self.headers,            environ={'REQUEST_METHOD':'POST',                     'CONTENT_TYPE':self.headers['Content-Type'],                     })        data = [field + "=" + form[field].value for field in form.keys()]        path = "%s?%s" % (self.path, "&".join(data))        log.debug("path: %s" % path)        self.__response(path)    def __response(self, path):        response_code = self.code_handler_func.im_func(path) if self.code_handler_func else 200        response_content = self.content_handler_func.im_func(path) if self.content_handler_func else ""        log.debug("code: %s, content: %s" % (response_code, response_content))        f = StringIO()        f.write(response_content)        length = f.tell()        f.seek(0)        self.send_response(response_code)        self.send_header("Content-type", "text/html")        self.send_header("Content-Length", str(length))        self.end_headers()        if f:            sleep_time = float(self.read_timeout)/1000            log.debug("Sleep %s seconds" % sleep_time)            time.sleep(sleep_time)            shutil.copyfileobj(f, self.wfile)            f.close()        class MockHTTPServer:    def __init__(self, port=8000):        self._port = port        self._code_handler_func = None        self._content_handler_func = None        self._read_timeout = 0        self._pid = 0        def set_code_handler_func(self, func):        """Code handler func, eg:        >>>def func(path): # /index.jsp?galaxy=test        ...    return 200        @param func: lambda x: 200        """        self._code_handler_func = func    def set_content_handler_func(self, func):        """The same as set_code_handler_func"""        self._content_handler_func = func    def set_read_timeout(self, milliseconds):        """Set read timeout"""        self._read_timeout = milliseconds    def _server(self, protocol="HTTP/1.0",               HandlerClass = MockHTTPRequestHandler,               ServerClass = BaseHTTPServer.HTTPServer):        server_address = ('', self._port)        HandlerClass.protocol_version = protocol        HandlerClass.code_handler_func = self._code_handler_func        HandlerClass.content_handler_func = self._content_handler_func        HandlerClass.read_timeout = self._read_timeout        HandlerClass.daemon_threads = True            httpd = ServerClass(server_address, HandlerClass)        sa = httpd.socket.getsockname()        log.info("Serving HTTP on %s port %s ..." % sa)        httpd.serve_forever()    def start(self):        log.info("Start mock http server ...")        child = os.fork()        if not child:            self._server()        self._pid = child    def stop(self):        log.info("Stop mock http server ...")        if self._pid:            os.kill(self._pid, 9)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.