Skip to content

Commit

Permalink
Internal: refactor isinstance-dict to isinstance-Mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
Claus Aichinger authored and msiemens committed Nov 6, 2018
1 parent cc7647a commit e23b831
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
23 changes: 23 additions & 0 deletions tests/test_tinydb.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,29 @@ def test_insert_multiple_with_ids(db):
{'int': 1, 'char': 'c'}]) == [1, 2, 3]


def test_insert_invalid_type_raises_error(db):
with pytest.raises(ValueError, message='Document is not a Mapping'):
db.insert(object()) # object() as an example of a non-mapping-type


def test_insert_valid_mapping_type(db):
from tinydb.database import Mapping

class CustomDocument(Mapping):
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)

db.purge()
db.insert(CustomDocument({'int': 1, 'char': 'a'}))
assert db.count(where('int') == 1) == 1


def test_remove(db):
db.remove(where('char') == 'b')

Expand Down
9 changes: 7 additions & 2 deletions tinydb/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
Contains the :class:`database <tinydb.database.TinyDB>` and
:class:`tables <tinydb.database.Table>` implementation.
"""
# Python 2/3 independent Mapping import
try:
from collections.abc import Mapping
except ImportError:
from collections import Mapping
import warnings

from . import JSONStorage
Expand Down Expand Up @@ -379,8 +384,8 @@ def _get_next_id(self):
return current_id

def _get_doc_id(self, document):
if not isinstance(document, dict):
raise ValueError('Document is not a dictionary')
if not isinstance(document, Mapping):
raise ValueError('Document is not a Mapping')
return self._get_next_id()

def _read(self):
Expand Down

0 comments on commit e23b831

Please sign in to comment.