Fix change check on preferences not working for dbs because of random serialization order and a typo in the comparison. Also add test for the change check.

This commit is contained in:
Kovid Goyal 2015-02-21 14:45:12 +05:30
parent 3146735962
commit 45bedfc1a9
2 changed files with 14 additions and 7 deletions

View File

@ -90,7 +90,9 @@ class DBPrefs(dict): # {{{
return json.loads(raw, object_hook=from_json) return json.loads(raw, object_hook=from_json)
def to_raw(self, val): def to_raw(self, val):
return json.dumps(val, indent=2, default=to_json) # sort_keys=True is required so that the serialization of dictionaries is
# not random, which is needed for the changed check in __setitem__
return json.dumps(val, indent=2, default=to_json, sort_keys=True)
def has_setting(self, key): def has_setting(self, key):
return key in self return key in self
@ -110,8 +112,11 @@ class DBPrefs(dict): # {{{
raw = self.to_raw(val) raw = self.to_raw(val)
with self.db.conn: with self.db.conn:
dbraw = self.db.execute('SELECT val FROM preferences WHERE key=?', (key,)).fetchone() dbraw = self.db.execute('SELECT val FROM preferences WHERE key=?', (key,)).fetchone()
if dbraw != raw: if dbraw != (raw,):
self.db.execute('INSERT OR REPLACE INTO preferences (key,val) VALUES (?,?)', (key, raw)) if dbraw is None:
self.db.execute('INSERT INTO preferences (key,val) VALUES (?,?)', (key, raw))
else:
self.db.execute('UPDATE preferences SET val=? WHERE key=?', (raw, key))
dict.__setitem__(self, key, val) dict.__setitem__(self, key, val)
def set(self, key, val): def set(self, key, val):

View File

@ -7,7 +7,6 @@ __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os
from collections import namedtuple from collections import namedtuple
from functools import partial from functools import partial
from io import BytesIO from io import BytesIO
@ -704,7 +703,10 @@ class WritingTest(BaseTest):
prefs['test mutable'] = a prefs['test mutable'] = a
prefs.load_from_db() prefs.load_from_db()
self.assertIn(4, prefs['test mutable']) self.assertIn(4, prefs['test mutable'])
before = os.stat(cache.backend.library_path) changes = []
prefs['test mutable'] = a cache.backend.conn.setupdatehook(lambda typ, dbname, tblname, rowid: changes.append(rowid))
self.assertEqual(before, os.stat(cache.backend.library_path), 'The database was written to despite there being no change in value') prefs['test mutable'] = {str(k):k for k in range(4)}
self.assertEqual(len(changes), 1)
prefs['test mutable'] = {str(k):k for k in range(4)}
self.assertEqual(len(changes), 1, 'The database was written to despite there being no change in value')
# }}} # }}}