def test_custom_cache(self): reload_module(utils) # re-import with patched settings request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('') user_agent = get_user_agent(request) self.assertIsInstance(user_agent, UserAgent) self.assertIsNone(cache.get(get_cache_key(iphone_ua_string))) self.assertIsInstance(utils.cache.get(get_cache_key(iphone_ua_string)), UserAgent)
def test_get_cache_key(self): self.assertEqual( get_cache_key(long_ua_string), 'django_user_agents.c226ec488bae76c60dd68ad58f03d729', ) self.assertEqual( get_cache_key(iphone_ua_string), 'django_user_agents.00705b9375a0e46e966515fe90f111da', )
def get_user_agent(request): # Tries to get UserAgent objects from cache before constructing a UserAgent # from scratch because parsing regexes.yaml/json (ua-parser) is slow ua_string = request.META.get('HTTP_USER_AGENT', '') key = get_cache_key(ua_string) user_agent = cache.get(key) if user_agent is None: user_agent = parse(ua_string) cache.set(key, user_agent) return user_agent
def test_cache_is_set(self): request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('') user_agent = get_user_agent(request) self.assertIsInstance(user_agent, UserAgent) self.assertIsInstance(cache.get(get_cache_key(iphone_ua_string)), UserAgent)
def tearDown(self): for ua in [iphone_ua_string, ipad_ua_string, long_ua_string]: cache.delete(get_cache_key(ua))
def test_get_cache_key(self): self.assertEqual(get_cache_key(long_ua_string), 'c226ec488bae76c60dd68ad58f03d729') self.assertEqual(get_cache_key(iphone_ua_string), '00705b9375a0e46e966515fe90f111da')