我正在尝试为几条路线编写单元测试。数据操作相当密集,并且使服务器CPU受限,并且新数据的检索相当罕见。因此,我将烧瓶缓存用于@cache.memoize
更密集的路线。
鉴于此,我想为测试用例做两件事。
以下是我的单元测试的代码,带有一些注释。
import unittest
from app import create_app
from app.charts.cache import cache
class ChartTests(unittest.TestCase):
def setUp(self):
self.app = create_app('TESTING')
self.context = self.app.app_context()
self.client = self.app.test_client()
self.context.push()
def tearDown(self):
self.context.pop()
def test_routes_cached(self):
""" test that the routes are caching and uncaching correctly """
r1 = self.client.get('/chart/upgrade/')
r2 = self.client.get('/chart/upgrade/')
r3 = self.client.get('/chart/upgrade/?start_date=201404')
self.assertTrue( #R1 is not cached )
self.assertTrue( #R2 is cached )
self.assertFalse(r3.data == r2.data)
update_data(app) # changes the csv. Also uses flask-cache's `clear_cache()` to purge
r_new = self.client.get('/chart/upgrade')
self.assertTrue( #R_NEW is not cached )
self.assertTrue(r_new.data != r1.data)
我的路线相当简单,并且往往遵循以下模式:
@charts.before_request():
def update_data():
charts.data = CSVReader('my_csv')
@charts.route('/upgrade')
@cache.memoize()
def upgrade():
# ... do little fiddles with some data
return jsonify(my_new_data)
如何在单元测试中对路由的缓存状态做出准确的断言?
答案 0 :(得分:1)
最简单的方法就是使用get
method of flask.ext.cache.Cache
:
def test_routes_cached(self):
self.assertTrue(cache.get("/chart/upgrade/") is None)
r1 = self.client.get("/chart/upgrade/")
self.assertTrue(cache.get("/chart/upgrade/") is not None)
# ... snip ...
update_data(app)
self.assertTrue(cache.get("/chart/upgrade/") is None)
r_new = self.client.get("/chart/upgrade/")
self.assertTrue(cache.get("/chart/upgrade/") is not None)
# ... etc. ...