def test_expires(self):
     get_cached_token = lambda k: token_cache[k]
     token_cache = TokenCache()
     token_cache['key'] = (current_time_millis() + 500, 'token')
     sleep_millis(300)
     token = get_cached_token('key')
     nt.assert_equal('token', token)
     sleep_millis(300)
     nt.assert_equal(1, len(token_cache))                                 # token still in cache, but expired
     nt.assert_raises(KeyError, get_cached_token, 'key')
    def test_singleton_among_threads(self):
        thread1 = Thread(target=self.thread_1)
        thread2 = Thread(target=self.thread_2)
        thread1.start()
        thread2.start()
        thread1.join()
        thread2.join()

        sleep_millis(100)
        cache = TokenCache()
        nt.assert_equal('token', cache['key'])
    def test_evict(self):
        token_cache = TokenCache(500)
        get_cached_token = lambda k: token_cache[k]
        token_cache['key'] = (current_time_millis() + 800, 'token')         # longer enough to pass 1st evict

        sleep_millis(300)                                                   # before 1st evict
        nt.assert_equal('token', get_cached_token('key'))

        sleep_millis(300)                                                   # short enough so not expired
        nt.assert_equal('token', get_cached_token('key'))                   # 1st eviction will not delete

        sleep_millis(600)
        nt.assert_equal(0, len(token_cache))                                # token was evicted in 2nd round.
        nt.assert_raises(KeyError, get_cached_token, 'key')
 def thread_2(self):
     cache = TokenCache()
     sleep_millis(400)
     nt.assert_equal('token', cache['key'])
     sleep_millis(400)
 def thread_1(self):
     cache = TokenCache()
     sleep_millis(200)
     cache['key'] = (current_time_millis()+1000, 'token')
     sleep_millis(400)