From d0ca1df7e4560cb971b36e1d2fea1f55d8688308 Mon Sep 17 00:00:00 2001 From: masklinn Date: Mon, 15 Aug 2022 21:05:11 +0200 Subject: [PATCH] Add type assertion to the cache lookup Currently if an incorrect type is passed in, it'll raise an error that's anything but clear, either failing in the cache lookup or in the regex application. Instead, make the error clear by checking upfront. Closes #122 --- ua_parser/user_agent_parser.py | 8 ++++++++ ua_parser/user_agent_parser_test.py | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/ua_parser/user_agent_parser.py b/ua_parser/user_agent_parser.py index 2c3d1bc..192d25a 100644 --- a/ua_parser/user_agent_parser.py +++ b/ua_parser/user_agent_parser.py @@ -18,6 +18,7 @@ import os import re +import sys import warnings __author__ = "Lindsey Simon " @@ -218,8 +219,15 @@ def Parse(self, user_agent_string): MAX_CACHE_SIZE = 200 _PARSE_CACHE = {} +_UA_TYPES = str +if sys.version_info < (3,): + _UA_TYPES = (str, unicode) + def _lookup(ua, args): + if not isinstance(ua, _UA_TYPES): + raise TypeError("Expected user agent to be a string, got %r" % ua) + key = (ua, tuple(sorted(args.items()))) entry = _PARSE_CACHE.get(key) if entry is not None: diff --git a/ua_parser/user_agent_parser_test.py b/ua_parser/user_agent_parser_test.py index 6658cb3..9d3384c 100644 --- a/ua_parser/user_agent_parser_test.py +++ b/ua_parser/user_agent_parser_test.py @@ -29,6 +29,7 @@ import os import platform import re +import sys import unittest import warnings import yaml @@ -301,5 +302,26 @@ def test_js_bits_deprecation(self): self.assertEqual(w.category, DeprecationWarning) +class ErrTest(unittest.TestCase): + @unittest.skipIf( + sys.version_info < (3,), "bytes and str are not differentiated in P2" + ) + def test_bytes(self): + with self.assertRaises(TypeError): + user_agent_parser.Parse(b"") + + def test_int(self): + with self.assertRaises(TypeError): + user_agent_parser.Parse(0) + + def test_list(self): + with self.assertRaises(TypeError): + user_agent_parser.Parse([]) + + def test_tuple(self): + with self.assertRaises(TypeError): + user_agent_parser.Parse(()) + + if __name__ == "__main__": unittest.main()