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

前端 未结 3 1358
自闭症患者
自闭症患者 2021-02-20 17:12

I have a custom HTTP request handler that can be simplified to something like this:

# Python 3:
from http import server

c         


        
3条回答
  •  遇见更好的自我
    2021-02-20 18:15

    So this is a little tricky depending on how "deep" you want to go into the BaseHTTPRequestHandler behavior to define your unit test. At the most basic level I think you can use this example from the mock library:

    >>> from mock import MagicMock
    >>> thing = ProductionClass()
    >>> thing.method = MagicMock(return_value=3)
    >>> thing.method(3, 4, 5, key='value')
    3
    >>> thing.method.assert_called_with(3, 4, 5, key='value')
    

    So if you know which methods in the BaseHTTPRequestHandler your class is going to call you could mock the results of those methods to be something acceptable. This can of course get pretty complex depending on how many different types of server responses you want to test.

提交回复
热议问题