From 94e64b45989113f40bfc419836ac5ba695e09a02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tuomas=20Lappetel=C3=A4inen?= Date: Sun, 19 Feb 2017 15:44:42 +0200 Subject: [PATCH 1/2] status/code: return 400 on invalid status code Request such as `/status/4!9` caused a `ValueError` exception when trying to cast the status to an int. Now the client is greeted with `400` and a body of `Invalid status code`. Fixes #329. --- httpbin/core.py | 10 ++++++++-- test_httpbin.py | 8 ++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/httpbin/core.py b/httpbin/core.py index e3ca094..50e7524 100644 --- a/httpbin/core.py +++ b/httpbin/core.py @@ -294,7 +294,10 @@ def view_status_code(codes): """Return status code or random status code if more than one are given""" if ',' not in codes: - code = int(codes) + try: + code = int(codes) + except ValueError: + return Response('Invalid status code', status=400) return status_code(code) choices = [] @@ -305,7 +308,10 @@ def view_status_code(codes): else: code, weight = choice.split(':') - choices.append((int(code), float(weight))) + try: + choices.append((int(code), float(weight))) + except ValueError: + return Response('Invalid status code', status=400) code = weighted_choice(choices) diff --git a/test_httpbin.py b/test_httpbin.py index 321a818..edb7ed6 100755 --- a/test_httpbin.py +++ b/test_httpbin.py @@ -373,6 +373,14 @@ class HttpbinTestCase(unittest.TestCase): response = self.app.open(path='/status/418', method=m) self.assertEqual(response.status_code, 418) + def test_status_endpoint_invalid_code(self): + response = self.app.get(path='/status/4!9') + self.assertEqual(response.status_code, 400) + + def test_status_endpoint_invalid_codes(self): + response = self.app.get(path='/status/200,402,foo') + self.assertEqual(response.status_code, 400) + def test_xml_endpoint(self): response = self.app.get(path='/xml') self.assertEqual( From 451a835c142e6c72a0ced7b25186c5f67edb05e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tuomas=20Lappetel=C3=A4inen?= Date: Sun, 19 Feb 2017 15:48:21 +0200 Subject: [PATCH 2/2] README: add a note that /status/code supports multiple codes --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index ca85ba5..3a2bbe9 100644 --- a/README.rst +++ b/README.rst @@ -30,7 +30,7 @@ Endpoint Description `/delete` Returns DELETE data `/gzip`_ Returns gzip-encoded data. `/deflate`_ Returns deflate-encoded data. -`/status/:code`_ Returns given HTTP Status code. +`/status/:code`_ Returns given HTTP Status code or random if more than one are given. `/response-headers`_ Returns given response headers. `/redirect/:n`_ 302 Redirects *n* times. `/redirect-to?url=foo`_ 302 Redirects to the *foo* URL.