diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py index 58ca2a5..d8afce2 100644 --- a/Lib/test/test_urllib.py +++ b/Lib/test/test_urllib.py @@ -1407,8 +1407,12 @@ class RequestTests(unittest.TestCase): Request = urllib.request.Request request = Request("http://www.python.org") self.assertEqual(request.get_method(), 'GET') + request = Request("http://www.python.org", None) + self.assertEqual(request.get_method(), 'GET') request = Request("http://www.python.org", {}) self.assertEqual(request.get_method(), 'POST') + request = Request("http://www.python.org", b'') + self.assertEqual(request.get_method(), 'POST') def test_with_method_arg(self): Request = urllib.request.Request @@ -1424,6 +1428,15 @@ class RequestTests(unittest.TestCase): self.assertEqual(request.get_method(), 'HEAD') + def test_with_invalid_param_type(self): + Request = urllib.request.Request + with self.assertRaisesRegex(TypeError, "url should be of type str"): + request = Request(b"http://www.python.org") + with self.assertRaisesRegex(TypeError, "POST data cannot be of type str"): + request = Request("http://www.python.org", urllib.parse.urlencode({})) + with self.assertRaisesRegex(TypeError,"Key should be type of bytes in POST data"): + request = Request("http://www.python.org", {'abc': 1}) + class URL2PathNameTests(unittest.TestCase): def test_converting_drive_letter(self): diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index e6abf34..6b9ca29 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -353,6 +353,8 @@ class Request: @full_url.setter def full_url(self, url): + if not isinstance(url, str): + raise TypeError("url should be of type str") # unwrap('') --> 'type://host/path' self._full_url = unwrap(url) self._full_url, self.fragment = splittag(self._full_url) @@ -370,6 +372,14 @@ class Request: @data.setter def data(self, data): + if isinstance(data, str): + raise TypeError("POST data cannot be of type str") + + if isinstance(data, dict): + for k in data.keys(): + if not isinstance(k, bytes): + raise TypeError("Key should be type of bytes in POST data") + if data != self._data: self._data = data # issue 16464