| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
# |
| 4 |
# Copyright 2014 Google Inc. All Rights Reserved. |
| 5 |
# |
| 6 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 |
# you may not use this file except in compliance with the License. |
| 8 |
# You may obtain a copy of the License at |
| 9 |
# |
| 10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
# |
| 12 |
# Unless required by applicable law or agreed to in writing, software |
| 13 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 |
# See the License for the specific language governing permissions and |
| 16 |
# limitations under the License. |
| 17 |
|
| 18 |
"""Discovery document cache tests.""" |
| 19 |
|
| 20 |
import datetime |
| 21 |
import unittest |
| 22 |
from unittest import mock |
| 23 |
|
| 24 |
from googleapiclient.discovery_cache import DISCOVERY_DOC_MAX_AGE |
| 25 |
|
| 26 |
try: |
| 27 |
from googleapiclient.discovery_cache.file_cache import Cache as FileCache |
| 28 |
except ImportError: |
| 29 |
FileCache = None |
| 30 |
|
| 31 |
|
| 32 |
@unittest.skipIf(FileCache is None, "FileCache unavailable.") |
| 33 |
class FileCacheTest(unittest.TestCase): |
| 34 |
@mock.patch( |
| 35 |
"googleapiclient.discovery_cache.file_cache.FILENAME", |
| 36 |
new="google-api-python-client-discovery-doc-tests.cache", |
| 37 |
) |
| 38 |
def test_expiration(self): |
| 39 |
def future_now(): |
| 40 |
return datetime.datetime.now() + datetime.timedelta( |
| 41 |
seconds=DISCOVERY_DOC_MAX_AGE |
| 42 |
) |
| 43 |
|
| 44 |
mocked_datetime = mock.MagicMock() |
| 45 |
mocked_datetime.datetime.now.side_effect = future_now |
| 46 |
cache = FileCache(max_age=DISCOVERY_DOC_MAX_AGE) |
| 47 |
first_url = "url-1" |
| 48 |
first_url_content = "url-1-content" |
| 49 |
cache.set(first_url, first_url_content) |
| 50 |
|
| 51 |
# Make sure the content is cached. |
| 52 |
self.assertEqual(first_url_content, cache.get(first_url)) |
| 53 |
|
| 54 |
# Simulate another `set` call in the future date. |
| 55 |
with mock.patch( |
| 56 |
"googleapiclient.discovery_cache.file_cache.datetime", new=mocked_datetime |
| 57 |
): |
| 58 |
cache.set("url-2", "url-2-content") |
| 59 |
|
| 60 |
# Make sure the content is expired |
| 61 |
self.assertEqual(None, cache.get(first_url)) |