案例:我有以下python程序。我需要进行单元测试。我不明白如何针对以下问题进行单元测试。
import ...
permitted_ip = ["127.0.0.1", "10.0.0.1", "10.0.0.2"]
class App(BaseHTTPRequestHandler):
# Response for 200
def _set_headers_200(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
# Response for 403
def _set_headers_403(self):
self.send_response(403)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("403: Forbidden!".encode('utf-8'))
# GET request
def do_GET(self):
# Read host IP
client_ip = self.client_address[0]
# Check permitted host and set response accordingly
if client_ip not in permitted_ip:
self._set_headers_403()
return
self._set_headers_200()
self.wfile.write(json.dumps(info).encode('utf-8'))
测试课程
import ...
class TestHandler(TestCase):
def test1(self):
expect = {"banner_id": "Banner-1"}
mock_data = {"banner_id": "Banner-1"}
App.get_scheduled_banner = MagicMock()
App.get_scheduled_banner.return_value = mock_data
actual = requests.get('http://localhost:5000').json()
eq_(actual, expect)
def test2(self):
I want to pass different client IP to check 403 in response
我认为我应该尝试使用http.client,但是失败了。我无法设置源IP来请求服务器感觉到它的客户端是不同的IP