Python: How to unit test a custom HTTP request Handler? -


i have custom http request handler can simplified this:

# python 3: http import server  class myhandler(server.basehttprequesthandler):     def do_get(self):         self.send_response(200)         self.send_header("content-type", "text/html")         self.end_headers()          # here's complicated logic done generate html.         # clarity here, replace simple stand-in:         html = "<html><p>hello world</p></html>"          self.wfile.write(html.encode()) 

i'd unit-test handler (i.e. make sure do_get executes without exception) without starting web server. there lightweight way mock simplehttpserver can test code?

here's 1 approach came mock server. note should compatible both python 2 , python 3. issue can't find way access result of get request, @ least test catch exceptions comes across!

try:     # python 2.x     import basehttpserver server     stringio import stringio io except importerror:     # python 3.x     http import server     io import bytesio io   class myhandler(server.basehttprequesthandler):     """custom handler tested"""     def do_get(self):         # print confirm method being called         print("executing do_get") # confirm...          self.send_response(200)         self.send_header("content-type", "text/html")         self.end_headers()          # here's complicated logic done generate html.         # clarity here, replace simple stand-in:         html = "<html><p>hello world</p></html>"          self.wfile.write(html.encode())   def test_handler():     """test custom http request handler mocking server"""     class mockrequest(object):         def makefile(self, *args, **kwargs):             return io(b"get /")      class mockserver(object):         def __init__(self, ip_port, handler):             handler = handler(mockrequest(), ip_port, self)      # request sent here     # , exceptions propagated through.     server = mockserver(('0.0.0.0', 8888), myhandler)   test_handler() 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -