-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtest_minimal.py
More file actions
86 lines (64 loc) · 2.27 KB
/
Copy pathtest_minimal.py
File metadata and controls
86 lines (64 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# coding: UTF-8
import unittest
from unittest.mock import Mock, MagicMock
from flask import Flask
from flask_cache import Cache
from flask_sqlalchemy import SQLAlchemy, Model
from flask_sqlalchemy_cache import CachingQuery, FromCache
Model.query_class = CachingQuery
db = SQLAlchemy()
cache = Cache()
class Country(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def create_app():
app = Flask(__name__)
app.config['CACHE_TYPE'] = 'simple'
db.init_app(app)
cache.init_app(app)
return app
class TestFromCache(unittest.TestCase):
def setUp(self):
self.app = create_app()
self.ctx = self.app.app_context()
self.ctx.push()
db.create_all()
db.session.add(Country(name='Brazil'))
db.session.commit()
def tearDown(self):
db.session.remove()
db.drop_all()
self.ctx.pop()
def test_cache_hit(self):
q = Country.query.order_by(Country.name.desc())
caching_q = q.options(FromCache(cache))
# cache miss
country = caching_q.first()
self.assertEqual('Brazil', country.name)
# add another record
c = Country(name='Germany')
db.session.add(c)
db.session.commit()
# no cache used
self.assertEqual('Germany', q.first().name)
# cache hit
self.assertEqual('Brazil', caching_q.first().name)
def test_no_results(self):
# regression test (check #3) to handle zero results gracefully
Country.query.filter_by(name="URSS").options(FromCache(cache)).all()
def test_empty_results(self):
# An empty result set should not trigger another set
mock_cache = Mock()
mock_cache.get = MagicMock(return_value=[])
Country.query.filter_by(name="URSS").options(FromCache(mock_cache)).all()
mock_cache.set.assert_not_called()
def test_special_chars(self):
unicode_name = u"Côte d'Ivoire"
unicode_country = Country(unicode_name)
db.session.add(unicode_country)
db.session.commit()
Country.query.filter_by(name=unicode_name).options(FromCache(cache)).all()