diff --git a/ua_parser/user_agent_parser.py b/ua_parser/user_agent_parser.py index 2c3d1bcd..192d25ab 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 6658cb39..9d3384c2 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()