Skip to content

Commit

Permalink
Make DBPersistence.data setter in sycn with getter + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
arikfr committed Oct 7, 2019
1 parent d44d7cb commit 16fbc5e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
10 changes: 7 additions & 3 deletions redash/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,19 +232,23 @@ class DataSourceGroup(db.Model):
__tablename__ = "data_source_groups"


DESERIALIZED_DATA_ATTR = '_deserialized_data'

class DBPersistence(object):
@property
def data(self):
if self._data is None:
return None

if not hasattr(self, '_deserialized_data'):
self._deserialized_data = json_loads(self._data)
if not hasattr(self, DESERIALIZED_DATA_ATTR):
setattr(self, DESERIALIZED_DATA_ATTR, json_loads(self._data))

return self._deserialized_data

@data.setter
def data(self, data):
if hasattr(self, DESERIALIZED_DATA_ATTR):
delattr(self, DESERIALIZED_DATA_ATTR)
self._data = data


Expand Down
24 changes: 23 additions & 1 deletion tests/models/test_query_results.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
#encoding: utf8
import datetime

from unittest import TestCase
from tests import BaseTestCase
from mock import patch

from redash import models
from redash.models import DBPersistence
from redash.utils import utcnow, json_dumps


Expand Down Expand Up @@ -66,4 +69,23 @@ def test_store_result_does_not_modify_query_update_at(self):

models.QueryResult.store_result(query.org_id, query.data_source, query.query_hash, query.query_text, "", 0, utcnow())

self.assertEqual(original_updated_at, query.updated_at)
self.assertEqual(original_updated_at, query.updated_at)


class TestDBPersistence(TestCase):
def test_updating_data_removes_cached_result(self):
p = DBPersistence()
p.data = '{"test": 1}'
self.assertDictEqual(p.data, {"test": 1})
p.data = '{"test": 2}'
self.assertDictEqual(p.data, {"test": 2})

@patch('redash.models.json_loads')
def test_calls_json_loads_only_once(self, json_loads_patch):
json_loads_patch.return_value = '1'
p = DBPersistence()
json_data = '{"test": 1}'
p.data = json_data
a = p.data
b = p.data
json_loads_patch.assert_called_once_with(json_data)

0 comments on commit 16fbc5e

Please sign in to comment.