Format the codebase using Black (#2109)
This commit: 1. Formats all of our existing code using `black`. 2. Adds a note about using `black` to `CONTRIBUTING.rst`. 3. Runs `black --check` as part of CI (failing builds that aren't properly formatted).
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -14,36 +14,37 @@ from mongoengine.python_support import StringIO
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
HAS_PIL = True
|
||||
except ImportError:
|
||||
HAS_PIL = False
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
|
||||
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), 'mongoengine.png')
|
||||
TEST_IMAGE2_PATH = os.path.join(os.path.dirname(__file__), 'mongodb_leaf.png')
|
||||
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), "mongoengine.png")
|
||||
TEST_IMAGE2_PATH = os.path.join(os.path.dirname(__file__), "mongodb_leaf.png")
|
||||
|
||||
|
||||
def get_file(path):
|
||||
"""Use a BytesIO instead of a file to allow
|
||||
to have a one-liner and avoid that the file remains opened"""
|
||||
bytes_io = StringIO()
|
||||
with open(path, 'rb') as f:
|
||||
with open(path, "rb") as f:
|
||||
bytes_io.write(f.read())
|
||||
bytes_io.seek(0)
|
||||
return bytes_io
|
||||
|
||||
|
||||
class FileTest(MongoDBTestCase):
|
||||
|
||||
def tearDown(self):
|
||||
self.db.drop_collection('fs.files')
|
||||
self.db.drop_collection('fs.chunks')
|
||||
self.db.drop_collection("fs.files")
|
||||
self.db.drop_collection("fs.chunks")
|
||||
|
||||
def test_file_field_optional(self):
|
||||
# Make sure FileField is optional and not required
|
||||
class DemoFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
DemoFile.objects.create()
|
||||
|
||||
def test_file_fields(self):
|
||||
@@ -55,8 +56,8 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
PutFile.drop_collection()
|
||||
|
||||
text = six.b('Hello, World!')
|
||||
content_type = 'text/plain'
|
||||
text = six.b("Hello, World!")
|
||||
content_type = "text/plain"
|
||||
|
||||
putfile = PutFile()
|
||||
putfile.the_file.put(text, content_type=content_type, filename="hello")
|
||||
@@ -64,7 +65,10 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
result = PutFile.objects.first()
|
||||
self.assertEqual(putfile, result)
|
||||
self.assertEqual("%s" % result.the_file, "<GridFSProxy: hello (%s)>" % result.the_file.grid_id)
|
||||
self.assertEqual(
|
||||
"%s" % result.the_file,
|
||||
"<GridFSProxy: hello (%s)>" % result.the_file.grid_id,
|
||||
)
|
||||
self.assertEqual(result.the_file.read(), text)
|
||||
self.assertEqual(result.the_file.content_type, content_type)
|
||||
result.the_file.delete() # Remove file from GridFS
|
||||
@@ -89,14 +93,15 @@ class FileTest(MongoDBTestCase):
|
||||
def test_file_fields_stream(self):
|
||||
"""Ensure that file fields can be written to and their data retrieved
|
||||
"""
|
||||
|
||||
class StreamFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
StreamFile.drop_collection()
|
||||
|
||||
text = six.b('Hello, World!')
|
||||
more_text = six.b('Foo Bar')
|
||||
content_type = 'text/plain'
|
||||
text = six.b("Hello, World!")
|
||||
more_text = six.b("Foo Bar")
|
||||
content_type = "text/plain"
|
||||
|
||||
streamfile = StreamFile()
|
||||
streamfile.the_file.new_file(content_type=content_type)
|
||||
@@ -124,14 +129,15 @@ class FileTest(MongoDBTestCase):
|
||||
"""Ensure that a file field can be written to after it has been saved as
|
||||
None
|
||||
"""
|
||||
|
||||
class StreamFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
StreamFile.drop_collection()
|
||||
|
||||
text = six.b('Hello, World!')
|
||||
more_text = six.b('Foo Bar')
|
||||
content_type = 'text/plain'
|
||||
text = six.b("Hello, World!")
|
||||
more_text = six.b("Foo Bar")
|
||||
content_type = "text/plain"
|
||||
|
||||
streamfile = StreamFile()
|
||||
streamfile.save()
|
||||
@@ -157,12 +163,11 @@ class FileTest(MongoDBTestCase):
|
||||
self.assertTrue(result.the_file.read() is None)
|
||||
|
||||
def test_file_fields_set(self):
|
||||
|
||||
class SetFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
text = six.b('Hello, World!')
|
||||
more_text = six.b('Foo Bar')
|
||||
text = six.b("Hello, World!")
|
||||
more_text = six.b("Foo Bar")
|
||||
|
||||
SetFile.drop_collection()
|
||||
|
||||
@@ -184,7 +189,6 @@ class FileTest(MongoDBTestCase):
|
||||
result.the_file.delete()
|
||||
|
||||
def test_file_field_no_default(self):
|
||||
|
||||
class GridDocument(Document):
|
||||
the_file = FileField()
|
||||
|
||||
@@ -199,7 +203,7 @@ class FileTest(MongoDBTestCase):
|
||||
doc_a.save()
|
||||
|
||||
doc_b = GridDocument.objects.with_id(doc_a.id)
|
||||
doc_b.the_file.replace(f, filename='doc_b')
|
||||
doc_b.the_file.replace(f, filename="doc_b")
|
||||
doc_b.save()
|
||||
self.assertNotEqual(doc_b.the_file.grid_id, None)
|
||||
|
||||
@@ -208,13 +212,13 @@ class FileTest(MongoDBTestCase):
|
||||
self.assertEqual(doc_b.the_file.grid_id, doc_c.the_file.grid_id)
|
||||
|
||||
# Test with default
|
||||
doc_d = GridDocument(the_file=six.b(''))
|
||||
doc_d = GridDocument(the_file=six.b(""))
|
||||
doc_d.save()
|
||||
|
||||
doc_e = GridDocument.objects.with_id(doc_d.id)
|
||||
self.assertEqual(doc_d.the_file.grid_id, doc_e.the_file.grid_id)
|
||||
|
||||
doc_e.the_file.replace(f, filename='doc_e')
|
||||
doc_e.the_file.replace(f, filename="doc_e")
|
||||
doc_e.save()
|
||||
|
||||
doc_f = GridDocument.objects.with_id(doc_e.id)
|
||||
@@ -222,11 +226,12 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
db = GridDocument._get_db()
|
||||
grid_fs = gridfs.GridFS(db)
|
||||
self.assertEqual(['doc_b', 'doc_e'], grid_fs.list())
|
||||
self.assertEqual(["doc_b", "doc_e"], grid_fs.list())
|
||||
|
||||
def test_file_uniqueness(self):
|
||||
"""Ensure that each instance of a FileField is unique
|
||||
"""
|
||||
|
||||
class TestFile(Document):
|
||||
name = StringField()
|
||||
the_file = FileField()
|
||||
@@ -234,7 +239,7 @@ class FileTest(MongoDBTestCase):
|
||||
# First instance
|
||||
test_file = TestFile()
|
||||
test_file.name = "Hello, World!"
|
||||
test_file.the_file.put(six.b('Hello, World!'))
|
||||
test_file.the_file.put(six.b("Hello, World!"))
|
||||
test_file.save()
|
||||
|
||||
# Second instance
|
||||
@@ -255,20 +260,21 @@ class FileTest(MongoDBTestCase):
|
||||
photo = FileField()
|
||||
|
||||
Animal.drop_collection()
|
||||
marmot = Animal(genus='Marmota', family='Sciuridae')
|
||||
marmot = Animal(genus="Marmota", family="Sciuridae")
|
||||
|
||||
marmot_photo_content = get_file(TEST_IMAGE_PATH) # Retrieve a photo from disk
|
||||
marmot.photo.put(marmot_photo_content, content_type='image/jpeg', foo='bar')
|
||||
marmot.photo.put(marmot_photo_content, content_type="image/jpeg", foo="bar")
|
||||
marmot.photo.close()
|
||||
marmot.save()
|
||||
|
||||
marmot = Animal.objects.get()
|
||||
self.assertEqual(marmot.photo.content_type, 'image/jpeg')
|
||||
self.assertEqual(marmot.photo.foo, 'bar')
|
||||
self.assertEqual(marmot.photo.content_type, "image/jpeg")
|
||||
self.assertEqual(marmot.photo.foo, "bar")
|
||||
|
||||
def test_file_reassigning(self):
|
||||
class TestFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
TestFile.drop_collection()
|
||||
|
||||
test_file = TestFile(the_file=get_file(TEST_IMAGE_PATH)).save()
|
||||
@@ -282,13 +288,15 @@ class FileTest(MongoDBTestCase):
|
||||
def test_file_boolean(self):
|
||||
"""Ensure that a boolean test of a FileField indicates its presence
|
||||
"""
|
||||
|
||||
class TestFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
TestFile.drop_collection()
|
||||
|
||||
test_file = TestFile()
|
||||
self.assertFalse(bool(test_file.the_file))
|
||||
test_file.the_file.put(six.b('Hello, World!'), content_type='text/plain')
|
||||
test_file.the_file.put(six.b("Hello, World!"), content_type="text/plain")
|
||||
test_file.save()
|
||||
self.assertTrue(bool(test_file.the_file))
|
||||
|
||||
@@ -297,6 +305,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_file_cmp(self):
|
||||
"""Test comparing against other types"""
|
||||
|
||||
class TestFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
@@ -305,11 +314,12 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_file_disk_space(self):
|
||||
""" Test disk space usage when we delete/replace a file """
|
||||
|
||||
class TestFile(Document):
|
||||
the_file = FileField()
|
||||
|
||||
text = six.b('Hello, World!')
|
||||
content_type = 'text/plain'
|
||||
text = six.b("Hello, World!")
|
||||
content_type = "text/plain"
|
||||
|
||||
testfile = TestFile()
|
||||
testfile.the_file.put(text, content_type=content_type, filename="hello")
|
||||
@@ -352,7 +362,7 @@ class FileTest(MongoDBTestCase):
|
||||
testfile.the_file.put(text, content_type=content_type, filename="hello")
|
||||
testfile.save()
|
||||
|
||||
text = six.b('Bonjour, World!')
|
||||
text = six.b("Bonjour, World!")
|
||||
testfile.the_file.replace(text, content_type=content_type, filename="hello")
|
||||
testfile.save()
|
||||
|
||||
@@ -370,7 +380,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_image_field(self):
|
||||
if not HAS_PIL:
|
||||
raise SkipTest('PIL not installed')
|
||||
raise SkipTest("PIL not installed")
|
||||
|
||||
class TestImage(Document):
|
||||
image = ImageField()
|
||||
@@ -386,7 +396,9 @@ class FileTest(MongoDBTestCase):
|
||||
t.image.put(f)
|
||||
self.fail("Should have raised an invalidation error")
|
||||
except ValidationError as e:
|
||||
self.assertEqual("%s" % e, "Invalid image: cannot identify image file %s" % f)
|
||||
self.assertEqual(
|
||||
"%s" % e, "Invalid image: cannot identify image file %s" % f
|
||||
)
|
||||
|
||||
t = TestImage()
|
||||
t.image.put(get_file(TEST_IMAGE_PATH))
|
||||
@@ -394,7 +406,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.format, 'PNG')
|
||||
self.assertEqual(t.image.format, "PNG")
|
||||
|
||||
w, h = t.image.size
|
||||
self.assertEqual(w, 371)
|
||||
@@ -404,10 +416,11 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_image_field_reassigning(self):
|
||||
if not HAS_PIL:
|
||||
raise SkipTest('PIL not installed')
|
||||
raise SkipTest("PIL not installed")
|
||||
|
||||
class TestFile(Document):
|
||||
the_file = ImageField()
|
||||
|
||||
TestFile.drop_collection()
|
||||
|
||||
test_file = TestFile(the_file=get_file(TEST_IMAGE_PATH)).save()
|
||||
@@ -420,7 +433,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_image_field_resize(self):
|
||||
if not HAS_PIL:
|
||||
raise SkipTest('PIL not installed')
|
||||
raise SkipTest("PIL not installed")
|
||||
|
||||
class TestImage(Document):
|
||||
image = ImageField(size=(185, 37))
|
||||
@@ -433,7 +446,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.format, 'PNG')
|
||||
self.assertEqual(t.image.format, "PNG")
|
||||
w, h = t.image.size
|
||||
|
||||
self.assertEqual(w, 185)
|
||||
@@ -443,7 +456,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_image_field_resize_force(self):
|
||||
if not HAS_PIL:
|
||||
raise SkipTest('PIL not installed')
|
||||
raise SkipTest("PIL not installed")
|
||||
|
||||
class TestImage(Document):
|
||||
image = ImageField(size=(185, 37, True))
|
||||
@@ -456,7 +469,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.format, 'PNG')
|
||||
self.assertEqual(t.image.format, "PNG")
|
||||
w, h = t.image.size
|
||||
|
||||
self.assertEqual(w, 185)
|
||||
@@ -466,7 +479,7 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
def test_image_field_thumbnail(self):
|
||||
if not HAS_PIL:
|
||||
raise SkipTest('PIL not installed')
|
||||
raise SkipTest("PIL not installed")
|
||||
|
||||
class TestImage(Document):
|
||||
image = ImageField(thumbnail_size=(92, 18))
|
||||
@@ -479,19 +492,18 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.thumbnail.format, 'PNG')
|
||||
self.assertEqual(t.image.thumbnail.format, "PNG")
|
||||
self.assertEqual(t.image.thumbnail.width, 92)
|
||||
self.assertEqual(t.image.thumbnail.height, 18)
|
||||
|
||||
t.image.delete()
|
||||
|
||||
def test_file_multidb(self):
|
||||
register_connection('test_files', 'test_files')
|
||||
register_connection("test_files", "test_files")
|
||||
|
||||
class TestFile(Document):
|
||||
name = StringField()
|
||||
the_file = FileField(db_alias="test_files",
|
||||
collection_name="macumba")
|
||||
the_file = FileField(db_alias="test_files", collection_name="macumba")
|
||||
|
||||
TestFile.drop_collection()
|
||||
|
||||
@@ -502,23 +514,21 @@ class FileTest(MongoDBTestCase):
|
||||
# First instance
|
||||
test_file = TestFile()
|
||||
test_file.name = "Hello, World!"
|
||||
test_file.the_file.put(six.b('Hello, World!'),
|
||||
name="hello.txt")
|
||||
test_file.the_file.put(six.b("Hello, World!"), name="hello.txt")
|
||||
test_file.save()
|
||||
|
||||
data = get_db("test_files").macumba.files.find_one()
|
||||
self.assertEqual(data.get('name'), 'hello.txt')
|
||||
self.assertEqual(data.get("name"), "hello.txt")
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
self.assertEqual(test_file.the_file.read(), six.b('Hello, World!'))
|
||||
self.assertEqual(test_file.the_file.read(), six.b("Hello, World!"))
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
test_file.the_file = six.b('HELLO, WORLD!')
|
||||
test_file.the_file = six.b("HELLO, WORLD!")
|
||||
test_file.save()
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
self.assertEqual(test_file.the_file.read(),
|
||||
six.b('HELLO, WORLD!'))
|
||||
self.assertEqual(test_file.the_file.read(), six.b("HELLO, WORLD!"))
|
||||
|
||||
def test_copyable(self):
|
||||
class PutFile(Document):
|
||||
@@ -526,8 +536,8 @@ class FileTest(MongoDBTestCase):
|
||||
|
||||
PutFile.drop_collection()
|
||||
|
||||
text = six.b('Hello, World!')
|
||||
content_type = 'text/plain'
|
||||
text = six.b("Hello, World!")
|
||||
content_type = "text/plain"
|
||||
|
||||
putfile = PutFile()
|
||||
putfile.the_file.put(text, content_type=content_type)
|
||||
@@ -542,7 +552,7 @@ class FileTest(MongoDBTestCase):
|
||||
def test_get_image_by_grid_id(self):
|
||||
|
||||
if not HAS_PIL:
|
||||
raise SkipTest('PIL not installed')
|
||||
raise SkipTest("PIL not installed")
|
||||
|
||||
class TestImage(Document):
|
||||
|
||||
@@ -559,8 +569,9 @@ class FileTest(MongoDBTestCase):
|
||||
test = TestImage.objects.first()
|
||||
grid_id = test.image1.grid_id
|
||||
|
||||
self.assertEqual(1, TestImage.objects(Q(image1=grid_id)
|
||||
or Q(image2=grid_id)).count())
|
||||
self.assertEqual(
|
||||
1, TestImage.objects(Q(image1=grid_id) or Q(image2=grid_id)).count()
|
||||
)
|
||||
|
||||
def test_complex_field_filefield(self):
|
||||
"""Ensure you can add meta data to file"""
|
||||
@@ -571,21 +582,21 @@ class FileTest(MongoDBTestCase):
|
||||
photos = ListField(FileField())
|
||||
|
||||
Animal.drop_collection()
|
||||
marmot = Animal(genus='Marmota', family='Sciuridae')
|
||||
marmot = Animal(genus="Marmota", family="Sciuridae")
|
||||
|
||||
with open(TEST_IMAGE_PATH, 'rb') as marmot_photo: # Retrieve a photo from disk
|
||||
photos_field = marmot._fields['photos'].field
|
||||
new_proxy = photos_field.get_proxy_obj('photos', marmot)
|
||||
new_proxy.put(marmot_photo, content_type='image/jpeg', foo='bar')
|
||||
with open(TEST_IMAGE_PATH, "rb") as marmot_photo: # Retrieve a photo from disk
|
||||
photos_field = marmot._fields["photos"].field
|
||||
new_proxy = photos_field.get_proxy_obj("photos", marmot)
|
||||
new_proxy.put(marmot_photo, content_type="image/jpeg", foo="bar")
|
||||
|
||||
marmot.photos.append(new_proxy)
|
||||
marmot.save()
|
||||
|
||||
marmot = Animal.objects.get()
|
||||
self.assertEqual(marmot.photos[0].content_type, 'image/jpeg')
|
||||
self.assertEqual(marmot.photos[0].foo, 'bar')
|
||||
self.assertEqual(marmot.photos[0].content_type, "image/jpeg")
|
||||
self.assertEqual(marmot.photos[0].foo, "bar")
|
||||
self.assertEqual(marmot.photos[0].get().length, 8313)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -4,28 +4,27 @@ import unittest
|
||||
from mongoengine import *
|
||||
from mongoengine.connection import get_db
|
||||
|
||||
__all__ = ("GeoFieldTest", )
|
||||
__all__ = ("GeoFieldTest",)
|
||||
|
||||
|
||||
class GeoFieldTest(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
connect(db='mongoenginetest')
|
||||
connect(db="mongoenginetest")
|
||||
self.db = get_db()
|
||||
|
||||
def _test_for_expected_error(self, Cls, loc, expected):
|
||||
try:
|
||||
Cls(loc=loc).validate()
|
||||
self.fail('Should not validate the location {0}'.format(loc))
|
||||
self.fail("Should not validate the location {0}".format(loc))
|
||||
except ValidationError as e:
|
||||
self.assertEqual(expected, e.to_dict()['loc'])
|
||||
self.assertEqual(expected, e.to_dict()["loc"])
|
||||
|
||||
def test_geopoint_validation(self):
|
||||
class Location(Document):
|
||||
loc = GeoPointField()
|
||||
|
||||
invalid_coords = [{"x": 1, "y": 2}, 5, "a"]
|
||||
expected = 'GeoPointField can only accept tuples or lists of (x, y)'
|
||||
expected = "GeoPointField can only accept tuples or lists of (x, y)"
|
||||
|
||||
for coord in invalid_coords:
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
@@ -40,7 +39,7 @@ class GeoFieldTest(unittest.TestCase):
|
||||
expected = "Both values (%s) in point must be float or int" % repr(coord)
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
|
||||
invalid_coords = [21, 4, 'a']
|
||||
invalid_coords = [21, 4, "a"]
|
||||
for coord in invalid_coords:
|
||||
expected = "GeoPointField can only accept tuples or lists of (x, y)"
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
@@ -50,7 +49,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
loc = PointField()
|
||||
|
||||
invalid_coords = {"x": 1, "y": 2}
|
||||
expected = 'PointField can only accept a valid GeoJson dictionary or lists of (x, y)'
|
||||
expected = (
|
||||
"PointField can only accept a valid GeoJson dictionary or lists of (x, y)"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MadeUp", "coordinates": []}
|
||||
@@ -77,19 +78,16 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
|
||||
Location(loc=[1, 2]).validate()
|
||||
Location(loc={
|
||||
"type": "Point",
|
||||
"coordinates": [
|
||||
81.4471435546875,
|
||||
23.61432859499169
|
||||
]}).validate()
|
||||
Location(
|
||||
loc={"type": "Point", "coordinates": [81.4471435546875, 23.61432859499169]}
|
||||
).validate()
|
||||
|
||||
def test_linestring_validation(self):
|
||||
class Location(Document):
|
||||
loc = LineStringField()
|
||||
|
||||
invalid_coords = {"x": 1, "y": 2}
|
||||
expected = 'LineStringField can only accept a valid GeoJson dictionary or lists of (x, y)'
|
||||
expected = "LineStringField can only accept a valid GeoJson dictionary or lists of (x, y)"
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MadeUp", "coordinates": [[]]}
|
||||
@@ -97,7 +95,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "LineString", "coordinates": [[1, 2, 3]]}
|
||||
expected = "Invalid LineString:\nValue ([1, 2, 3]) must be a two-dimensional point"
|
||||
expected = (
|
||||
"Invalid LineString:\nValue ([1, 2, 3]) must be a two-dimensional point"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [5, "a"]
|
||||
@@ -105,16 +105,25 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[1]]
|
||||
expected = "Invalid LineString:\nValue (%s) must be a two-dimensional point" % repr(invalid_coords[0])
|
||||
expected = (
|
||||
"Invalid LineString:\nValue (%s) must be a two-dimensional point"
|
||||
% repr(invalid_coords[0])
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[1, 2, 3]]
|
||||
expected = "Invalid LineString:\nValue (%s) must be a two-dimensional point" % repr(invalid_coords[0])
|
||||
expected = (
|
||||
"Invalid LineString:\nValue (%s) must be a two-dimensional point"
|
||||
% repr(invalid_coords[0])
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[{}, {}]], [("a", "b")]]
|
||||
for coord in invalid_coords:
|
||||
expected = "Invalid LineString:\nBoth values (%s) in point must be float or int" % repr(coord[0])
|
||||
expected = (
|
||||
"Invalid LineString:\nBoth values (%s) in point must be float or int"
|
||||
% repr(coord[0])
|
||||
)
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
|
||||
Location(loc=[[1, 2], [3, 4], [5, 6], [1, 2]]).validate()
|
||||
@@ -124,7 +133,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
loc = PolygonField()
|
||||
|
||||
invalid_coords = {"x": 1, "y": 2}
|
||||
expected = 'PolygonField can only accept a valid GeoJson dictionary or lists of (x, y)'
|
||||
expected = (
|
||||
"PolygonField can only accept a valid GeoJson dictionary or lists of (x, y)"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MadeUp", "coordinates": [[]]}
|
||||
@@ -136,7 +147,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[5, "a"]]]
|
||||
expected = "Invalid Polygon:\nBoth values ([5, 'a']) in point must be float or int"
|
||||
expected = (
|
||||
"Invalid Polygon:\nBoth values ([5, 'a']) in point must be float or int"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[]]]
|
||||
@@ -162,7 +175,7 @@ class GeoFieldTest(unittest.TestCase):
|
||||
loc = MultiPointField()
|
||||
|
||||
invalid_coords = {"x": 1, "y": 2}
|
||||
expected = 'MultiPointField can only accept a valid GeoJson dictionary or lists of (x, y)'
|
||||
expected = "MultiPointField can only accept a valid GeoJson dictionary or lists of (x, y)"
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MadeUp", "coordinates": [[]]}
|
||||
@@ -188,19 +201,19 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
|
||||
Location(loc=[[1, 2]]).validate()
|
||||
Location(loc={
|
||||
"type": "MultiPoint",
|
||||
"coordinates": [
|
||||
[1, 2],
|
||||
[81.4471435546875, 23.61432859499169]
|
||||
]}).validate()
|
||||
Location(
|
||||
loc={
|
||||
"type": "MultiPoint",
|
||||
"coordinates": [[1, 2], [81.4471435546875, 23.61432859499169]],
|
||||
}
|
||||
).validate()
|
||||
|
||||
def test_multilinestring_validation(self):
|
||||
class Location(Document):
|
||||
loc = MultiLineStringField()
|
||||
|
||||
invalid_coords = {"x": 1, "y": 2}
|
||||
expected = 'MultiLineStringField can only accept a valid GeoJson dictionary or lists of (x, y)'
|
||||
expected = "MultiLineStringField can only accept a valid GeoJson dictionary or lists of (x, y)"
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MadeUp", "coordinates": [[]]}
|
||||
@@ -216,16 +229,25 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[1]]]
|
||||
expected = "Invalid MultiLineString:\nValue (%s) must be a two-dimensional point" % repr(invalid_coords[0][0])
|
||||
expected = (
|
||||
"Invalid MultiLineString:\nValue (%s) must be a two-dimensional point"
|
||||
% repr(invalid_coords[0][0])
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[1, 2, 3]]]
|
||||
expected = "Invalid MultiLineString:\nValue (%s) must be a two-dimensional point" % repr(invalid_coords[0][0])
|
||||
expected = (
|
||||
"Invalid MultiLineString:\nValue (%s) must be a two-dimensional point"
|
||||
% repr(invalid_coords[0][0])
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[[{}, {}]]], [[("a", "b")]]]
|
||||
for coord in invalid_coords:
|
||||
expected = "Invalid MultiLineString:\nBoth values (%s) in point must be float or int" % repr(coord[0][0])
|
||||
expected = (
|
||||
"Invalid MultiLineString:\nBoth values (%s) in point must be float or int"
|
||||
% repr(coord[0][0])
|
||||
)
|
||||
self._test_for_expected_error(Location, coord, expected)
|
||||
|
||||
Location(loc=[[[1, 2], [3, 4], [5, 6], [1, 2]]]).validate()
|
||||
@@ -235,7 +257,7 @@ class GeoFieldTest(unittest.TestCase):
|
||||
loc = MultiPolygonField()
|
||||
|
||||
invalid_coords = {"x": 1, "y": 2}
|
||||
expected = 'MultiPolygonField can only accept a valid GeoJson dictionary or lists of (x, y)'
|
||||
expected = "MultiPolygonField can only accept a valid GeoJson dictionary or lists of (x, y)"
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MadeUp", "coordinates": [[]]}
|
||||
@@ -243,7 +265,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = {"type": "MultiPolygon", "coordinates": [[[[1, 2, 3]]]]}
|
||||
expected = "Invalid MultiPolygon:\nValue ([1, 2, 3]) must be a two-dimensional point"
|
||||
expected = (
|
||||
"Invalid MultiPolygon:\nValue ([1, 2, 3]) must be a two-dimensional point"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[[5, "a"]]]]
|
||||
@@ -255,7 +279,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[[1, 2, 3]]]]
|
||||
expected = "Invalid MultiPolygon:\nValue ([1, 2, 3]) must be a two-dimensional point"
|
||||
expected = (
|
||||
"Invalid MultiPolygon:\nValue ([1, 2, 3]) must be a two-dimensional point"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[[{}, {}]]], [[("a", "b")]]]
|
||||
@@ -263,7 +289,9 @@ class GeoFieldTest(unittest.TestCase):
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
invalid_coords = [[[[1, 2], [3, 4]]]]
|
||||
expected = "Invalid MultiPolygon:\nLineStrings must start and end at the same point"
|
||||
expected = (
|
||||
"Invalid MultiPolygon:\nLineStrings must start and end at the same point"
|
||||
)
|
||||
self._test_for_expected_error(Location, invalid_coords, expected)
|
||||
|
||||
Location(loc=[[[[1, 2], [3, 4], [5, 6], [1, 2]]]]).validate()
|
||||
@@ -271,17 +299,19 @@ class GeoFieldTest(unittest.TestCase):
|
||||
def test_indexes_geopoint(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields.
|
||||
"""
|
||||
|
||||
class Event(Document):
|
||||
title = StringField()
|
||||
location = GeoPointField()
|
||||
|
||||
geo_indicies = Event._geo_indices()
|
||||
self.assertEqual(geo_indicies, [{'fields': [('location', '2d')]}])
|
||||
self.assertEqual(geo_indicies, [{"fields": [("location", "2d")]}])
|
||||
|
||||
def test_geopoint_embedded_indexes(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields on
|
||||
embedded documents.
|
||||
"""
|
||||
|
||||
class Venue(EmbeddedDocument):
|
||||
location = GeoPointField()
|
||||
name = StringField()
|
||||
@@ -291,11 +321,12 @@ class GeoFieldTest(unittest.TestCase):
|
||||
venue = EmbeddedDocumentField(Venue)
|
||||
|
||||
geo_indicies = Event._geo_indices()
|
||||
self.assertEqual(geo_indicies, [{'fields': [('venue.location', '2d')]}])
|
||||
self.assertEqual(geo_indicies, [{"fields": [("venue.location", "2d")]}])
|
||||
|
||||
def test_indexes_2dsphere(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields.
|
||||
"""
|
||||
|
||||
class Event(Document):
|
||||
title = StringField()
|
||||
point = PointField()
|
||||
@@ -303,13 +334,14 @@ class GeoFieldTest(unittest.TestCase):
|
||||
polygon = PolygonField()
|
||||
|
||||
geo_indicies = Event._geo_indices()
|
||||
self.assertIn({'fields': [('line', '2dsphere')]}, geo_indicies)
|
||||
self.assertIn({'fields': [('polygon', '2dsphere')]}, geo_indicies)
|
||||
self.assertIn({'fields': [('point', '2dsphere')]}, geo_indicies)
|
||||
self.assertIn({"fields": [("line", "2dsphere")]}, geo_indicies)
|
||||
self.assertIn({"fields": [("polygon", "2dsphere")]}, geo_indicies)
|
||||
self.assertIn({"fields": [("point", "2dsphere")]}, geo_indicies)
|
||||
|
||||
def test_indexes_2dsphere_embedded(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields.
|
||||
"""
|
||||
|
||||
class Venue(EmbeddedDocument):
|
||||
name = StringField()
|
||||
point = PointField()
|
||||
@@ -321,12 +353,11 @@ class GeoFieldTest(unittest.TestCase):
|
||||
venue = EmbeddedDocumentField(Venue)
|
||||
|
||||
geo_indicies = Event._geo_indices()
|
||||
self.assertIn({'fields': [('venue.line', '2dsphere')]}, geo_indicies)
|
||||
self.assertIn({'fields': [('venue.polygon', '2dsphere')]}, geo_indicies)
|
||||
self.assertIn({'fields': [('venue.point', '2dsphere')]}, geo_indicies)
|
||||
self.assertIn({"fields": [("venue.line", "2dsphere")]}, geo_indicies)
|
||||
self.assertIn({"fields": [("venue.polygon", "2dsphere")]}, geo_indicies)
|
||||
self.assertIn({"fields": [("venue.point", "2dsphere")]}, geo_indicies)
|
||||
|
||||
def test_geo_indexes_recursion(self):
|
||||
|
||||
class Location(Document):
|
||||
name = StringField()
|
||||
location = GeoPointField()
|
||||
@@ -338,11 +369,11 @@ class GeoFieldTest(unittest.TestCase):
|
||||
Location.drop_collection()
|
||||
Parent.drop_collection()
|
||||
|
||||
Parent(name='Berlin').save()
|
||||
Parent(name="Berlin").save()
|
||||
info = Parent._get_collection().index_information()
|
||||
self.assertNotIn('location_2d', info)
|
||||
self.assertNotIn("location_2d", info)
|
||||
info = Location._get_collection().index_information()
|
||||
self.assertIn('location_2d', info)
|
||||
self.assertIn("location_2d", info)
|
||||
|
||||
self.assertEqual(len(Parent._geo_indices()), 0)
|
||||
self.assertEqual(len(Location._geo_indices()), 1)
|
||||
@@ -354,9 +385,7 @@ class GeoFieldTest(unittest.TestCase):
|
||||
location = PointField(auto_index=False)
|
||||
datetime = DateTimeField()
|
||||
|
||||
meta = {
|
||||
'indexes': [[("location", "2dsphere"), ("datetime", 1)]]
|
||||
}
|
||||
meta = {"indexes": [[("location", "2dsphere"), ("datetime", 1)]]}
|
||||
|
||||
self.assertEqual([], Log._geo_indices())
|
||||
|
||||
@@ -364,8 +393,10 @@ class GeoFieldTest(unittest.TestCase):
|
||||
Log.ensure_indexes()
|
||||
|
||||
info = Log._get_collection().index_information()
|
||||
self.assertEqual(info["location_2dsphere_datetime_1"]["key"],
|
||||
[('location', '2dsphere'), ('datetime', 1)])
|
||||
self.assertEqual(
|
||||
info["location_2dsphere_datetime_1"]["key"],
|
||||
[("location", "2dsphere"), ("datetime", 1)],
|
||||
)
|
||||
|
||||
# Test listing explicitly
|
||||
class Log(Document):
|
||||
@@ -373,9 +404,7 @@ class GeoFieldTest(unittest.TestCase):
|
||||
datetime = DateTimeField()
|
||||
|
||||
meta = {
|
||||
'indexes': [
|
||||
{'fields': [("location", "2dsphere"), ("datetime", 1)]}
|
||||
]
|
||||
"indexes": [{"fields": [("location", "2dsphere"), ("datetime", 1)]}]
|
||||
}
|
||||
|
||||
self.assertEqual([], Log._geo_indices())
|
||||
@@ -384,9 +413,11 @@ class GeoFieldTest(unittest.TestCase):
|
||||
Log.ensure_indexes()
|
||||
|
||||
info = Log._get_collection().index_information()
|
||||
self.assertEqual(info["location_2dsphere_datetime_1"]["key"],
|
||||
[('location', '2dsphere'), ('datetime', 1)])
|
||||
self.assertEqual(
|
||||
info["location_2dsphere_datetime_1"]["key"],
|
||||
[("location", "2dsphere"), ("datetime", 1)],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -9,19 +9,22 @@ from bson import Binary
|
||||
from mongoengine import *
|
||||
from tests.utils import MongoDBTestCase
|
||||
|
||||
BIN_VALUE = six.b('\xa9\xf3\x8d(\xd7\x03\x84\xb4k[\x0f\xe3\xa2\x19\x85p[J\xa3\xd2>\xde\xe6\x87\xb1\x7f\xc6\xe6\xd9r\x18\xf5')
|
||||
BIN_VALUE = six.b(
|
||||
"\xa9\xf3\x8d(\xd7\x03\x84\xb4k[\x0f\xe3\xa2\x19\x85p[J\xa3\xd2>\xde\xe6\x87\xb1\x7f\xc6\xe6\xd9r\x18\xf5"
|
||||
)
|
||||
|
||||
|
||||
class TestBinaryField(MongoDBTestCase):
|
||||
def test_binary_fields(self):
|
||||
"""Ensure that binary fields can be stored and retrieved.
|
||||
"""
|
||||
|
||||
class Attachment(Document):
|
||||
content_type = StringField()
|
||||
blob = BinaryField()
|
||||
|
||||
BLOB = six.b('\xe6\x00\xc4\xff\x07')
|
||||
MIME_TYPE = 'application/octet-stream'
|
||||
BLOB = six.b("\xe6\x00\xc4\xff\x07")
|
||||
MIME_TYPE = "application/octet-stream"
|
||||
|
||||
Attachment.drop_collection()
|
||||
|
||||
@@ -35,6 +38,7 @@ class TestBinaryField(MongoDBTestCase):
|
||||
def test_validation_succeeds(self):
|
||||
"""Ensure that valid values can be assigned to binary fields.
|
||||
"""
|
||||
|
||||
class AttachmentRequired(Document):
|
||||
blob = BinaryField(required=True)
|
||||
|
||||
@@ -43,11 +47,11 @@ class TestBinaryField(MongoDBTestCase):
|
||||
|
||||
attachment_required = AttachmentRequired()
|
||||
self.assertRaises(ValidationError, attachment_required.validate)
|
||||
attachment_required.blob = Binary(six.b('\xe6\x00\xc4\xff\x07'))
|
||||
attachment_required.blob = Binary(six.b("\xe6\x00\xc4\xff\x07"))
|
||||
attachment_required.validate()
|
||||
|
||||
_5_BYTES = six.b('\xe6\x00\xc4\xff\x07')
|
||||
_4_BYTES = six.b('\xe6\x00\xc4\xff')
|
||||
_5_BYTES = six.b("\xe6\x00\xc4\xff\x07")
|
||||
_4_BYTES = six.b("\xe6\x00\xc4\xff")
|
||||
self.assertRaises(ValidationError, AttachmentSizeLimit(blob=_5_BYTES).validate)
|
||||
AttachmentSizeLimit(blob=_4_BYTES).validate()
|
||||
|
||||
@@ -57,7 +61,7 @@ class TestBinaryField(MongoDBTestCase):
|
||||
class Attachment(Document):
|
||||
blob = BinaryField()
|
||||
|
||||
for invalid_data in (2, u'Im_a_unicode', ['some_str']):
|
||||
for invalid_data in (2, u"Im_a_unicode", ["some_str"]):
|
||||
self.assertRaises(ValidationError, Attachment(blob=invalid_data).validate)
|
||||
|
||||
def test__primary(self):
|
||||
@@ -108,17 +112,17 @@ class TestBinaryField(MongoDBTestCase):
|
||||
|
||||
def test_modify_operation__set(self):
|
||||
"""Ensures no regression of bug #1127"""
|
||||
|
||||
class MyDocument(Document):
|
||||
some_field = StringField()
|
||||
bin_field = BinaryField()
|
||||
|
||||
MyDocument.drop_collection()
|
||||
|
||||
doc = MyDocument.objects(some_field='test').modify(
|
||||
upsert=True, new=True,
|
||||
set__bin_field=BIN_VALUE
|
||||
doc = MyDocument.objects(some_field="test").modify(
|
||||
upsert=True, new=True, set__bin_field=BIN_VALUE
|
||||
)
|
||||
self.assertEqual(doc.some_field, 'test')
|
||||
self.assertEqual(doc.some_field, "test")
|
||||
if six.PY3:
|
||||
self.assertEqual(doc.bin_field, BIN_VALUE)
|
||||
else:
|
||||
@@ -126,15 +130,18 @@ class TestBinaryField(MongoDBTestCase):
|
||||
|
||||
def test_update_one(self):
|
||||
"""Ensures no regression of bug #1127"""
|
||||
|
||||
class MyDocument(Document):
|
||||
bin_field = BinaryField()
|
||||
|
||||
MyDocument.drop_collection()
|
||||
|
||||
bin_data = six.b('\xe6\x00\xc4\xff\x07')
|
||||
bin_data = six.b("\xe6\x00\xc4\xff\x07")
|
||||
doc = MyDocument(bin_field=bin_data).save()
|
||||
|
||||
n_updated = MyDocument.objects(bin_field=bin_data).update_one(bin_field=BIN_VALUE)
|
||||
n_updated = MyDocument.objects(bin_field=bin_data).update_one(
|
||||
bin_field=BIN_VALUE
|
||||
)
|
||||
self.assertEqual(n_updated, 1)
|
||||
fetched = MyDocument.objects.with_id(doc.id)
|
||||
if six.PY3:
|
||||
|
||||
@@ -11,15 +11,13 @@ class TestBooleanField(MongoDBTestCase):
|
||||
|
||||
person = Person(admin=True)
|
||||
person.save()
|
||||
self.assertEqual(
|
||||
get_as_pymongo(person),
|
||||
{'_id': person.id,
|
||||
'admin': True})
|
||||
self.assertEqual(get_as_pymongo(person), {"_id": person.id, "admin": True})
|
||||
|
||||
def test_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to boolean
|
||||
fields.
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
admin = BooleanField()
|
||||
|
||||
@@ -29,9 +27,9 @@ class TestBooleanField(MongoDBTestCase):
|
||||
|
||||
person.admin = 2
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.admin = 'Yes'
|
||||
person.admin = "Yes"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.admin = 'False'
|
||||
person.admin = "False"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
def test_weirdness_constructor(self):
|
||||
@@ -39,11 +37,12 @@ class TestBooleanField(MongoDBTestCase):
|
||||
which causes some weird behavior. We dont necessarily want to maintain this behavior
|
||||
but its a known issue
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
admin = BooleanField()
|
||||
|
||||
new_person = Person(admin='False')
|
||||
new_person = Person(admin="False")
|
||||
self.assertTrue(new_person.admin)
|
||||
|
||||
new_person = Person(admin='0')
|
||||
new_person = Person(admin="0")
|
||||
self.assertTrue(new_person.admin)
|
||||
|
||||
@@ -7,12 +7,12 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
def test_get_and_save(self):
|
||||
"""
|
||||
Tests #1047: CachedReferenceField creates DBRefs on to_python,
|
||||
but can't save them on to_mongo.
|
||||
"""
|
||||
|
||||
class Animal(Document):
|
||||
name = StringField()
|
||||
tag = StringField()
|
||||
@@ -24,10 +24,11 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
Animal.drop_collection()
|
||||
Ocorrence.drop_collection()
|
||||
|
||||
Ocorrence(person="testte",
|
||||
animal=Animal(name="Leopard", tag="heavy").save()).save()
|
||||
Ocorrence(
|
||||
person="testte", animal=Animal(name="Leopard", tag="heavy").save()
|
||||
).save()
|
||||
p = Ocorrence.objects.get()
|
||||
p.person = 'new_testte'
|
||||
p.person = "new_testte"
|
||||
p.save()
|
||||
|
||||
def test_general_things(self):
|
||||
@@ -37,8 +38,7 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
class Ocorrence(Document):
|
||||
person = StringField()
|
||||
animal = CachedReferenceField(
|
||||
Animal, fields=['tag'])
|
||||
animal = CachedReferenceField(Animal, fields=["tag"])
|
||||
|
||||
Animal.drop_collection()
|
||||
Ocorrence.drop_collection()
|
||||
@@ -55,19 +55,18 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
self.assertEqual(Ocorrence.objects(animal=None).count(), 1)
|
||||
|
||||
self.assertEqual(
|
||||
a.to_mongo(fields=['tag']), {'tag': 'heavy', "_id": a.pk})
|
||||
self.assertEqual(a.to_mongo(fields=["tag"]), {"tag": "heavy", "_id": a.pk})
|
||||
|
||||
self.assertEqual(o.to_mongo()['animal']['tag'], 'heavy')
|
||||
self.assertEqual(o.to_mongo()["animal"]["tag"], "heavy")
|
||||
|
||||
# counts
|
||||
Ocorrence(person="teste 2").save()
|
||||
Ocorrence(person="teste 3").save()
|
||||
|
||||
count = Ocorrence.objects(animal__tag='heavy').count()
|
||||
count = Ocorrence.objects(animal__tag="heavy").count()
|
||||
self.assertEqual(count, 1)
|
||||
|
||||
ocorrence = Ocorrence.objects(animal__tag='heavy').first()
|
||||
ocorrence = Ocorrence.objects(animal__tag="heavy").first()
|
||||
self.assertEqual(ocorrence.person, "teste")
|
||||
self.assertIsInstance(ocorrence.animal, Animal)
|
||||
|
||||
@@ -78,28 +77,21 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
class SocialTest(Document):
|
||||
group = StringField()
|
||||
person = CachedReferenceField(
|
||||
PersonAuto,
|
||||
fields=('salary',))
|
||||
person = CachedReferenceField(PersonAuto, fields=("salary",))
|
||||
|
||||
PersonAuto.drop_collection()
|
||||
SocialTest.drop_collection()
|
||||
|
||||
p = PersonAuto(name="Alberto", salary=Decimal('7000.00'))
|
||||
p = PersonAuto(name="Alberto", salary=Decimal("7000.00"))
|
||||
p.save()
|
||||
|
||||
s = SocialTest(group="dev", person=p)
|
||||
s.save()
|
||||
|
||||
self.assertEqual(
|
||||
SocialTest.objects._collection.find_one({'person.salary': 7000.00}), {
|
||||
'_id': s.pk,
|
||||
'group': s.group,
|
||||
'person': {
|
||||
'_id': p.pk,
|
||||
'salary': 7000.00
|
||||
}
|
||||
})
|
||||
SocialTest.objects._collection.find_one({"person.salary": 7000.00}),
|
||||
{"_id": s.pk, "group": s.group, "person": {"_id": p.pk, "salary": 7000.00}},
|
||||
)
|
||||
|
||||
def test_cached_reference_field_reference(self):
|
||||
class Group(Document):
|
||||
@@ -111,17 +103,14 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
class SocialData(Document):
|
||||
obs = StringField()
|
||||
tags = ListField(
|
||||
StringField())
|
||||
person = CachedReferenceField(
|
||||
Person,
|
||||
fields=('group',))
|
||||
tags = ListField(StringField())
|
||||
person = CachedReferenceField(Person, fields=("group",))
|
||||
|
||||
Group.drop_collection()
|
||||
Person.drop_collection()
|
||||
SocialData.drop_collection()
|
||||
|
||||
g1 = Group(name='dev')
|
||||
g1 = Group(name="dev")
|
||||
g1.save()
|
||||
|
||||
g2 = Group(name="designers")
|
||||
@@ -136,22 +125,21 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
p3 = Person(name="Afro design", group=g2)
|
||||
p3.save()
|
||||
|
||||
s1 = SocialData(obs="testing 123", person=p1, tags=['tag1', 'tag2'])
|
||||
s1 = SocialData(obs="testing 123", person=p1, tags=["tag1", "tag2"])
|
||||
s1.save()
|
||||
|
||||
s2 = SocialData(obs="testing 321", person=p3, tags=['tag3', 'tag4'])
|
||||
s2 = SocialData(obs="testing 321", person=p3, tags=["tag3", "tag4"])
|
||||
s2.save()
|
||||
|
||||
self.assertEqual(SocialData.objects._collection.find_one(
|
||||
{'tags': 'tag2'}), {
|
||||
'_id': s1.pk,
|
||||
'obs': 'testing 123',
|
||||
'tags': ['tag1', 'tag2'],
|
||||
'person': {
|
||||
'_id': p1.pk,
|
||||
'group': g1.pk
|
||||
}
|
||||
})
|
||||
self.assertEqual(
|
||||
SocialData.objects._collection.find_one({"tags": "tag2"}),
|
||||
{
|
||||
"_id": s1.pk,
|
||||
"obs": "testing 123",
|
||||
"tags": ["tag1", "tag2"],
|
||||
"person": {"_id": p1.pk, "group": g1.pk},
|
||||
},
|
||||
)
|
||||
|
||||
self.assertEqual(SocialData.objects(person__group=g2).count(), 1)
|
||||
self.assertEqual(SocialData.objects(person__group=g2).first(), s2)
|
||||
@@ -163,23 +151,18 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
Product.drop_collection()
|
||||
|
||||
class Basket(Document):
|
||||
products = ListField(CachedReferenceField(Product, fields=['name']))
|
||||
products = ListField(CachedReferenceField(Product, fields=["name"]))
|
||||
|
||||
Basket.drop_collection()
|
||||
product1 = Product(name='abc').save()
|
||||
product2 = Product(name='def').save()
|
||||
product1 = Product(name="abc").save()
|
||||
product2 = Product(name="def").save()
|
||||
basket = Basket(products=[product1]).save()
|
||||
self.assertEqual(
|
||||
Basket.objects._collection.find_one(),
|
||||
{
|
||||
'_id': basket.pk,
|
||||
'products': [
|
||||
{
|
||||
'_id': product1.pk,
|
||||
'name': product1.name
|
||||
}
|
||||
]
|
||||
}
|
||||
"_id": basket.pk,
|
||||
"products": [{"_id": product1.pk, "name": product1.name}],
|
||||
},
|
||||
)
|
||||
# push to list
|
||||
basket.update(push__products=product2)
|
||||
@@ -187,161 +170,135 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
self.assertEqual(
|
||||
Basket.objects._collection.find_one(),
|
||||
{
|
||||
'_id': basket.pk,
|
||||
'products': [
|
||||
{
|
||||
'_id': product1.pk,
|
||||
'name': product1.name
|
||||
},
|
||||
{
|
||||
'_id': product2.pk,
|
||||
'name': product2.name
|
||||
}
|
||||
]
|
||||
}
|
||||
"_id": basket.pk,
|
||||
"products": [
|
||||
{"_id": product1.pk, "name": product1.name},
|
||||
{"_id": product2.pk, "name": product2.name},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
def test_cached_reference_field_update_all(self):
|
||||
class Person(Document):
|
||||
TYPES = (
|
||||
('pf', "PF"),
|
||||
('pj', "PJ")
|
||||
)
|
||||
TYPES = (("pf", "PF"), ("pj", "PJ"))
|
||||
name = StringField()
|
||||
tp = StringField(choices=TYPES)
|
||||
father = CachedReferenceField('self', fields=('tp',))
|
||||
father = CachedReferenceField("self", fields=("tp",))
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
a1 = Person(name="Wilson Father", tp="pj")
|
||||
a1.save()
|
||||
|
||||
a2 = Person(name='Wilson Junior', tp='pf', father=a1)
|
||||
a2 = Person(name="Wilson Junior", tp="pf", father=a1)
|
||||
a2.save()
|
||||
|
||||
a2 = Person.objects.with_id(a2.id)
|
||||
self.assertEqual(a2.father.tp, a1.tp)
|
||||
|
||||
self.assertEqual(dict(a2.to_mongo()), {
|
||||
"_id": a2.pk,
|
||||
"name": u"Wilson Junior",
|
||||
"tp": u"pf",
|
||||
"father": {
|
||||
"_id": a1.pk,
|
||||
"tp": u"pj"
|
||||
}
|
||||
})
|
||||
self.assertEqual(
|
||||
dict(a2.to_mongo()),
|
||||
{
|
||||
"_id": a2.pk,
|
||||
"name": u"Wilson Junior",
|
||||
"tp": u"pf",
|
||||
"father": {"_id": a1.pk, "tp": u"pj"},
|
||||
},
|
||||
)
|
||||
|
||||
self.assertEqual(Person.objects(father=a1)._query, {
|
||||
'father._id': a1.pk
|
||||
})
|
||||
self.assertEqual(Person.objects(father=a1)._query, {"father._id": a1.pk})
|
||||
self.assertEqual(Person.objects(father=a1).count(), 1)
|
||||
|
||||
Person.objects.update(set__tp="pf")
|
||||
Person.father.sync_all()
|
||||
|
||||
a2.reload()
|
||||
self.assertEqual(dict(a2.to_mongo()), {
|
||||
"_id": a2.pk,
|
||||
"name": u"Wilson Junior",
|
||||
"tp": u"pf",
|
||||
"father": {
|
||||
"_id": a1.pk,
|
||||
"tp": u"pf"
|
||||
}
|
||||
})
|
||||
self.assertEqual(
|
||||
dict(a2.to_mongo()),
|
||||
{
|
||||
"_id": a2.pk,
|
||||
"name": u"Wilson Junior",
|
||||
"tp": u"pf",
|
||||
"father": {"_id": a1.pk, "tp": u"pf"},
|
||||
},
|
||||
)
|
||||
|
||||
def test_cached_reference_fields_on_embedded_documents(self):
|
||||
with self.assertRaises(InvalidDocumentError):
|
||||
|
||||
class Test(Document):
|
||||
name = StringField()
|
||||
|
||||
type('WrongEmbeddedDocument', (
|
||||
EmbeddedDocument,), {
|
||||
'test': CachedReferenceField(Test)
|
||||
})
|
||||
type(
|
||||
"WrongEmbeddedDocument",
|
||||
(EmbeddedDocument,),
|
||||
{"test": CachedReferenceField(Test)},
|
||||
)
|
||||
|
||||
def test_cached_reference_auto_sync(self):
|
||||
class Person(Document):
|
||||
TYPES = (
|
||||
('pf', "PF"),
|
||||
('pj', "PJ")
|
||||
)
|
||||
TYPES = (("pf", "PF"), ("pj", "PJ"))
|
||||
name = StringField()
|
||||
tp = StringField(
|
||||
choices=TYPES
|
||||
)
|
||||
tp = StringField(choices=TYPES)
|
||||
|
||||
father = CachedReferenceField('self', fields=('tp',))
|
||||
father = CachedReferenceField("self", fields=("tp",))
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
a1 = Person(name="Wilson Father", tp="pj")
|
||||
a1.save()
|
||||
|
||||
a2 = Person(name='Wilson Junior', tp='pf', father=a1)
|
||||
a2 = Person(name="Wilson Junior", tp="pf", father=a1)
|
||||
a2.save()
|
||||
|
||||
a1.tp = 'pf'
|
||||
a1.tp = "pf"
|
||||
a1.save()
|
||||
|
||||
a2.reload()
|
||||
self.assertEqual(dict(a2.to_mongo()), {
|
||||
'_id': a2.pk,
|
||||
'name': 'Wilson Junior',
|
||||
'tp': 'pf',
|
||||
'father': {
|
||||
'_id': a1.pk,
|
||||
'tp': 'pf'
|
||||
}
|
||||
})
|
||||
self.assertEqual(
|
||||
dict(a2.to_mongo()),
|
||||
{
|
||||
"_id": a2.pk,
|
||||
"name": "Wilson Junior",
|
||||
"tp": "pf",
|
||||
"father": {"_id": a1.pk, "tp": "pf"},
|
||||
},
|
||||
)
|
||||
|
||||
def test_cached_reference_auto_sync_disabled(self):
|
||||
class Persone(Document):
|
||||
TYPES = (
|
||||
('pf', "PF"),
|
||||
('pj', "PJ")
|
||||
)
|
||||
TYPES = (("pf", "PF"), ("pj", "PJ"))
|
||||
name = StringField()
|
||||
tp = StringField(
|
||||
choices=TYPES
|
||||
)
|
||||
tp = StringField(choices=TYPES)
|
||||
|
||||
father = CachedReferenceField(
|
||||
'self', fields=('tp',), auto_sync=False)
|
||||
father = CachedReferenceField("self", fields=("tp",), auto_sync=False)
|
||||
|
||||
Persone.drop_collection()
|
||||
|
||||
a1 = Persone(name="Wilson Father", tp="pj")
|
||||
a1.save()
|
||||
|
||||
a2 = Persone(name='Wilson Junior', tp='pf', father=a1)
|
||||
a2 = Persone(name="Wilson Junior", tp="pf", father=a1)
|
||||
a2.save()
|
||||
|
||||
a1.tp = 'pf'
|
||||
a1.tp = "pf"
|
||||
a1.save()
|
||||
|
||||
self.assertEqual(Persone.objects._collection.find_one({'_id': a2.pk}), {
|
||||
'_id': a2.pk,
|
||||
'name': 'Wilson Junior',
|
||||
'tp': 'pf',
|
||||
'father': {
|
||||
'_id': a1.pk,
|
||||
'tp': 'pj'
|
||||
}
|
||||
})
|
||||
self.assertEqual(
|
||||
Persone.objects._collection.find_one({"_id": a2.pk}),
|
||||
{
|
||||
"_id": a2.pk,
|
||||
"name": "Wilson Junior",
|
||||
"tp": "pf",
|
||||
"father": {"_id": a1.pk, "tp": "pj"},
|
||||
},
|
||||
)
|
||||
|
||||
def test_cached_reference_embedded_fields(self):
|
||||
class Owner(EmbeddedDocument):
|
||||
TPS = (
|
||||
('n', "Normal"),
|
||||
('u', "Urgent")
|
||||
)
|
||||
TPS = (("n", "Normal"), ("u", "Urgent"))
|
||||
name = StringField()
|
||||
tp = StringField(
|
||||
verbose_name="Type",
|
||||
db_field="t",
|
||||
choices=TPS)
|
||||
tp = StringField(verbose_name="Type", db_field="t", choices=TPS)
|
||||
|
||||
class Animal(Document):
|
||||
name = StringField()
|
||||
@@ -351,43 +308,38 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
class Ocorrence(Document):
|
||||
person = StringField()
|
||||
animal = CachedReferenceField(
|
||||
Animal, fields=['tag', 'owner.tp'])
|
||||
animal = CachedReferenceField(Animal, fields=["tag", "owner.tp"])
|
||||
|
||||
Animal.drop_collection()
|
||||
Ocorrence.drop_collection()
|
||||
|
||||
a = Animal(name="Leopard", tag="heavy",
|
||||
owner=Owner(tp='u', name="Wilson Júnior")
|
||||
)
|
||||
a = Animal(
|
||||
name="Leopard", tag="heavy", owner=Owner(tp="u", name="Wilson Júnior")
|
||||
)
|
||||
a.save()
|
||||
|
||||
o = Ocorrence(person="teste", animal=a)
|
||||
o.save()
|
||||
self.assertEqual(dict(a.to_mongo(fields=['tag', 'owner.tp'])), {
|
||||
'_id': a.pk,
|
||||
'tag': 'heavy',
|
||||
'owner': {
|
||||
't': 'u'
|
||||
}
|
||||
})
|
||||
self.assertEqual(o.to_mongo()['animal']['tag'], 'heavy')
|
||||
self.assertEqual(o.to_mongo()['animal']['owner']['t'], 'u')
|
||||
self.assertEqual(
|
||||
dict(a.to_mongo(fields=["tag", "owner.tp"])),
|
||||
{"_id": a.pk, "tag": "heavy", "owner": {"t": "u"}},
|
||||
)
|
||||
self.assertEqual(o.to_mongo()["animal"]["tag"], "heavy")
|
||||
self.assertEqual(o.to_mongo()["animal"]["owner"]["t"], "u")
|
||||
|
||||
# Check to_mongo with fields
|
||||
self.assertNotIn('animal', o.to_mongo(fields=['person']))
|
||||
self.assertNotIn("animal", o.to_mongo(fields=["person"]))
|
||||
|
||||
# counts
|
||||
Ocorrence(person="teste 2").save()
|
||||
Ocorrence(person="teste 3").save()
|
||||
|
||||
count = Ocorrence.objects(
|
||||
animal__tag='heavy', animal__owner__tp='u').count()
|
||||
count = Ocorrence.objects(animal__tag="heavy", animal__owner__tp="u").count()
|
||||
self.assertEqual(count, 1)
|
||||
|
||||
ocorrence = Ocorrence.objects(
|
||||
animal__tag='heavy',
|
||||
animal__owner__tp='u').first()
|
||||
animal__tag="heavy", animal__owner__tp="u"
|
||||
).first()
|
||||
self.assertEqual(ocorrence.person, "teste")
|
||||
self.assertIsInstance(ocorrence.animal, Animal)
|
||||
|
||||
@@ -404,43 +356,39 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
class Ocorrence(Document):
|
||||
person = StringField()
|
||||
animal = CachedReferenceField(
|
||||
Animal, fields=['tag', 'owner.tags'])
|
||||
animal = CachedReferenceField(Animal, fields=["tag", "owner.tags"])
|
||||
|
||||
Animal.drop_collection()
|
||||
Ocorrence.drop_collection()
|
||||
|
||||
a = Animal(name="Leopard", tag="heavy",
|
||||
owner=Owner(tags=['cool', 'funny'],
|
||||
name="Wilson Júnior")
|
||||
)
|
||||
a = Animal(
|
||||
name="Leopard",
|
||||
tag="heavy",
|
||||
owner=Owner(tags=["cool", "funny"], name="Wilson Júnior"),
|
||||
)
|
||||
a.save()
|
||||
|
||||
o = Ocorrence(person="teste 2", animal=a)
|
||||
o.save()
|
||||
self.assertEqual(dict(a.to_mongo(fields=['tag', 'owner.tags'])), {
|
||||
'_id': a.pk,
|
||||
'tag': 'heavy',
|
||||
'owner': {
|
||||
'tags': ['cool', 'funny']
|
||||
}
|
||||
})
|
||||
self.assertEqual(
|
||||
dict(a.to_mongo(fields=["tag", "owner.tags"])),
|
||||
{"_id": a.pk, "tag": "heavy", "owner": {"tags": ["cool", "funny"]}},
|
||||
)
|
||||
|
||||
self.assertEqual(o.to_mongo()['animal']['tag'], 'heavy')
|
||||
self.assertEqual(o.to_mongo()['animal']['owner']['tags'],
|
||||
['cool', 'funny'])
|
||||
self.assertEqual(o.to_mongo()["animal"]["tag"], "heavy")
|
||||
self.assertEqual(o.to_mongo()["animal"]["owner"]["tags"], ["cool", "funny"])
|
||||
|
||||
# counts
|
||||
Ocorrence(person="teste 2").save()
|
||||
Ocorrence(person="teste 3").save()
|
||||
|
||||
query = Ocorrence.objects(
|
||||
animal__tag='heavy', animal__owner__tags='cool')._query
|
||||
self.assertEqual(
|
||||
query, {'animal.owner.tags': 'cool', 'animal.tag': 'heavy'})
|
||||
animal__tag="heavy", animal__owner__tags="cool"
|
||||
)._query
|
||||
self.assertEqual(query, {"animal.owner.tags": "cool", "animal.tag": "heavy"})
|
||||
|
||||
ocorrence = Ocorrence.objects(
|
||||
animal__tag='heavy',
|
||||
animal__owner__tags='cool').first()
|
||||
animal__tag="heavy", animal__owner__tags="cool"
|
||||
).first()
|
||||
self.assertEqual(ocorrence.person, "teste 2")
|
||||
self.assertIsInstance(ocorrence.animal, Animal)
|
||||
|
||||
@@ -14,9 +14,10 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
"""Tests for complex datetime fields - which can handle
|
||||
microseconds without rounding.
|
||||
"""
|
||||
|
||||
class LogEntry(Document):
|
||||
date = ComplexDateTimeField()
|
||||
date_with_dots = ComplexDateTimeField(separator='.')
|
||||
date_with_dots = ComplexDateTimeField(separator=".")
|
||||
|
||||
LogEntry.drop_collection()
|
||||
|
||||
@@ -62,17 +63,25 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
mm = dd = hh = ii = ss = [1, 10]
|
||||
|
||||
for values in itertools.product([2014], mm, dd, hh, ii, ss, microsecond):
|
||||
stored = LogEntry(date=datetime.datetime(*values)).to_mongo()['date']
|
||||
self.assertTrue(re.match('^\d{4},\d{2},\d{2},\d{2},\d{2},\d{2},\d{6}$', stored) is not None)
|
||||
stored = LogEntry(date=datetime.datetime(*values)).to_mongo()["date"]
|
||||
self.assertTrue(
|
||||
re.match("^\d{4},\d{2},\d{2},\d{2},\d{2},\d{2},\d{6}$", stored)
|
||||
is not None
|
||||
)
|
||||
|
||||
# Test separator
|
||||
stored = LogEntry(date_with_dots=datetime.datetime(2014, 1, 1)).to_mongo()['date_with_dots']
|
||||
self.assertTrue(re.match('^\d{4}.\d{2}.\d{2}.\d{2}.\d{2}.\d{2}.\d{6}$', stored) is not None)
|
||||
stored = LogEntry(date_with_dots=datetime.datetime(2014, 1, 1)).to_mongo()[
|
||||
"date_with_dots"
|
||||
]
|
||||
self.assertTrue(
|
||||
re.match("^\d{4}.\d{2}.\d{2}.\d{2}.\d{2}.\d{2}.\d{6}$", stored) is not None
|
||||
)
|
||||
|
||||
def test_complexdatetime_usage(self):
|
||||
"""Tests for complex datetime fields - which can handle
|
||||
microseconds without rounding.
|
||||
"""
|
||||
|
||||
class LogEntry(Document):
|
||||
date = ComplexDateTimeField()
|
||||
|
||||
@@ -123,22 +132,21 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
|
||||
# Test microsecond-level ordering/filtering
|
||||
for microsecond in (99, 999, 9999, 10000):
|
||||
LogEntry(
|
||||
date=datetime.datetime(2015, 1, 1, 0, 0, 0, microsecond)
|
||||
).save()
|
||||
LogEntry(date=datetime.datetime(2015, 1, 1, 0, 0, 0, microsecond)).save()
|
||||
|
||||
logs = list(LogEntry.objects.order_by('date'))
|
||||
logs = list(LogEntry.objects.order_by("date"))
|
||||
for next_idx, log in enumerate(logs[:-1], start=1):
|
||||
next_log = logs[next_idx]
|
||||
self.assertTrue(log.date < next_log.date)
|
||||
|
||||
logs = list(LogEntry.objects.order_by('-date'))
|
||||
logs = list(LogEntry.objects.order_by("-date"))
|
||||
for next_idx, log in enumerate(logs[:-1], start=1):
|
||||
next_log = logs[next_idx]
|
||||
self.assertTrue(log.date > next_log.date)
|
||||
|
||||
logs = LogEntry.objects.filter(
|
||||
date__lte=datetime.datetime(2015, 1, 1, 0, 0, 0, 10000))
|
||||
date__lte=datetime.datetime(2015, 1, 1, 0, 0, 0, 10000)
|
||||
)
|
||||
self.assertEqual(logs.count(), 4)
|
||||
|
||||
def test_no_default_value(self):
|
||||
@@ -156,6 +164,7 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
|
||||
def test_default_static_value(self):
|
||||
NOW = datetime.datetime.utcnow()
|
||||
|
||||
class Log(Document):
|
||||
timestamp = ComplexDateTimeField(default=NOW)
|
||||
|
||||
|
||||
@@ -18,10 +18,11 @@ class TestDateField(MongoDBTestCase):
|
||||
Ensure an exception is raised when trying to
|
||||
cast an empty string to datetime.
|
||||
"""
|
||||
|
||||
class MyDoc(Document):
|
||||
dt = DateField()
|
||||
|
||||
md = MyDoc(dt='')
|
||||
md = MyDoc(dt="")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
|
||||
def test_date_from_whitespace_string(self):
|
||||
@@ -29,16 +30,18 @@ class TestDateField(MongoDBTestCase):
|
||||
Ensure an exception is raised when trying to
|
||||
cast a whitespace-only string to datetime.
|
||||
"""
|
||||
|
||||
class MyDoc(Document):
|
||||
dt = DateField()
|
||||
|
||||
md = MyDoc(dt=' ')
|
||||
md = MyDoc(dt=" ")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
|
||||
def test_default_values_today(self):
|
||||
"""Ensure that default field values are used when creating
|
||||
a document.
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
day = DateField(default=datetime.date.today)
|
||||
|
||||
@@ -46,13 +49,14 @@ class TestDateField(MongoDBTestCase):
|
||||
person.validate()
|
||||
self.assertEqual(person.day, person.day)
|
||||
self.assertEqual(person.day, datetime.date.today())
|
||||
self.assertEqual(person._data['day'], person.day)
|
||||
self.assertEqual(person._data["day"], person.day)
|
||||
|
||||
def test_date(self):
|
||||
"""Tests showing pymongo date fields
|
||||
|
||||
See: http://api.mongodb.org/python/current/api/bson/son.html#dt
|
||||
"""
|
||||
|
||||
class LogEntry(Document):
|
||||
date = DateField()
|
||||
|
||||
@@ -95,6 +99,7 @@ class TestDateField(MongoDBTestCase):
|
||||
|
||||
def test_regular_usage(self):
|
||||
"""Tests for regular datetime fields"""
|
||||
|
||||
class LogEntry(Document):
|
||||
date = DateField()
|
||||
|
||||
@@ -106,12 +111,12 @@ class TestDateField(MongoDBTestCase):
|
||||
log.validate()
|
||||
log.save()
|
||||
|
||||
for query in (d1, d1.isoformat(' ')):
|
||||
for query in (d1, d1.isoformat(" ")):
|
||||
log1 = LogEntry.objects.get(date=query)
|
||||
self.assertEqual(log, log1)
|
||||
|
||||
if dateutil:
|
||||
log1 = LogEntry.objects.get(date=d1.isoformat('T'))
|
||||
log1 = LogEntry.objects.get(date=d1.isoformat("T"))
|
||||
self.assertEqual(log, log1)
|
||||
|
||||
# create additional 19 log entries for a total of 20
|
||||
@@ -142,6 +147,7 @@ class TestDateField(MongoDBTestCase):
|
||||
"""Ensure that invalid values cannot be assigned to datetime
|
||||
fields.
|
||||
"""
|
||||
|
||||
class LogEntry(Document):
|
||||
time = DateField()
|
||||
|
||||
@@ -152,14 +158,14 @@ class TestDateField(MongoDBTestCase):
|
||||
log.time = datetime.date.today()
|
||||
log.validate()
|
||||
|
||||
log.time = datetime.datetime.now().isoformat(' ')
|
||||
log.time = datetime.datetime.now().isoformat(" ")
|
||||
log.validate()
|
||||
|
||||
if dateutil:
|
||||
log.time = datetime.datetime.now().isoformat('T')
|
||||
log.time = datetime.datetime.now().isoformat("T")
|
||||
log.validate()
|
||||
|
||||
log.time = -1
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
log.time = 'ABC'
|
||||
log.time = "ABC"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
|
||||
@@ -19,10 +19,11 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
Ensure an exception is raised when trying to
|
||||
cast an empty string to datetime.
|
||||
"""
|
||||
|
||||
class MyDoc(Document):
|
||||
dt = DateTimeField()
|
||||
|
||||
md = MyDoc(dt='')
|
||||
md = MyDoc(dt="")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
|
||||
def test_datetime_from_whitespace_string(self):
|
||||
@@ -30,16 +31,18 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
Ensure an exception is raised when trying to
|
||||
cast a whitespace-only string to datetime.
|
||||
"""
|
||||
|
||||
class MyDoc(Document):
|
||||
dt = DateTimeField()
|
||||
|
||||
md = MyDoc(dt=' ')
|
||||
md = MyDoc(dt=" ")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
|
||||
def test_default_value_utcnow(self):
|
||||
"""Ensure that default field values are used when creating
|
||||
a document.
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
created = DateTimeField(default=dt.datetime.utcnow)
|
||||
|
||||
@@ -48,8 +51,10 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
person.validate()
|
||||
person_created_t0 = person.created
|
||||
self.assertLess(person.created - utcnow, dt.timedelta(seconds=1))
|
||||
self.assertEqual(person_created_t0, person.created) # make sure it does not change
|
||||
self.assertEqual(person._data['created'], person.created)
|
||||
self.assertEqual(
|
||||
person_created_t0, person.created
|
||||
) # make sure it does not change
|
||||
self.assertEqual(person._data["created"], person.created)
|
||||
|
||||
def test_handling_microseconds(self):
|
||||
"""Tests showing pymongo datetime fields handling of microseconds.
|
||||
@@ -58,6 +63,7 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
|
||||
See: http://api.mongodb.org/python/current/api/bson/son.html#dt
|
||||
"""
|
||||
|
||||
class LogEntry(Document):
|
||||
date = DateTimeField()
|
||||
|
||||
@@ -103,6 +109,7 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
|
||||
def test_regular_usage(self):
|
||||
"""Tests for regular datetime fields"""
|
||||
|
||||
class LogEntry(Document):
|
||||
date = DateTimeField()
|
||||
|
||||
@@ -114,12 +121,12 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.validate()
|
||||
log.save()
|
||||
|
||||
for query in (d1, d1.isoformat(' ')):
|
||||
for query in (d1, d1.isoformat(" ")):
|
||||
log1 = LogEntry.objects.get(date=query)
|
||||
self.assertEqual(log, log1)
|
||||
|
||||
if dateutil:
|
||||
log1 = LogEntry.objects.get(date=d1.isoformat('T'))
|
||||
log1 = LogEntry.objects.get(date=d1.isoformat("T"))
|
||||
self.assertEqual(log, log1)
|
||||
|
||||
# create additional 19 log entries for a total of 20
|
||||
@@ -150,8 +157,7 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
self.assertEqual(logs.count(), 10)
|
||||
|
||||
logs = LogEntry.objects.filter(
|
||||
date__lte=dt.datetime(1980, 1, 1),
|
||||
date__gte=dt.datetime(1975, 1, 1),
|
||||
date__lte=dt.datetime(1980, 1, 1), date__gte=dt.datetime(1975, 1, 1)
|
||||
)
|
||||
self.assertEqual(logs.count(), 5)
|
||||
|
||||
@@ -159,6 +165,7 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
"""Ensure that invalid values cannot be assigned to datetime
|
||||
fields.
|
||||
"""
|
||||
|
||||
class LogEntry(Document):
|
||||
time = DateTimeField()
|
||||
|
||||
@@ -169,32 +176,32 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.time = dt.date.today()
|
||||
log.validate()
|
||||
|
||||
log.time = dt.datetime.now().isoformat(' ')
|
||||
log.time = dt.datetime.now().isoformat(" ")
|
||||
log.validate()
|
||||
|
||||
log.time = '2019-05-16 21:42:57.897847'
|
||||
log.time = "2019-05-16 21:42:57.897847"
|
||||
log.validate()
|
||||
|
||||
if dateutil:
|
||||
log.time = dt.datetime.now().isoformat('T')
|
||||
log.time = dt.datetime.now().isoformat("T")
|
||||
log.validate()
|
||||
|
||||
log.time = -1
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
log.time = 'ABC'
|
||||
log.time = "ABC"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
log.time = '2019-05-16 21:GARBAGE:12'
|
||||
log.time = "2019-05-16 21:GARBAGE:12"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
log.time = '2019-05-16 21:42:57.GARBAGE'
|
||||
log.time = "2019-05-16 21:42:57.GARBAGE"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
log.time = '2019-05-16 21:42:57.123.456'
|
||||
log.time = "2019-05-16 21:42:57.123.456"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
|
||||
def test_parse_datetime_as_str(self):
|
||||
class DTDoc(Document):
|
||||
date = DateTimeField()
|
||||
|
||||
date_str = '2019-03-02 22:26:01'
|
||||
date_str = "2019-03-02 22:26:01"
|
||||
|
||||
# make sure that passing a parsable datetime works
|
||||
dtd = DTDoc()
|
||||
@@ -206,7 +213,7 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
self.assertIsInstance(dtd.date, dt.datetime)
|
||||
self.assertEqual(str(dtd.date), date_str)
|
||||
|
||||
dtd.date = 'January 1st, 9999999999'
|
||||
dtd.date = "January 1st, 9999999999"
|
||||
self.assertRaises(ValidationError, dtd.validate)
|
||||
|
||||
|
||||
@@ -217,7 +224,7 @@ class TestDateTimeTzAware(MongoDBTestCase):
|
||||
connection._connections = {}
|
||||
connection._dbs = {}
|
||||
|
||||
connect(db='mongoenginetest', tz_aware=True)
|
||||
connect(db="mongoenginetest", tz_aware=True)
|
||||
|
||||
class LogEntry(Document):
|
||||
time = DateTimeField()
|
||||
@@ -228,4 +235,4 @@ class TestDateTimeTzAware(MongoDBTestCase):
|
||||
|
||||
log = LogEntry.objects.first()
|
||||
log.time = dt.datetime(2013, 1, 1, 0, 0, 0)
|
||||
self.assertEqual(['time'], log._changed_fields)
|
||||
self.assertEqual(["time"], log._changed_fields)
|
||||
|
||||
@@ -7,32 +7,31 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestDecimalField(MongoDBTestCase):
|
||||
|
||||
def test_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to decimal fields.
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
height = DecimalField(min_value=Decimal('0.1'),
|
||||
max_value=Decimal('3.5'))
|
||||
height = DecimalField(min_value=Decimal("0.1"), max_value=Decimal("3.5"))
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
Person(height=Decimal('1.89')).save()
|
||||
Person(height=Decimal("1.89")).save()
|
||||
person = Person.objects.first()
|
||||
self.assertEqual(person.height, Decimal('1.89'))
|
||||
self.assertEqual(person.height, Decimal("1.89"))
|
||||
|
||||
person.height = '2.0'
|
||||
person.height = "2.0"
|
||||
person.save()
|
||||
person.height = 0.01
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.height = Decimal('0.01')
|
||||
person.height = Decimal("0.01")
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.height = Decimal('4.0')
|
||||
person.height = Decimal("4.0")
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.height = 'something invalid'
|
||||
person.height = "something invalid"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
person_2 = Person(height='something invalid')
|
||||
person_2 = Person(height="something invalid")
|
||||
self.assertRaises(ValidationError, person_2.validate)
|
||||
|
||||
def test_comparison(self):
|
||||
@@ -58,7 +57,14 @@ class TestDecimalField(MongoDBTestCase):
|
||||
string_value = DecimalField(precision=4, force_string=True)
|
||||
|
||||
Person.drop_collection()
|
||||
values_to_store = [10, 10.1, 10.11, "10.111", Decimal("10.1111"), Decimal("10.11111")]
|
||||
values_to_store = [
|
||||
10,
|
||||
10.1,
|
||||
10.11,
|
||||
"10.111",
|
||||
Decimal("10.1111"),
|
||||
Decimal("10.11111"),
|
||||
]
|
||||
for store_at_creation in [True, False]:
|
||||
for value in values_to_store:
|
||||
# to_python is called explicitly if values were sent in the kwargs of __init__
|
||||
@@ -72,20 +78,27 @@ class TestDecimalField(MongoDBTestCase):
|
||||
|
||||
# How its stored
|
||||
expected = [
|
||||
{'float_value': 10.0, 'string_value': '10.0000'},
|
||||
{'float_value': 10.1, 'string_value': '10.1000'},
|
||||
{'float_value': 10.11, 'string_value': '10.1100'},
|
||||
{'float_value': 10.111, 'string_value': '10.1110'},
|
||||
{'float_value': 10.1111, 'string_value': '10.1111'},
|
||||
{'float_value': 10.1111, 'string_value': '10.1111'}]
|
||||
{"float_value": 10.0, "string_value": "10.0000"},
|
||||
{"float_value": 10.1, "string_value": "10.1000"},
|
||||
{"float_value": 10.11, "string_value": "10.1100"},
|
||||
{"float_value": 10.111, "string_value": "10.1110"},
|
||||
{"float_value": 10.1111, "string_value": "10.1111"},
|
||||
{"float_value": 10.1111, "string_value": "10.1111"},
|
||||
]
|
||||
expected.extend(expected)
|
||||
actual = list(Person.objects.exclude('id').as_pymongo())
|
||||
actual = list(Person.objects.exclude("id").as_pymongo())
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
# How it comes out locally
|
||||
expected = [Decimal('10.0000'), Decimal('10.1000'), Decimal('10.1100'),
|
||||
Decimal('10.1110'), Decimal('10.1111'), Decimal('10.1111')]
|
||||
expected = [
|
||||
Decimal("10.0000"),
|
||||
Decimal("10.1000"),
|
||||
Decimal("10.1100"),
|
||||
Decimal("10.1110"),
|
||||
Decimal("10.1111"),
|
||||
Decimal("10.1111"),
|
||||
]
|
||||
expected.extend(expected)
|
||||
for field_name in ['float_value', 'string_value']:
|
||||
for field_name in ["float_value", "string_value"]:
|
||||
actual = list(Person.objects().scalar(field_name))
|
||||
self.assertEqual(expected, actual)
|
||||
|
||||
@@ -6,95 +6,92 @@ from tests.utils import MongoDBTestCase, get_as_pymongo
|
||||
|
||||
|
||||
class TestDictField(MongoDBTestCase):
|
||||
|
||||
def test_storage(self):
|
||||
class BlogPost(Document):
|
||||
info = DictField()
|
||||
|
||||
BlogPost.drop_collection()
|
||||
|
||||
info = {'testkey': 'testvalue'}
|
||||
info = {"testkey": "testvalue"}
|
||||
post = BlogPost(info=info).save()
|
||||
self.assertEqual(
|
||||
get_as_pymongo(post),
|
||||
{
|
||||
'_id': post.id,
|
||||
'info': info
|
||||
}
|
||||
)
|
||||
self.assertEqual(get_as_pymongo(post), {"_id": post.id, "info": info})
|
||||
|
||||
def test_general_things(self):
|
||||
"""Ensure that dict types work as expected."""
|
||||
|
||||
class BlogPost(Document):
|
||||
info = DictField()
|
||||
|
||||
BlogPost.drop_collection()
|
||||
|
||||
post = BlogPost()
|
||||
post.info = 'my post'
|
||||
post.info = "my post"
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = ['test', 'test']
|
||||
post.info = ["test", "test"]
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = {'$title': 'test'}
|
||||
post.info = {"$title": "test"}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = {'nested': {'$title': 'test'}}
|
||||
post.info = {"nested": {"$title": "test"}}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = {'the.title': 'test'}
|
||||
post.info = {"the.title": "test"}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = {'nested': {'the.title': 'test'}}
|
||||
post.info = {"nested": {"the.title": "test"}}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = {1: 'test'}
|
||||
post.info = {1: "test"}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
|
||||
post.info = {'title': 'test'}
|
||||
post.info = {"title": "test"}
|
||||
post.save()
|
||||
|
||||
post = BlogPost()
|
||||
post.info = {'title': 'dollar_sign', 'details': {'te$t': 'test'}}
|
||||
post.info = {"title": "dollar_sign", "details": {"te$t": "test"}}
|
||||
post.save()
|
||||
|
||||
post = BlogPost()
|
||||
post.info = {'details': {'test': 'test'}}
|
||||
post.info = {"details": {"test": "test"}}
|
||||
post.save()
|
||||
|
||||
post = BlogPost()
|
||||
post.info = {'details': {'test': 3}}
|
||||
post.info = {"details": {"test": 3}}
|
||||
post.save()
|
||||
|
||||
self.assertEqual(BlogPost.objects.count(), 4)
|
||||
self.assertEqual(BlogPost.objects.filter(info__title__exact="test").count(), 1)
|
||||
self.assertEqual(
|
||||
BlogPost.objects.filter(info__title__exact='test').count(), 1)
|
||||
self.assertEqual(
|
||||
BlogPost.objects.filter(info__details__test__exact='test').count(), 1)
|
||||
BlogPost.objects.filter(info__details__test__exact="test").count(), 1
|
||||
)
|
||||
|
||||
post = BlogPost.objects.filter(info__title__exact='dollar_sign').first()
|
||||
self.assertIn('te$t', post['info']['details'])
|
||||
post = BlogPost.objects.filter(info__title__exact="dollar_sign").first()
|
||||
self.assertIn("te$t", post["info"]["details"])
|
||||
|
||||
# Confirm handles non strings or non existing keys
|
||||
self.assertEqual(
|
||||
BlogPost.objects.filter(info__details__test__exact=5).count(), 0)
|
||||
BlogPost.objects.filter(info__details__test__exact=5).count(), 0
|
||||
)
|
||||
self.assertEqual(
|
||||
BlogPost.objects.filter(info__made_up__test__exact='test').count(), 0)
|
||||
BlogPost.objects.filter(info__made_up__test__exact="test").count(), 0
|
||||
)
|
||||
|
||||
post = BlogPost.objects.create(info={'title': 'original'})
|
||||
post.info.update({'title': 'updated'})
|
||||
post = BlogPost.objects.create(info={"title": "original"})
|
||||
post.info.update({"title": "updated"})
|
||||
post.save()
|
||||
post.reload()
|
||||
self.assertEqual('updated', post.info['title'])
|
||||
self.assertEqual("updated", post.info["title"])
|
||||
|
||||
post.info.setdefault('authors', [])
|
||||
post.info.setdefault("authors", [])
|
||||
post.save()
|
||||
post.reload()
|
||||
self.assertEqual([], post.info['authors'])
|
||||
self.assertEqual([], post.info["authors"])
|
||||
|
||||
def test_dictfield_dump_document(self):
|
||||
"""Ensure a DictField can handle another document's dump."""
|
||||
|
||||
class Doc(Document):
|
||||
field = DictField()
|
||||
|
||||
@@ -106,51 +103,62 @@ class TestDictField(MongoDBTestCase):
|
||||
id = IntField(primary_key=True, default=1)
|
||||
recursive = DictField()
|
||||
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
|
||||
class ToEmbedChild(ToEmbedParent):
|
||||
pass
|
||||
|
||||
to_embed_recursive = ToEmbed(id=1).save()
|
||||
to_embed = ToEmbed(
|
||||
id=2, recursive=to_embed_recursive.to_mongo().to_dict()).save()
|
||||
id=2, recursive=to_embed_recursive.to_mongo().to_dict()
|
||||
).save()
|
||||
doc = Doc(field=to_embed.to_mongo().to_dict())
|
||||
doc.save()
|
||||
self.assertIsInstance(doc.field, dict)
|
||||
self.assertEqual(doc.field, {'_id': 2, 'recursive': {'_id': 1, 'recursive': {}}})
|
||||
self.assertEqual(
|
||||
doc.field, {"_id": 2, "recursive": {"_id": 1, "recursive": {}}}
|
||||
)
|
||||
# Same thing with a Document with a _cls field
|
||||
to_embed_recursive = ToEmbedChild(id=1).save()
|
||||
to_embed_child = ToEmbedChild(
|
||||
id=2, recursive=to_embed_recursive.to_mongo().to_dict()).save()
|
||||
id=2, recursive=to_embed_recursive.to_mongo().to_dict()
|
||||
).save()
|
||||
doc = Doc(field=to_embed_child.to_mongo().to_dict())
|
||||
doc.save()
|
||||
self.assertIsInstance(doc.field, dict)
|
||||
expected = {
|
||||
'_id': 2, '_cls': 'ToEmbedParent.ToEmbedChild',
|
||||
'recursive': {'_id': 1, '_cls': 'ToEmbedParent.ToEmbedChild', 'recursive': {}}
|
||||
"_id": 2,
|
||||
"_cls": "ToEmbedParent.ToEmbedChild",
|
||||
"recursive": {
|
||||
"_id": 1,
|
||||
"_cls": "ToEmbedParent.ToEmbedChild",
|
||||
"recursive": {},
|
||||
},
|
||||
}
|
||||
self.assertEqual(doc.field, expected)
|
||||
|
||||
def test_dictfield_strict(self):
|
||||
"""Ensure that dict field handles validation if provided a strict field type."""
|
||||
|
||||
class Simple(Document):
|
||||
mapping = DictField(field=IntField())
|
||||
|
||||
Simple.drop_collection()
|
||||
|
||||
e = Simple()
|
||||
e.mapping['someint'] = 1
|
||||
e.mapping["someint"] = 1
|
||||
e.save()
|
||||
|
||||
# try creating an invalid mapping
|
||||
with self.assertRaises(ValidationError):
|
||||
e.mapping['somestring'] = "abc"
|
||||
e.mapping["somestring"] = "abc"
|
||||
e.save()
|
||||
|
||||
def test_dictfield_complex(self):
|
||||
"""Ensure that the dict field can handle the complex types."""
|
||||
|
||||
class SettingBase(EmbeddedDocument):
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
|
||||
class StringSetting(SettingBase):
|
||||
value = StringField()
|
||||
@@ -164,70 +172,72 @@ class TestDictField(MongoDBTestCase):
|
||||
Simple.drop_collection()
|
||||
|
||||
e = Simple()
|
||||
e.mapping['somestring'] = StringSetting(value='foo')
|
||||
e.mapping['someint'] = IntegerSetting(value=42)
|
||||
e.mapping['nested_dict'] = {'number': 1, 'string': 'Hi!',
|
||||
'float': 1.001,
|
||||
'complex': IntegerSetting(value=42),
|
||||
'list': [IntegerSetting(value=42),
|
||||
StringSetting(value='foo')]}
|
||||
e.mapping["somestring"] = StringSetting(value="foo")
|
||||
e.mapping["someint"] = IntegerSetting(value=42)
|
||||
e.mapping["nested_dict"] = {
|
||||
"number": 1,
|
||||
"string": "Hi!",
|
||||
"float": 1.001,
|
||||
"complex": IntegerSetting(value=42),
|
||||
"list": [IntegerSetting(value=42), StringSetting(value="foo")],
|
||||
}
|
||||
e.save()
|
||||
|
||||
e2 = Simple.objects.get(id=e.id)
|
||||
self.assertIsInstance(e2.mapping['somestring'], StringSetting)
|
||||
self.assertIsInstance(e2.mapping['someint'], IntegerSetting)
|
||||
self.assertIsInstance(e2.mapping["somestring"], StringSetting)
|
||||
self.assertIsInstance(e2.mapping["someint"], IntegerSetting)
|
||||
|
||||
# Test querying
|
||||
self.assertEqual(Simple.objects.filter(mapping__someint__value=42).count(), 1)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__someint__value=42).count(), 1)
|
||||
Simple.objects.filter(mapping__nested_dict__number=1).count(), 1
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__number=1).count(), 1)
|
||||
Simple.objects.filter(mapping__nested_dict__complex__value=42).count(), 1
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__complex__value=42).count(), 1)
|
||||
Simple.objects.filter(mapping__nested_dict__list__0__value=42).count(), 1
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__list__0__value=42).count(), 1)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value='foo').count(), 1)
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value="foo").count(), 1
|
||||
)
|
||||
|
||||
# Confirm can update
|
||||
Simple.objects().update(set__mapping={"someint": IntegerSetting(value=10)})
|
||||
Simple.objects().update(
|
||||
set__mapping={"someint": IntegerSetting(value=10)})
|
||||
Simple.objects().update(
|
||||
set__mapping__nested_dict__list__1=StringSetting(value='Boo'))
|
||||
set__mapping__nested_dict__list__1=StringSetting(value="Boo")
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value='foo').count(), 0)
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value="foo").count(), 0
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value='Boo').count(), 1)
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value="Boo").count(), 1
|
||||
)
|
||||
|
||||
def test_push_dict(self):
|
||||
class MyModel(Document):
|
||||
events = ListField(DictField())
|
||||
|
||||
doc = MyModel(events=[{'a': 1}]).save()
|
||||
doc = MyModel(events=[{"a": 1}]).save()
|
||||
raw_doc = get_as_pymongo(doc)
|
||||
expected_raw_doc = {
|
||||
'_id': doc.id,
|
||||
'events': [{'a': 1}]
|
||||
}
|
||||
expected_raw_doc = {"_id": doc.id, "events": [{"a": 1}]}
|
||||
self.assertEqual(raw_doc, expected_raw_doc)
|
||||
|
||||
MyModel.objects(id=doc.id).update(push__events={})
|
||||
raw_doc = get_as_pymongo(doc)
|
||||
expected_raw_doc = {
|
||||
'_id': doc.id,
|
||||
'events': [{'a': 1}, {}]
|
||||
}
|
||||
expected_raw_doc = {"_id": doc.id, "events": [{"a": 1}, {}]}
|
||||
self.assertEqual(raw_doc, expected_raw_doc)
|
||||
|
||||
def test_ensure_unique_default_instances(self):
|
||||
"""Ensure that every field has it's own unique default instance."""
|
||||
|
||||
class D(Document):
|
||||
data = DictField()
|
||||
data2 = DictField(default=lambda: {})
|
||||
|
||||
d1 = D()
|
||||
d1.data['foo'] = 'bar'
|
||||
d1.data2['foo'] = 'bar'
|
||||
d1.data["foo"] = "bar"
|
||||
d1.data2["foo"] = "bar"
|
||||
d2 = D()
|
||||
self.assertEqual(d2.data, {})
|
||||
self.assertEqual(d2.data2, {})
|
||||
@@ -255,22 +265,25 @@ class TestDictField(MongoDBTestCase):
|
||||
class Embedded(EmbeddedDocument):
|
||||
name = StringField()
|
||||
|
||||
embed = Embedded(name='garbage')
|
||||
embed = Embedded(name="garbage")
|
||||
doc = DictFieldTest(dictionary=embed)
|
||||
with self.assertRaises(ValidationError) as ctx_err:
|
||||
doc.validate()
|
||||
self.assertIn("'dictionary'", str(ctx_err.exception))
|
||||
self.assertIn('Only dictionaries may be used in a DictField', str(ctx_err.exception))
|
||||
self.assertIn(
|
||||
"Only dictionaries may be used in a DictField", str(ctx_err.exception)
|
||||
)
|
||||
|
||||
def test_atomic_update_dict_field(self):
|
||||
"""Ensure that the entire DictField can be atomically updated."""
|
||||
|
||||
class Simple(Document):
|
||||
mapping = DictField(field=ListField(IntField(required=True)))
|
||||
|
||||
Simple.drop_collection()
|
||||
|
||||
e = Simple()
|
||||
e.mapping['someints'] = [1, 2]
|
||||
e.mapping["someints"] = [1, 2]
|
||||
e.save()
|
||||
e.update(set__mapping={"ints": [3, 4]})
|
||||
e.reload()
|
||||
@@ -279,7 +292,7 @@ class TestDictField(MongoDBTestCase):
|
||||
|
||||
# try creating an invalid mapping
|
||||
with self.assertRaises(ValueError):
|
||||
e.update(set__mapping={"somestrings": ["foo", "bar", ]})
|
||||
e.update(set__mapping={"somestrings": ["foo", "bar"]})
|
||||
|
||||
def test_dictfield_with_referencefield_complex_nesting_cases(self):
|
||||
"""Ensure complex nesting inside DictField handles dereferencing of ReferenceField(dbref=True | False)"""
|
||||
@@ -296,29 +309,33 @@ class TestDictField(MongoDBTestCase):
|
||||
mapping5 = DictField(DictField(field=ReferenceField(Doc, dbref=False)))
|
||||
mapping6 = DictField(ListField(DictField(ReferenceField(Doc, dbref=True))))
|
||||
mapping7 = DictField(ListField(DictField(ReferenceField(Doc, dbref=False))))
|
||||
mapping8 = DictField(ListField(DictField(ListField(ReferenceField(Doc, dbref=True)))))
|
||||
mapping9 = DictField(ListField(DictField(ListField(ReferenceField(Doc, dbref=False)))))
|
||||
mapping8 = DictField(
|
||||
ListField(DictField(ListField(ReferenceField(Doc, dbref=True))))
|
||||
)
|
||||
mapping9 = DictField(
|
||||
ListField(DictField(ListField(ReferenceField(Doc, dbref=False))))
|
||||
)
|
||||
|
||||
Doc.drop_collection()
|
||||
Simple.drop_collection()
|
||||
|
||||
d = Doc(s='aa').save()
|
||||
d = Doc(s="aa").save()
|
||||
e = Simple()
|
||||
e.mapping0['someint'] = e.mapping1['someint'] = d
|
||||
e.mapping2['someint'] = e.mapping3['someint'] = [d]
|
||||
e.mapping4['someint'] = e.mapping5['someint'] = {'d': d}
|
||||
e.mapping6['someint'] = e.mapping7['someint'] = [{'d': d}]
|
||||
e.mapping8['someint'] = e.mapping9['someint'] = [{'d': [d]}]
|
||||
e.mapping0["someint"] = e.mapping1["someint"] = d
|
||||
e.mapping2["someint"] = e.mapping3["someint"] = [d]
|
||||
e.mapping4["someint"] = e.mapping5["someint"] = {"d": d}
|
||||
e.mapping6["someint"] = e.mapping7["someint"] = [{"d": d}]
|
||||
e.mapping8["someint"] = e.mapping9["someint"] = [{"d": [d]}]
|
||||
e.save()
|
||||
|
||||
s = Simple.objects.first()
|
||||
self.assertIsInstance(s.mapping0['someint'], Doc)
|
||||
self.assertIsInstance(s.mapping1['someint'], Doc)
|
||||
self.assertIsInstance(s.mapping2['someint'][0], Doc)
|
||||
self.assertIsInstance(s.mapping3['someint'][0], Doc)
|
||||
self.assertIsInstance(s.mapping4['someint']['d'], Doc)
|
||||
self.assertIsInstance(s.mapping5['someint']['d'], Doc)
|
||||
self.assertIsInstance(s.mapping6['someint'][0]['d'], Doc)
|
||||
self.assertIsInstance(s.mapping7['someint'][0]['d'], Doc)
|
||||
self.assertIsInstance(s.mapping8['someint'][0]['d'][0], Doc)
|
||||
self.assertIsInstance(s.mapping9['someint'][0]['d'][0], Doc)
|
||||
self.assertIsInstance(s.mapping0["someint"], Doc)
|
||||
self.assertIsInstance(s.mapping1["someint"], Doc)
|
||||
self.assertIsInstance(s.mapping2["someint"][0], Doc)
|
||||
self.assertIsInstance(s.mapping3["someint"][0], Doc)
|
||||
self.assertIsInstance(s.mapping4["someint"]["d"], Doc)
|
||||
self.assertIsInstance(s.mapping5["someint"]["d"], Doc)
|
||||
self.assertIsInstance(s.mapping6["someint"][0]["d"], Doc)
|
||||
self.assertIsInstance(s.mapping7["someint"][0]["d"], Doc)
|
||||
self.assertIsInstance(s.mapping8["someint"][0]["d"][0], Doc)
|
||||
self.assertIsInstance(s.mapping9["someint"][0]["d"][0], Doc)
|
||||
|
||||
@@ -12,28 +12,29 @@ class TestEmailField(MongoDBTestCase):
|
||||
class User(Document):
|
||||
email = EmailField()
|
||||
|
||||
user = User(email='ross@example.com')
|
||||
user = User(email="ross@example.com")
|
||||
user.validate()
|
||||
|
||||
user = User(email='ross@example.co.uk')
|
||||
user = User(email="ross@example.co.uk")
|
||||
user.validate()
|
||||
|
||||
user = User(email=('Kofq@rhom0e4klgauOhpbpNdogawnyIKvQS0wk2mjqrgGQ5S'
|
||||
'aJIazqqWkm7.net'))
|
||||
user = User(
|
||||
email=("Kofq@rhom0e4klgauOhpbpNdogawnyIKvQS0wk2mjqrgGQ5SaJIazqqWkm7.net")
|
||||
)
|
||||
user.validate()
|
||||
|
||||
user = User(email='new-tld@example.technology')
|
||||
user = User(email="new-tld@example.technology")
|
||||
user.validate()
|
||||
|
||||
user = User(email='ross@example.com.')
|
||||
user = User(email="ross@example.com.")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
|
||||
# unicode domain
|
||||
user = User(email=u'user@пример.рф')
|
||||
user = User(email=u"user@пример.рф")
|
||||
user.validate()
|
||||
|
||||
# invalid unicode domain
|
||||
user = User(email=u'user@пример')
|
||||
user = User(email=u"user@пример")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
|
||||
# invalid data type
|
||||
@@ -44,20 +45,20 @@ class TestEmailField(MongoDBTestCase):
|
||||
# Don't run this test on pypy3, which doesn't support unicode regex:
|
||||
# https://bitbucket.org/pypy/pypy/issues/1821/regular-expression-doesnt-find-unicode
|
||||
if sys.version_info[:2] == (3, 2):
|
||||
raise SkipTest('unicode email addresses are not supported on PyPy 3')
|
||||
raise SkipTest("unicode email addresses are not supported on PyPy 3")
|
||||
|
||||
class User(Document):
|
||||
email = EmailField()
|
||||
|
||||
# unicode user shouldn't validate by default...
|
||||
user = User(email=u'Dörte@Sörensen.example.com')
|
||||
user = User(email=u"Dörte@Sörensen.example.com")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
|
||||
# ...but it should be fine with allow_utf8_user set to True
|
||||
class User(Document):
|
||||
email = EmailField(allow_utf8_user=True)
|
||||
|
||||
user = User(email=u'Dörte@Sörensen.example.com')
|
||||
user = User(email=u"Dörte@Sörensen.example.com")
|
||||
user.validate()
|
||||
|
||||
def test_email_field_domain_whitelist(self):
|
||||
@@ -65,22 +66,22 @@ class TestEmailField(MongoDBTestCase):
|
||||
email = EmailField()
|
||||
|
||||
# localhost domain shouldn't validate by default...
|
||||
user = User(email='me@localhost')
|
||||
user = User(email="me@localhost")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
|
||||
# ...but it should be fine if it's whitelisted
|
||||
class User(Document):
|
||||
email = EmailField(domain_whitelist=['localhost'])
|
||||
email = EmailField(domain_whitelist=["localhost"])
|
||||
|
||||
user = User(email='me@localhost')
|
||||
user = User(email="me@localhost")
|
||||
user.validate()
|
||||
|
||||
def test_email_domain_validation_fails_if_invalid_idn(self):
|
||||
class User(Document):
|
||||
email = EmailField()
|
||||
|
||||
invalid_idn = '.google.com'
|
||||
user = User(email='me@%s' % invalid_idn)
|
||||
invalid_idn = ".google.com"
|
||||
user = User(email="me@%s" % invalid_idn)
|
||||
with self.assertRaises(ValidationError) as ctx_err:
|
||||
user.validate()
|
||||
self.assertIn("domain failed IDN encoding", str(ctx_err.exception))
|
||||
@@ -89,9 +90,9 @@ class TestEmailField(MongoDBTestCase):
|
||||
class User(Document):
|
||||
email = EmailField()
|
||||
|
||||
valid_ipv4 = 'email@[127.0.0.1]'
|
||||
valid_ipv6 = 'email@[2001:dB8::1]'
|
||||
invalid_ip = 'email@[324.0.0.1]'
|
||||
valid_ipv4 = "email@[127.0.0.1]"
|
||||
valid_ipv6 = "email@[2001:dB8::1]"
|
||||
invalid_ip = "email@[324.0.0.1]"
|
||||
|
||||
# IP address as a domain shouldn't validate by default...
|
||||
user = User(email=valid_ipv4)
|
||||
@@ -119,12 +120,12 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
def test_email_field_honors_regex(self):
|
||||
class User(Document):
|
||||
email = EmailField(regex=r'\w+@example.com')
|
||||
email = EmailField(regex=r"\w+@example.com")
|
||||
|
||||
# Fails regex validation
|
||||
user = User(email='me@foo.com')
|
||||
user = User(email="me@foo.com")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
|
||||
# Passes regex validation
|
||||
user = User(email='me@example.com')
|
||||
user = User(email="me@example.com")
|
||||
self.assertIsNone(user.validate())
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from mongoengine import Document, StringField, ValidationError, EmbeddedDocument, EmbeddedDocumentField, \
|
||||
InvalidQueryError, LookUpError, IntField, GenericEmbeddedDocumentField, ListField, EmbeddedDocumentListField, \
|
||||
ReferenceField
|
||||
from mongoengine import (
|
||||
Document,
|
||||
StringField,
|
||||
ValidationError,
|
||||
EmbeddedDocument,
|
||||
EmbeddedDocumentField,
|
||||
InvalidQueryError,
|
||||
LookUpError,
|
||||
IntField,
|
||||
GenericEmbeddedDocumentField,
|
||||
ListField,
|
||||
EmbeddedDocumentListField,
|
||||
ReferenceField,
|
||||
)
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
|
||||
@@ -14,22 +25,24 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
field = EmbeddedDocumentField(MyDoc)
|
||||
self.assertEqual(field.document_type_obj, MyDoc)
|
||||
|
||||
field2 = EmbeddedDocumentField('MyDoc')
|
||||
self.assertEqual(field2.document_type_obj, 'MyDoc')
|
||||
field2 = EmbeddedDocumentField("MyDoc")
|
||||
self.assertEqual(field2.document_type_obj, "MyDoc")
|
||||
|
||||
def test___init___throw_error_if_document_type_is_not_EmbeddedDocument(self):
|
||||
with self.assertRaises(ValidationError):
|
||||
EmbeddedDocumentField(dict)
|
||||
|
||||
def test_document_type_throw_error_if_not_EmbeddedDocument_subclass(self):
|
||||
|
||||
class MyDoc(Document):
|
||||
name = StringField()
|
||||
|
||||
emb = EmbeddedDocumentField('MyDoc')
|
||||
emb = EmbeddedDocumentField("MyDoc")
|
||||
with self.assertRaises(ValidationError) as ctx:
|
||||
emb.document_type
|
||||
self.assertIn('Invalid embedded document class provided to an EmbeddedDocumentField', str(ctx.exception))
|
||||
self.assertIn(
|
||||
"Invalid embedded document class provided to an EmbeddedDocumentField",
|
||||
str(ctx.exception),
|
||||
)
|
||||
|
||||
def test_embedded_document_field_only_allow_subclasses_of_embedded_document(self):
|
||||
# Relates to #1661
|
||||
@@ -37,12 +50,14 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
name = StringField()
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
|
||||
class MyFailingDoc(Document):
|
||||
emb = EmbeddedDocumentField(MyDoc)
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
|
||||
class MyFailingdoc2(Document):
|
||||
emb = EmbeddedDocumentField('MyDoc')
|
||||
emb = EmbeddedDocumentField("MyDoc")
|
||||
|
||||
def test_query_embedded_document_attribute(self):
|
||||
class AdminSettings(EmbeddedDocument):
|
||||
@@ -55,34 +70,31 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
p = Person(
|
||||
settings=AdminSettings(foo1='bar1', foo2='bar2'),
|
||||
name='John',
|
||||
).save()
|
||||
p = Person(settings=AdminSettings(foo1="bar1", foo2="bar2"), name="John").save()
|
||||
|
||||
# Test non exiting attribute
|
||||
with self.assertRaises(InvalidQueryError) as ctx_err:
|
||||
Person.objects(settings__notexist='bar').first()
|
||||
Person.objects(settings__notexist="bar").first()
|
||||
self.assertEqual(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
|
||||
with self.assertRaises(LookUpError):
|
||||
Person.objects.only('settings.notexist')
|
||||
Person.objects.only("settings.notexist")
|
||||
|
||||
# Test existing attribute
|
||||
self.assertEqual(Person.objects(settings__foo1='bar1').first().id, p.id)
|
||||
only_p = Person.objects.only('settings.foo1').first()
|
||||
self.assertEqual(Person.objects(settings__foo1="bar1").first().id, p.id)
|
||||
only_p = Person.objects.only("settings.foo1").first()
|
||||
self.assertEqual(only_p.settings.foo1, p.settings.foo1)
|
||||
self.assertIsNone(only_p.settings.foo2)
|
||||
self.assertIsNone(only_p.name)
|
||||
|
||||
exclude_p = Person.objects.exclude('settings.foo1').first()
|
||||
exclude_p = Person.objects.exclude("settings.foo1").first()
|
||||
self.assertIsNone(exclude_p.settings.foo1)
|
||||
self.assertEqual(exclude_p.settings.foo2, p.settings.foo2)
|
||||
self.assertEqual(exclude_p.name, p.name)
|
||||
|
||||
def test_query_embedded_document_attribute_with_inheritance(self):
|
||||
class BaseSettings(EmbeddedDocument):
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
base_foo = StringField()
|
||||
|
||||
class AdminSettings(BaseSettings):
|
||||
@@ -93,26 +105,26 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
p = Person(settings=AdminSettings(base_foo='basefoo', sub_foo='subfoo'))
|
||||
p = Person(settings=AdminSettings(base_foo="basefoo", sub_foo="subfoo"))
|
||||
p.save()
|
||||
|
||||
# Test non exiting attribute
|
||||
with self.assertRaises(InvalidQueryError) as ctx_err:
|
||||
self.assertEqual(Person.objects(settings__notexist='bar').first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__notexist="bar").first().id, p.id)
|
||||
self.assertEqual(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
|
||||
# Test existing attribute
|
||||
self.assertEqual(Person.objects(settings__base_foo='basefoo').first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__sub_foo='subfoo').first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__base_foo="basefoo").first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__sub_foo="subfoo").first().id, p.id)
|
||||
|
||||
only_p = Person.objects.only('settings.base_foo', 'settings._cls').first()
|
||||
self.assertEqual(only_p.settings.base_foo, 'basefoo')
|
||||
only_p = Person.objects.only("settings.base_foo", "settings._cls").first()
|
||||
self.assertEqual(only_p.settings.base_foo, "basefoo")
|
||||
self.assertIsNone(only_p.settings.sub_foo)
|
||||
|
||||
def test_query_list_embedded_document_with_inheritance(self):
|
||||
class Post(EmbeddedDocument):
|
||||
title = StringField(max_length=120, required=True)
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
|
||||
class TextPost(Post):
|
||||
content = StringField()
|
||||
@@ -123,8 +135,8 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
class Record(Document):
|
||||
posts = ListField(EmbeddedDocumentField(Post))
|
||||
|
||||
record_movie = Record(posts=[MoviePost(author='John', title='foo')]).save()
|
||||
record_text = Record(posts=[TextPost(content='a', title='foo')]).save()
|
||||
record_movie = Record(posts=[MoviePost(author="John", title="foo")]).save()
|
||||
record_text = Record(posts=[TextPost(content="a", title="foo")]).save()
|
||||
|
||||
records = list(Record.objects(posts__author=record_movie.posts[0].author))
|
||||
self.assertEqual(len(records), 1)
|
||||
@@ -134,11 +146,10 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
self.assertEqual(len(records), 1)
|
||||
self.assertEqual(records[0].id, record_text.id)
|
||||
|
||||
self.assertEqual(Record.objects(posts__title='foo').count(), 2)
|
||||
self.assertEqual(Record.objects(posts__title="foo").count(), 2)
|
||||
|
||||
|
||||
class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
def test_generic_embedded_document(self):
|
||||
class Car(EmbeddedDocument):
|
||||
name = StringField()
|
||||
@@ -153,8 +164,8 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
person = Person(name='Test User')
|
||||
person.like = Car(name='Fiat')
|
||||
person = Person(name="Test User")
|
||||
person.like = Car(name="Fiat")
|
||||
person.save()
|
||||
|
||||
person = Person.objects.first()
|
||||
@@ -168,6 +179,7 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
def test_generic_embedded_document_choices(self):
|
||||
"""Ensure you can limit GenericEmbeddedDocument choices."""
|
||||
|
||||
class Car(EmbeddedDocument):
|
||||
name = StringField()
|
||||
|
||||
@@ -181,8 +193,8 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
person = Person(name='Test User')
|
||||
person.like = Car(name='Fiat')
|
||||
person = Person(name="Test User")
|
||||
person.like = Car(name="Fiat")
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
person.like = Dish(food="arroz", number=15)
|
||||
@@ -195,6 +207,7 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
"""Ensure you can limit GenericEmbeddedDocument choices inside
|
||||
a list field.
|
||||
"""
|
||||
|
||||
class Car(EmbeddedDocument):
|
||||
name = StringField()
|
||||
|
||||
@@ -208,8 +221,8 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
person = Person(name='Test User')
|
||||
person.likes = [Car(name='Fiat')]
|
||||
person = Person(name="Test User")
|
||||
person.likes = [Car(name="Fiat")]
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
person.likes = [Dish(food="arroz", number=15)]
|
||||
@@ -222,25 +235,23 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
"""
|
||||
Ensure fields with document choices validate given a valid choice.
|
||||
"""
|
||||
|
||||
class UserComments(EmbeddedDocument):
|
||||
author = StringField()
|
||||
message = StringField()
|
||||
|
||||
class BlogPost(Document):
|
||||
comments = ListField(
|
||||
GenericEmbeddedDocumentField(choices=(UserComments,))
|
||||
)
|
||||
comments = ListField(GenericEmbeddedDocumentField(choices=(UserComments,)))
|
||||
|
||||
# Ensure Validation Passes
|
||||
BlogPost(comments=[
|
||||
UserComments(author='user2', message='message2'),
|
||||
]).save()
|
||||
BlogPost(comments=[UserComments(author="user2", message="message2")]).save()
|
||||
|
||||
def test_choices_validation_documents_invalid(self):
|
||||
"""
|
||||
Ensure fields with document choices validate given an invalid choice.
|
||||
This should throw a ValidationError exception.
|
||||
"""
|
||||
|
||||
class UserComments(EmbeddedDocument):
|
||||
author = StringField()
|
||||
message = StringField()
|
||||
@@ -250,31 +261,28 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
message = StringField()
|
||||
|
||||
class BlogPost(Document):
|
||||
comments = ListField(
|
||||
GenericEmbeddedDocumentField(choices=(UserComments,))
|
||||
)
|
||||
comments = ListField(GenericEmbeddedDocumentField(choices=(UserComments,)))
|
||||
|
||||
# Single Entry Failure
|
||||
post = BlogPost(comments=[
|
||||
ModeratorComments(author='mod1', message='message1'),
|
||||
])
|
||||
post = BlogPost(comments=[ModeratorComments(author="mod1", message="message1")])
|
||||
self.assertRaises(ValidationError, post.save)
|
||||
|
||||
# Mixed Entry Failure
|
||||
post = BlogPost(comments=[
|
||||
ModeratorComments(author='mod1', message='message1'),
|
||||
UserComments(author='user2', message='message2'),
|
||||
])
|
||||
post = BlogPost(
|
||||
comments=[
|
||||
ModeratorComments(author="mod1", message="message1"),
|
||||
UserComments(author="user2", message="message2"),
|
||||
]
|
||||
)
|
||||
self.assertRaises(ValidationError, post.save)
|
||||
|
||||
def test_choices_validation_documents_inheritance(self):
|
||||
"""
|
||||
Ensure fields with document choices validate given subclass of choice.
|
||||
"""
|
||||
|
||||
class Comments(EmbeddedDocument):
|
||||
meta = {
|
||||
'abstract': True
|
||||
}
|
||||
meta = {"abstract": True}
|
||||
author = StringField()
|
||||
message = StringField()
|
||||
|
||||
@@ -282,14 +290,10 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
pass
|
||||
|
||||
class BlogPost(Document):
|
||||
comments = ListField(
|
||||
GenericEmbeddedDocumentField(choices=(Comments,))
|
||||
)
|
||||
comments = ListField(GenericEmbeddedDocumentField(choices=(Comments,)))
|
||||
|
||||
# Save Valid EmbeddedDocument Type
|
||||
BlogPost(comments=[
|
||||
UserComments(author='user2', message='message2'),
|
||||
]).save()
|
||||
BlogPost(comments=[UserComments(author="user2", message="message2")]).save()
|
||||
|
||||
def test_query_generic_embedded_document_attribute(self):
|
||||
class AdminSettings(EmbeddedDocument):
|
||||
@@ -299,28 +303,30 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
foo2 = StringField()
|
||||
|
||||
class Person(Document):
|
||||
settings = GenericEmbeddedDocumentField(choices=(AdminSettings, NonAdminSettings))
|
||||
settings = GenericEmbeddedDocumentField(
|
||||
choices=(AdminSettings, NonAdminSettings)
|
||||
)
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
p1 = Person(settings=AdminSettings(foo1='bar1')).save()
|
||||
p2 = Person(settings=NonAdminSettings(foo2='bar2')).save()
|
||||
p1 = Person(settings=AdminSettings(foo1="bar1")).save()
|
||||
p2 = Person(settings=NonAdminSettings(foo2="bar2")).save()
|
||||
|
||||
# Test non exiting attribute
|
||||
with self.assertRaises(InvalidQueryError) as ctx_err:
|
||||
Person.objects(settings__notexist='bar').first()
|
||||
Person.objects(settings__notexist="bar").first()
|
||||
self.assertEqual(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
|
||||
with self.assertRaises(LookUpError):
|
||||
Person.objects.only('settings.notexist')
|
||||
Person.objects.only("settings.notexist")
|
||||
|
||||
# Test existing attribute
|
||||
self.assertEqual(Person.objects(settings__foo1='bar1').first().id, p1.id)
|
||||
self.assertEqual(Person.objects(settings__foo2='bar2').first().id, p2.id)
|
||||
self.assertEqual(Person.objects(settings__foo1="bar1").first().id, p1.id)
|
||||
self.assertEqual(Person.objects(settings__foo2="bar2").first().id, p2.id)
|
||||
|
||||
def test_query_generic_embedded_document_attribute_with_inheritance(self):
|
||||
class BaseSettings(EmbeddedDocument):
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
base_foo = StringField()
|
||||
|
||||
class AdminSettings(BaseSettings):
|
||||
@@ -331,14 +337,14 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
p = Person(settings=AdminSettings(base_foo='basefoo', sub_foo='subfoo'))
|
||||
p = Person(settings=AdminSettings(base_foo="basefoo", sub_foo="subfoo"))
|
||||
p.save()
|
||||
|
||||
# Test non exiting attribute
|
||||
with self.assertRaises(InvalidQueryError) as ctx_err:
|
||||
self.assertEqual(Person.objects(settings__notexist='bar').first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__notexist="bar").first().id, p.id)
|
||||
self.assertEqual(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
|
||||
# Test existing attribute
|
||||
self.assertEqual(Person.objects(settings__base_foo='basefoo').first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__sub_foo='subfoo').first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__base_foo="basefoo").first().id, p.id)
|
||||
self.assertEqual(Person.objects(settings__sub_foo="subfoo").first().id, p.id)
|
||||
|
||||
@@ -7,7 +7,6 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestFloatField(MongoDBTestCase):
|
||||
|
||||
def test_float_ne_operator(self):
|
||||
class TestDocument(Document):
|
||||
float_fld = FloatField()
|
||||
@@ -23,6 +22,7 @@ class TestFloatField(MongoDBTestCase):
|
||||
def test_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to float fields.
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
height = FloatField(min_value=0.1, max_value=3.5)
|
||||
|
||||
@@ -33,7 +33,7 @@ class TestFloatField(MongoDBTestCase):
|
||||
person.height = 1.89
|
||||
person.validate()
|
||||
|
||||
person.height = '2.0'
|
||||
person.height = "2.0"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
person.height = 0.01
|
||||
@@ -42,7 +42,7 @@ class TestFloatField(MongoDBTestCase):
|
||||
person.height = 4.0
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
person_2 = Person(height='something invalid')
|
||||
person_2 = Person(height="something invalid")
|
||||
self.assertRaises(ValidationError, person_2.validate)
|
||||
|
||||
big_person = BigPerson()
|
||||
|
||||
@@ -5,10 +5,10 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestIntField(MongoDBTestCase):
|
||||
|
||||
def test_int_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to int fields.
|
||||
"""
|
||||
|
||||
class Person(Document):
|
||||
age = IntField(min_value=0, max_value=110)
|
||||
|
||||
@@ -26,7 +26,7 @@ class TestIntField(MongoDBTestCase):
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.age = 120
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
person.age = 'ten'
|
||||
person.age = "ten"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
def test_ne_operator(self):
|
||||
|
||||
@@ -25,7 +25,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
animal = Animal()
|
||||
oc = Ocurrence(animal=animal)
|
||||
self.assertIn('LazyReference', repr(oc.animal))
|
||||
self.assertIn("LazyReference", repr(oc.animal))
|
||||
|
||||
def test___getattr___unknown_attr_raises_attribute_error(self):
|
||||
class Animal(Document):
|
||||
@@ -93,7 +93,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
def test_lazy_reference_set(self):
|
||||
class Animal(Document):
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
|
||||
name = StringField()
|
||||
tag = StringField()
|
||||
@@ -109,18 +109,17 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
nick = StringField()
|
||||
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
sub_animal = SubAnimal(nick='doggo', name='dog').save()
|
||||
sub_animal = SubAnimal(nick="doggo", name="dog").save()
|
||||
for ref in (
|
||||
animal,
|
||||
animal.pk,
|
||||
DBRef(animal._get_collection_name(), animal.pk),
|
||||
LazyReference(Animal, animal.pk),
|
||||
|
||||
sub_animal,
|
||||
sub_animal.pk,
|
||||
DBRef(sub_animal._get_collection_name(), sub_animal.pk),
|
||||
LazyReference(SubAnimal, sub_animal.pk),
|
||||
):
|
||||
animal,
|
||||
animal.pk,
|
||||
DBRef(animal._get_collection_name(), animal.pk),
|
||||
LazyReference(Animal, animal.pk),
|
||||
sub_animal,
|
||||
sub_animal.pk,
|
||||
DBRef(sub_animal._get_collection_name(), sub_animal.pk),
|
||||
LazyReference(SubAnimal, sub_animal.pk),
|
||||
):
|
||||
p = Ocurrence(person="test", animal=ref).save()
|
||||
p.reload()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
@@ -144,12 +143,12 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
baddoc = BadDoc().save()
|
||||
for bad in (
|
||||
42,
|
||||
'foo',
|
||||
baddoc,
|
||||
DBRef(baddoc._get_collection_name(), animal.pk),
|
||||
LazyReference(BadDoc, animal.pk)
|
||||
):
|
||||
42,
|
||||
"foo",
|
||||
baddoc,
|
||||
DBRef(baddoc._get_collection_name(), animal.pk),
|
||||
LazyReference(BadDoc, animal.pk),
|
||||
):
|
||||
with self.assertRaises(ValidationError):
|
||||
p = Ocurrence(person="test", animal=bad).save()
|
||||
|
||||
@@ -157,6 +156,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
"""Ensure that LazyReferenceFields can be queried using objects and values
|
||||
of the type of the primary key of the referenced object.
|
||||
"""
|
||||
|
||||
class Member(Document):
|
||||
user_num = IntField(primary_key=True)
|
||||
|
||||
@@ -172,10 +172,10 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
m2 = Member(user_num=2)
|
||||
m2.save()
|
||||
|
||||
post1 = BlogPost(title='post 1', author=m1)
|
||||
post1 = BlogPost(title="post 1", author=m1)
|
||||
post1.save()
|
||||
|
||||
post2 = BlogPost(title='post 2', author=m2)
|
||||
post2 = BlogPost(title="post 2", author=m2)
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
@@ -192,6 +192,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
"""Ensure that LazyReferenceFields can be queried using objects and values
|
||||
of the type of the primary key of the referenced object.
|
||||
"""
|
||||
|
||||
class Member(Document):
|
||||
user_num = IntField(primary_key=True)
|
||||
|
||||
@@ -207,10 +208,10 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
m2 = Member(user_num=2)
|
||||
m2.save()
|
||||
|
||||
post1 = BlogPost(title='post 1', author=m1)
|
||||
post1 = BlogPost(title="post 1", author=m1)
|
||||
post1.save()
|
||||
|
||||
post2 = BlogPost(title='post 2', author=m2)
|
||||
post2 = BlogPost(title="post 2", author=m2)
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
@@ -240,19 +241,19 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
with self.assertRaises(KeyError):
|
||||
p.animal['name']
|
||||
p.animal["name"]
|
||||
with self.assertRaises(AttributeError):
|
||||
p.animal.name
|
||||
self.assertEqual(p.animal.pk, animal.pk)
|
||||
|
||||
self.assertEqual(p.animal_passthrough.name, "Leopard")
|
||||
self.assertEqual(p.animal_passthrough['name'], "Leopard")
|
||||
self.assertEqual(p.animal_passthrough["name"], "Leopard")
|
||||
|
||||
# Should not be able to access referenced document's methods
|
||||
with self.assertRaises(AttributeError):
|
||||
p.animal.save
|
||||
with self.assertRaises(KeyError):
|
||||
p.animal['save']
|
||||
p.animal["save"]
|
||||
|
||||
def test_lazy_reference_not_set(self):
|
||||
class Animal(Document):
|
||||
@@ -266,7 +267,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
Animal.drop_collection()
|
||||
Ocurrence.drop_collection()
|
||||
|
||||
Ocurrence(person='foo').save()
|
||||
Ocurrence(person="foo").save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIs(p.animal, None)
|
||||
|
||||
@@ -303,8 +304,8 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
Animal.drop_collection()
|
||||
Ocurrence.drop_collection()
|
||||
|
||||
animal1 = Animal(name='doggo').save()
|
||||
animal2 = Animal(name='cheeta').save()
|
||||
animal1 = Animal(name="doggo").save()
|
||||
animal2 = Animal(name="cheeta").save()
|
||||
|
||||
def check_fields_type(occ):
|
||||
self.assertIsInstance(occ.direct, LazyReference)
|
||||
@@ -316,8 +317,8 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
occ = Ocurrence(
|
||||
in_list=[animal1, animal2],
|
||||
in_embedded={'in_list': [animal1, animal2], 'direct': animal1},
|
||||
direct=animal1
|
||||
in_embedded={"in_list": [animal1, animal2], "direct": animal1},
|
||||
direct=animal1,
|
||||
).save()
|
||||
check_fields_type(occ)
|
||||
occ.reload()
|
||||
@@ -403,7 +404,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
def test_generic_lazy_reference_set(self):
|
||||
class Animal(Document):
|
||||
meta = {'allow_inheritance': True}
|
||||
meta = {"allow_inheritance": True}
|
||||
|
||||
name = StringField()
|
||||
tag = StringField()
|
||||
@@ -419,16 +420,18 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
nick = StringField()
|
||||
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
sub_animal = SubAnimal(nick='doggo', name='dog').save()
|
||||
sub_animal = SubAnimal(nick="doggo", name="dog").save()
|
||||
for ref in (
|
||||
animal,
|
||||
LazyReference(Animal, animal.pk),
|
||||
{'_cls': 'Animal', '_ref': DBRef(animal._get_collection_name(), animal.pk)},
|
||||
|
||||
sub_animal,
|
||||
LazyReference(SubAnimal, sub_animal.pk),
|
||||
{'_cls': 'SubAnimal', '_ref': DBRef(sub_animal._get_collection_name(), sub_animal.pk)},
|
||||
):
|
||||
animal,
|
||||
LazyReference(Animal, animal.pk),
|
||||
{"_cls": "Animal", "_ref": DBRef(animal._get_collection_name(), animal.pk)},
|
||||
sub_animal,
|
||||
LazyReference(SubAnimal, sub_animal.pk),
|
||||
{
|
||||
"_cls": "SubAnimal",
|
||||
"_ref": DBRef(sub_animal._get_collection_name(), sub_animal.pk),
|
||||
},
|
||||
):
|
||||
p = Ocurrence(person="test", animal=ref).save()
|
||||
p.reload()
|
||||
self.assertIsInstance(p.animal, (LazyReference, Document))
|
||||
@@ -441,7 +444,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
class Ocurrence(Document):
|
||||
person = StringField()
|
||||
animal = GenericLazyReferenceField(choices=['Animal'])
|
||||
animal = GenericLazyReferenceField(choices=["Animal"])
|
||||
|
||||
Animal.drop_collection()
|
||||
Ocurrence.drop_collection()
|
||||
@@ -451,12 +454,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
baddoc = BadDoc().save()
|
||||
for bad in (
|
||||
42,
|
||||
'foo',
|
||||
baddoc,
|
||||
LazyReference(BadDoc, animal.pk)
|
||||
):
|
||||
for bad in (42, "foo", baddoc, LazyReference(BadDoc, animal.pk)):
|
||||
with self.assertRaises(ValidationError):
|
||||
p = Ocurrence(person="test", animal=bad).save()
|
||||
|
||||
@@ -476,10 +474,10 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
m2 = Member(user_num=2)
|
||||
m2.save()
|
||||
|
||||
post1 = BlogPost(title='post 1', author=m1)
|
||||
post1 = BlogPost(title="post 1", author=m1)
|
||||
post1.save()
|
||||
|
||||
post2 = BlogPost(title='post 2', author=m2)
|
||||
post2 = BlogPost(title="post 2", author=m2)
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
@@ -504,7 +502,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
Animal.drop_collection()
|
||||
Ocurrence.drop_collection()
|
||||
|
||||
Ocurrence(person='foo').save()
|
||||
Ocurrence(person="foo").save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIs(p.animal, None)
|
||||
|
||||
@@ -515,7 +513,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
class Ocurrence(Document):
|
||||
person = StringField()
|
||||
animal = GenericLazyReferenceField('Animal')
|
||||
animal = GenericLazyReferenceField("Animal")
|
||||
|
||||
Animal.drop_collection()
|
||||
Ocurrence.drop_collection()
|
||||
@@ -542,8 +540,8 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
Animal.drop_collection()
|
||||
Ocurrence.drop_collection()
|
||||
|
||||
animal1 = Animal(name='doggo').save()
|
||||
animal2 = Animal(name='cheeta').save()
|
||||
animal1 = Animal(name="doggo").save()
|
||||
animal2 = Animal(name="cheeta").save()
|
||||
|
||||
def check_fields_type(occ):
|
||||
self.assertIsInstance(occ.direct, LazyReference)
|
||||
@@ -555,14 +553,20 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
occ = Ocurrence(
|
||||
in_list=[animal1, animal2],
|
||||
in_embedded={'in_list': [animal1, animal2], 'direct': animal1},
|
||||
direct=animal1
|
||||
in_embedded={"in_list": [animal1, animal2], "direct": animal1},
|
||||
direct=animal1,
|
||||
).save()
|
||||
check_fields_type(occ)
|
||||
occ.reload()
|
||||
check_fields_type(occ)
|
||||
animal1_ref = {'_cls': 'Animal', '_ref': DBRef(animal1._get_collection_name(), animal1.pk)}
|
||||
animal2_ref = {'_cls': 'Animal', '_ref': DBRef(animal2._get_collection_name(), animal2.pk)}
|
||||
animal1_ref = {
|
||||
"_cls": "Animal",
|
||||
"_ref": DBRef(animal1._get_collection_name(), animal1.pk),
|
||||
}
|
||||
animal2_ref = {
|
||||
"_cls": "Animal",
|
||||
"_ref": DBRef(animal2._get_collection_name(), animal2.pk),
|
||||
}
|
||||
occ.direct = animal1_ref
|
||||
occ.in_list = [animal1_ref, animal2_ref]
|
||||
occ.in_embedded.direct = animal1_ref
|
||||
|
||||
@@ -13,23 +13,26 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestLongField(MongoDBTestCase):
|
||||
|
||||
def test_long_field_is_considered_as_int64(self):
|
||||
"""
|
||||
Tests that long fields are stored as long in mongo, even if long
|
||||
value is small enough to be an int.
|
||||
"""
|
||||
|
||||
class TestLongFieldConsideredAsInt64(Document):
|
||||
some_long = LongField()
|
||||
|
||||
doc = TestLongFieldConsideredAsInt64(some_long=42).save()
|
||||
db = get_db()
|
||||
self.assertIsInstance(db.test_long_field_considered_as_int64.find()[0]['some_long'], Int64)
|
||||
self.assertIsInstance(
|
||||
db.test_long_field_considered_as_int64.find()[0]["some_long"], Int64
|
||||
)
|
||||
self.assertIsInstance(doc.some_long, six.integer_types)
|
||||
|
||||
def test_long_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to long fields.
|
||||
"""
|
||||
|
||||
class TestDocument(Document):
|
||||
value = LongField(min_value=0, max_value=110)
|
||||
|
||||
@@ -41,7 +44,7 @@ class TestLongField(MongoDBTestCase):
|
||||
self.assertRaises(ValidationError, doc.validate)
|
||||
doc.value = 120
|
||||
self.assertRaises(ValidationError, doc.validate)
|
||||
doc.value = 'ten'
|
||||
doc.value = "ten"
|
||||
self.assertRaises(ValidationError, doc.validate)
|
||||
|
||||
def test_long_ne_operator(self):
|
||||
|
||||
@@ -7,23 +7,24 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestMapField(MongoDBTestCase):
|
||||
|
||||
def test_mapfield(self):
|
||||
"""Ensure that the MapField handles the declared type."""
|
||||
|
||||
class Simple(Document):
|
||||
mapping = MapField(IntField())
|
||||
|
||||
Simple.drop_collection()
|
||||
|
||||
e = Simple()
|
||||
e.mapping['someint'] = 1
|
||||
e.mapping["someint"] = 1
|
||||
e.save()
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
e.mapping['somestring'] = "abc"
|
||||
e.mapping["somestring"] = "abc"
|
||||
e.save()
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
|
||||
class NoDeclaredType(Document):
|
||||
mapping = MapField()
|
||||
|
||||
@@ -45,38 +46,37 @@ class TestMapField(MongoDBTestCase):
|
||||
Extensible.drop_collection()
|
||||
|
||||
e = Extensible()
|
||||
e.mapping['somestring'] = StringSetting(value='foo')
|
||||
e.mapping['someint'] = IntegerSetting(value=42)
|
||||
e.mapping["somestring"] = StringSetting(value="foo")
|
||||
e.mapping["someint"] = IntegerSetting(value=42)
|
||||
e.save()
|
||||
|
||||
e2 = Extensible.objects.get(id=e.id)
|
||||
self.assertIsInstance(e2.mapping['somestring'], StringSetting)
|
||||
self.assertIsInstance(e2.mapping['someint'], IntegerSetting)
|
||||
self.assertIsInstance(e2.mapping["somestring"], StringSetting)
|
||||
self.assertIsInstance(e2.mapping["someint"], IntegerSetting)
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
e.mapping['someint'] = 123
|
||||
e.mapping["someint"] = 123
|
||||
e.save()
|
||||
|
||||
def test_embedded_mapfield_db_field(self):
|
||||
class Embedded(EmbeddedDocument):
|
||||
number = IntField(default=0, db_field='i')
|
||||
number = IntField(default=0, db_field="i")
|
||||
|
||||
class Test(Document):
|
||||
my_map = MapField(field=EmbeddedDocumentField(Embedded),
|
||||
db_field='x')
|
||||
my_map = MapField(field=EmbeddedDocumentField(Embedded), db_field="x")
|
||||
|
||||
Test.drop_collection()
|
||||
|
||||
test = Test()
|
||||
test.my_map['DICTIONARY_KEY'] = Embedded(number=1)
|
||||
test.my_map["DICTIONARY_KEY"] = Embedded(number=1)
|
||||
test.save()
|
||||
|
||||
Test.objects.update_one(inc__my_map__DICTIONARY_KEY__number=1)
|
||||
|
||||
test = Test.objects.get()
|
||||
self.assertEqual(test.my_map['DICTIONARY_KEY'].number, 2)
|
||||
self.assertEqual(test.my_map["DICTIONARY_KEY"].number, 2)
|
||||
doc = self.db.test.find_one()
|
||||
self.assertEqual(doc['x']['DICTIONARY_KEY']['i'], 2)
|
||||
self.assertEqual(doc["x"]["DICTIONARY_KEY"]["i"], 2)
|
||||
|
||||
def test_mapfield_numerical_index(self):
|
||||
"""Ensure that MapField accept numeric strings as indexes."""
|
||||
@@ -90,9 +90,9 @@ class TestMapField(MongoDBTestCase):
|
||||
Test.drop_collection()
|
||||
|
||||
test = Test()
|
||||
test.my_map['1'] = Embedded(name='test')
|
||||
test.my_map["1"] = Embedded(name="test")
|
||||
test.save()
|
||||
test.my_map['1'].name = 'test updated'
|
||||
test.my_map["1"].name = "test updated"
|
||||
test.save()
|
||||
|
||||
def test_map_field_lookup(self):
|
||||
@@ -110,15 +110,20 @@ class TestMapField(MongoDBTestCase):
|
||||
actions = MapField(EmbeddedDocumentField(Action))
|
||||
|
||||
Log.drop_collection()
|
||||
Log(name="wilson", visited={'friends': datetime.datetime.now()},
|
||||
actions={'friends': Action(operation='drink', object='beer')}).save()
|
||||
Log(
|
||||
name="wilson",
|
||||
visited={"friends": datetime.datetime.now()},
|
||||
actions={"friends": Action(operation="drink", object="beer")},
|
||||
).save()
|
||||
|
||||
self.assertEqual(1, Log.objects(
|
||||
visited__friends__exists=True).count())
|
||||
self.assertEqual(1, Log.objects(visited__friends__exists=True).count())
|
||||
|
||||
self.assertEqual(1, Log.objects(
|
||||
actions__friends__operation='drink',
|
||||
actions__friends__object='beer').count())
|
||||
self.assertEqual(
|
||||
1,
|
||||
Log.objects(
|
||||
actions__friends__operation="drink", actions__friends__object="beer"
|
||||
).count(),
|
||||
)
|
||||
|
||||
def test_map_field_unicode(self):
|
||||
class Info(EmbeddedDocument):
|
||||
@@ -130,15 +135,11 @@ class TestMapField(MongoDBTestCase):
|
||||
|
||||
BlogPost.drop_collection()
|
||||
|
||||
tree = BlogPost(info_dict={
|
||||
u"éééé": {
|
||||
'description': u"VALUE: éééé"
|
||||
}
|
||||
})
|
||||
tree = BlogPost(info_dict={u"éééé": {"description": u"VALUE: éééé"}})
|
||||
|
||||
tree.save()
|
||||
|
||||
self.assertEqual(
|
||||
BlogPost.objects.get(id=tree.id).info_dict[u"éééé"].description,
|
||||
u"VALUE: éééé"
|
||||
u"VALUE: éééé",
|
||||
)
|
||||
|
||||
@@ -26,15 +26,15 @@ class TestReferenceField(MongoDBTestCase):
|
||||
# with a document class name.
|
||||
self.assertRaises(ValidationError, ReferenceField, EmbeddedDocument)
|
||||
|
||||
user = User(name='Test User')
|
||||
user = User(name="Test User")
|
||||
|
||||
# Ensure that the referenced object must have been saved
|
||||
post1 = BlogPost(content='Chips and gravy taste good.')
|
||||
post1 = BlogPost(content="Chips and gravy taste good.")
|
||||
post1.author = user
|
||||
self.assertRaises(ValidationError, post1.save)
|
||||
|
||||
# Check that an invalid object type cannot be used
|
||||
post2 = BlogPost(content='Chips and chilli taste good.')
|
||||
post2 = BlogPost(content="Chips and chilli taste good.")
|
||||
post1.author = post2
|
||||
self.assertRaises(ValidationError, post1.validate)
|
||||
|
||||
@@ -59,7 +59,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
|
||||
class Person(Document):
|
||||
name = StringField()
|
||||
parent = ReferenceField('self')
|
||||
parent = ReferenceField("self")
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
@@ -74,7 +74,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
|
||||
class Person(Document):
|
||||
name = StringField()
|
||||
parent = ReferenceField('self', dbref=True)
|
||||
parent = ReferenceField("self", dbref=True)
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
@@ -82,8 +82,8 @@ class TestReferenceField(MongoDBTestCase):
|
||||
Person(name="Ross", parent=p1).save()
|
||||
|
||||
self.assertEqual(
|
||||
Person._get_collection().find_one({'name': 'Ross'})['parent'],
|
||||
DBRef('person', p1.pk)
|
||||
Person._get_collection().find_one({"name": "Ross"})["parent"],
|
||||
DBRef("person", p1.pk),
|
||||
)
|
||||
|
||||
p = Person.objects.get(name="Ross")
|
||||
@@ -97,21 +97,17 @@ class TestReferenceField(MongoDBTestCase):
|
||||
|
||||
class Person(Document):
|
||||
name = StringField()
|
||||
parent = ReferenceField('self', dbref=False)
|
||||
parent = ReferenceField("self", dbref=False)
|
||||
|
||||
p = Person(
|
||||
name='Steve',
|
||||
parent=DBRef('person', 'abcdefghijklmnop')
|
||||
p = Person(name="Steve", parent=DBRef("person", "abcdefghijklmnop"))
|
||||
self.assertEqual(
|
||||
p.to_mongo(), SON([("name", u"Steve"), ("parent", "abcdefghijklmnop")])
|
||||
)
|
||||
self.assertEqual(p.to_mongo(), SON([
|
||||
('name', u'Steve'),
|
||||
('parent', 'abcdefghijklmnop')
|
||||
]))
|
||||
|
||||
def test_objectid_reference_fields(self):
|
||||
class Person(Document):
|
||||
name = StringField()
|
||||
parent = ReferenceField('self', dbref=False)
|
||||
parent = ReferenceField("self", dbref=False)
|
||||
|
||||
Person.drop_collection()
|
||||
|
||||
@@ -119,8 +115,8 @@ class TestReferenceField(MongoDBTestCase):
|
||||
Person(name="Ross", parent=p1).save()
|
||||
|
||||
col = Person._get_collection()
|
||||
data = col.find_one({'name': 'Ross'})
|
||||
self.assertEqual(data['parent'], p1.pk)
|
||||
data = col.find_one({"name": "Ross"})
|
||||
self.assertEqual(data["parent"], p1.pk)
|
||||
|
||||
p = Person.objects.get(name="Ross")
|
||||
self.assertEqual(p.parent, p1)
|
||||
@@ -128,9 +124,10 @@ class TestReferenceField(MongoDBTestCase):
|
||||
def test_undefined_reference(self):
|
||||
"""Ensure that ReferenceFields may reference undefined Documents.
|
||||
"""
|
||||
|
||||
class Product(Document):
|
||||
name = StringField()
|
||||
company = ReferenceField('Company')
|
||||
company = ReferenceField("Company")
|
||||
|
||||
class Company(Document):
|
||||
name = StringField()
|
||||
@@ -138,12 +135,12 @@ class TestReferenceField(MongoDBTestCase):
|
||||
Product.drop_collection()
|
||||
Company.drop_collection()
|
||||
|
||||
ten_gen = Company(name='10gen')
|
||||
ten_gen = Company(name="10gen")
|
||||
ten_gen.save()
|
||||
mongodb = Product(name='MongoDB', company=ten_gen)
|
||||
mongodb = Product(name="MongoDB", company=ten_gen)
|
||||
mongodb.save()
|
||||
|
||||
me = Product(name='MongoEngine')
|
||||
me = Product(name="MongoEngine")
|
||||
me.save()
|
||||
|
||||
obj = Product.objects(company=ten_gen).first()
|
||||
@@ -160,6 +157,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
"""Ensure that ReferenceFields can be queried using objects and values
|
||||
of the type of the primary key of the referenced object.
|
||||
"""
|
||||
|
||||
class Member(Document):
|
||||
user_num = IntField(primary_key=True)
|
||||
|
||||
@@ -175,10 +173,10 @@ class TestReferenceField(MongoDBTestCase):
|
||||
m2 = Member(user_num=2)
|
||||
m2.save()
|
||||
|
||||
post1 = BlogPost(title='post 1', author=m1)
|
||||
post1 = BlogPost(title="post 1", author=m1)
|
||||
post1.save()
|
||||
|
||||
post2 = BlogPost(title='post 2', author=m2)
|
||||
post2 = BlogPost(title="post 2", author=m2)
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
@@ -191,6 +189,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
"""Ensure that ReferenceFields can be queried using objects and values
|
||||
of the type of the primary key of the referenced object.
|
||||
"""
|
||||
|
||||
class Member(Document):
|
||||
user_num = IntField(primary_key=True)
|
||||
|
||||
@@ -206,10 +205,10 @@ class TestReferenceField(MongoDBTestCase):
|
||||
m2 = Member(user_num=2)
|
||||
m2.save()
|
||||
|
||||
post1 = BlogPost(title='post 1', author=m1)
|
||||
post1 = BlogPost(title="post 1", author=m1)
|
||||
post1.save()
|
||||
|
||||
post2 = BlogPost(title='post 2', author=m2)
|
||||
post2 = BlogPost(title="post 2", author=m2)
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
|
||||
@@ -11,38 +11,38 @@ class TestSequenceField(MongoDBTestCase):
|
||||
id = SequenceField(primary_key=True)
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Person.drop_collection()
|
||||
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
Person.id.set_next_value(1000)
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 1000)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 1000)
|
||||
|
||||
def test_sequence_field_get_next_value(self):
|
||||
class Person(Document):
|
||||
id = SequenceField(primary_key=True)
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Person.drop_collection()
|
||||
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), 11)
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), 1)
|
||||
|
||||
@@ -50,40 +50,40 @@ class TestSequenceField(MongoDBTestCase):
|
||||
id = SequenceField(primary_key=True, value_decorator=str)
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Person.drop_collection()
|
||||
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), '11')
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.assertEqual(Person.id.get_next_value(), "11")
|
||||
self.db["mongoengine.counters"].drop()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), '1')
|
||||
self.assertEqual(Person.id.get_next_value(), "1")
|
||||
|
||||
def test_sequence_field_sequence_name(self):
|
||||
class Person(Document):
|
||||
id = SequenceField(primary_key=True, sequence_name='jelly')
|
||||
id = SequenceField(primary_key=True, sequence_name="jelly")
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Person.drop_collection()
|
||||
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'jelly.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "jelly.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'jelly.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "jelly.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
Person.id.set_next_value(1000)
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'jelly.id'})
|
||||
self.assertEqual(c['next'], 1000)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "jelly.id"})
|
||||
self.assertEqual(c["next"], 1000)
|
||||
|
||||
def test_multiple_sequence_fields(self):
|
||||
class Person(Document):
|
||||
@@ -91,14 +91,14 @@ class TestSequenceField(MongoDBTestCase):
|
||||
counter = SequenceField()
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Person.drop_collection()
|
||||
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
@@ -106,23 +106,23 @@ class TestSequenceField(MongoDBTestCase):
|
||||
counters = [i.counter for i in Person.objects]
|
||||
self.assertEqual(counters, range(1, 11))
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
Person.id.set_next_value(1000)
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 1000)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 1000)
|
||||
|
||||
Person.counter.set_next_value(999)
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.counter'})
|
||||
self.assertEqual(c['next'], 999)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.counter"})
|
||||
self.assertEqual(c["next"], 999)
|
||||
|
||||
def test_sequence_fields_reload(self):
|
||||
class Animal(Document):
|
||||
counter = SequenceField()
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Animal.drop_collection()
|
||||
|
||||
a = Animal(name="Boi").save()
|
||||
@@ -151,7 +151,7 @@ class TestSequenceField(MongoDBTestCase):
|
||||
id = SequenceField(primary_key=True)
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Animal.drop_collection()
|
||||
Person.drop_collection()
|
||||
|
||||
@@ -159,11 +159,11 @@ class TestSequenceField(MongoDBTestCase):
|
||||
Animal(name="Animal %s" % x).save()
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'animal.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "animal.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
@@ -171,32 +171,32 @@ class TestSequenceField(MongoDBTestCase):
|
||||
id = [i.id for i in Animal.objects]
|
||||
self.assertEqual(id, range(1, 11))
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'animal.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "animal.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
def test_sequence_field_value_decorator(self):
|
||||
class Person(Document):
|
||||
id = SequenceField(primary_key=True, value_decorator=str)
|
||||
name = StringField()
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Person.drop_collection()
|
||||
|
||||
for x in range(10):
|
||||
p = Person(name="Person %s" % x)
|
||||
p.save()
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, map(str, range(1, 11)))
|
||||
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'person.id'})
|
||||
self.assertEqual(c['next'], 10)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
|
||||
def test_embedded_sequence_field(self):
|
||||
class Comment(EmbeddedDocument):
|
||||
@@ -207,14 +207,18 @@ class TestSequenceField(MongoDBTestCase):
|
||||
title = StringField(required=True)
|
||||
comments = ListField(EmbeddedDocumentField(Comment))
|
||||
|
||||
self.db['mongoengine.counters'].drop()
|
||||
self.db["mongoengine.counters"].drop()
|
||||
Post.drop_collection()
|
||||
|
||||
Post(title="MongoEngine",
|
||||
comments=[Comment(content="NoSQL Rocks"),
|
||||
Comment(content="MongoEngine Rocks")]).save()
|
||||
c = self.db['mongoengine.counters'].find_one({'_id': 'comment.id'})
|
||||
self.assertEqual(c['next'], 2)
|
||||
Post(
|
||||
title="MongoEngine",
|
||||
comments=[
|
||||
Comment(content="NoSQL Rocks"),
|
||||
Comment(content="MongoEngine Rocks"),
|
||||
],
|
||||
).save()
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "comment.id"})
|
||||
self.assertEqual(c["next"], 2)
|
||||
post = Post.objects.first()
|
||||
self.assertEqual(1, post.comments[0].id)
|
||||
self.assertEqual(2, post.comments[1].id)
|
||||
@@ -223,7 +227,7 @@ class TestSequenceField(MongoDBTestCase):
|
||||
class Base(Document):
|
||||
name = StringField()
|
||||
counter = SequenceField()
|
||||
meta = {'abstract': True}
|
||||
meta = {"abstract": True}
|
||||
|
||||
class Foo(Base):
|
||||
pass
|
||||
@@ -231,24 +235,27 @@ class TestSequenceField(MongoDBTestCase):
|
||||
class Bar(Base):
|
||||
pass
|
||||
|
||||
bar = Bar(name='Bar')
|
||||
bar = Bar(name="Bar")
|
||||
bar.save()
|
||||
|
||||
foo = Foo(name='Foo')
|
||||
foo = Foo(name="Foo")
|
||||
foo.save()
|
||||
|
||||
self.assertTrue('base.counter' in
|
||||
self.db['mongoengine.counters'].find().distinct('_id'))
|
||||
self.assertFalse(('foo.counter' or 'bar.counter') in
|
||||
self.db['mongoengine.counters'].find().distinct('_id'))
|
||||
self.assertTrue(
|
||||
"base.counter" in self.db["mongoengine.counters"].find().distinct("_id")
|
||||
)
|
||||
self.assertFalse(
|
||||
("foo.counter" or "bar.counter")
|
||||
in self.db["mongoengine.counters"].find().distinct("_id")
|
||||
)
|
||||
self.assertNotEqual(foo.counter, bar.counter)
|
||||
self.assertEqual(foo._fields['counter'].owner_document, Base)
|
||||
self.assertEqual(bar._fields['counter'].owner_document, Base)
|
||||
self.assertEqual(foo._fields["counter"].owner_document, Base)
|
||||
self.assertEqual(bar._fields["counter"].owner_document, Base)
|
||||
|
||||
def test_no_inherited_sequencefield(self):
|
||||
class Base(Document):
|
||||
name = StringField()
|
||||
meta = {'abstract': True}
|
||||
meta = {"abstract": True}
|
||||
|
||||
class Foo(Base):
|
||||
counter = SequenceField()
|
||||
@@ -256,16 +263,19 @@ class TestSequenceField(MongoDBTestCase):
|
||||
class Bar(Base):
|
||||
counter = SequenceField()
|
||||
|
||||
bar = Bar(name='Bar')
|
||||
bar = Bar(name="Bar")
|
||||
bar.save()
|
||||
|
||||
foo = Foo(name='Foo')
|
||||
foo = Foo(name="Foo")
|
||||
foo.save()
|
||||
|
||||
self.assertFalse('base.counter' in
|
||||
self.db['mongoengine.counters'].find().distinct('_id'))
|
||||
self.assertTrue(('foo.counter' and 'bar.counter') in
|
||||
self.db['mongoengine.counters'].find().distinct('_id'))
|
||||
self.assertFalse(
|
||||
"base.counter" in self.db["mongoengine.counters"].find().distinct("_id")
|
||||
)
|
||||
self.assertTrue(
|
||||
("foo.counter" and "bar.counter")
|
||||
in self.db["mongoengine.counters"].find().distinct("_id")
|
||||
)
|
||||
self.assertEqual(foo.counter, bar.counter)
|
||||
self.assertEqual(foo._fields['counter'].owner_document, Foo)
|
||||
self.assertEqual(bar._fields['counter'].owner_document, Bar)
|
||||
self.assertEqual(foo._fields["counter"].owner_document, Foo)
|
||||
self.assertEqual(bar._fields["counter"].owner_document, Bar)
|
||||
|
||||
@@ -5,49 +5,53 @@ from tests.utils import MongoDBTestCase
|
||||
|
||||
|
||||
class TestURLField(MongoDBTestCase):
|
||||
|
||||
def test_validation(self):
|
||||
"""Ensure that URLFields validate urls properly."""
|
||||
|
||||
class Link(Document):
|
||||
url = URLField()
|
||||
|
||||
link = Link()
|
||||
link.url = 'google'
|
||||
link.url = "google"
|
||||
self.assertRaises(ValidationError, link.validate)
|
||||
|
||||
link.url = 'http://www.google.com:8080'
|
||||
link.url = "http://www.google.com:8080"
|
||||
link.validate()
|
||||
|
||||
def test_unicode_url_validation(self):
|
||||
"""Ensure unicode URLs are validated properly."""
|
||||
|
||||
class Link(Document):
|
||||
url = URLField()
|
||||
|
||||
link = Link()
|
||||
link.url = u'http://привет.com'
|
||||
link.url = u"http://привет.com"
|
||||
|
||||
# TODO fix URL validation - this *IS* a valid URL
|
||||
# For now we just want to make sure that the error message is correct
|
||||
with self.assertRaises(ValidationError) as ctx_err:
|
||||
link.validate()
|
||||
self.assertEqual(unicode(ctx_err.exception),
|
||||
u"ValidationError (Link:None) (Invalid URL: http://\u043f\u0440\u0438\u0432\u0435\u0442.com: ['url'])")
|
||||
self.assertEqual(
|
||||
unicode(ctx_err.exception),
|
||||
u"ValidationError (Link:None) (Invalid URL: http://\u043f\u0440\u0438\u0432\u0435\u0442.com: ['url'])",
|
||||
)
|
||||
|
||||
def test_url_scheme_validation(self):
|
||||
"""Ensure that URLFields validate urls with specific schemes properly.
|
||||
"""
|
||||
|
||||
class Link(Document):
|
||||
url = URLField()
|
||||
|
||||
class SchemeLink(Document):
|
||||
url = URLField(schemes=['ws', 'irc'])
|
||||
url = URLField(schemes=["ws", "irc"])
|
||||
|
||||
link = Link()
|
||||
link.url = 'ws://google.com'
|
||||
link.url = "ws://google.com"
|
||||
self.assertRaises(ValidationError, link.validate)
|
||||
|
||||
scheme_link = SchemeLink()
|
||||
scheme_link.url = 'ws://google.com'
|
||||
scheme_link.url = "ws://google.com"
|
||||
scheme_link.validate()
|
||||
|
||||
def test_underscore_allowed_in_domains_names(self):
|
||||
@@ -55,5 +59,5 @@ class TestURLField(MongoDBTestCase):
|
||||
url = URLField()
|
||||
|
||||
link = Link()
|
||||
link.url = 'https://san_leandro-ca.geebo.com'
|
||||
link.url = "https://san_leandro-ca.geebo.com"
|
||||
link.validate()
|
||||
|
||||
@@ -15,11 +15,8 @@ class TestUUIDField(MongoDBTestCase):
|
||||
uid = uuid.uuid4()
|
||||
person = Person(api_key=uid).save()
|
||||
self.assertEqual(
|
||||
get_as_pymongo(person),
|
||||
{'_id': person.id,
|
||||
'api_key': str(uid)
|
||||
}
|
||||
)
|
||||
get_as_pymongo(person), {"_id": person.id, "api_key": str(uid)}
|
||||
)
|
||||
|
||||
def test_field_string(self):
|
||||
"""Test UUID fields storing as String
|
||||
@@ -37,8 +34,10 @@ class TestUUIDField(MongoDBTestCase):
|
||||
person.api_key = api_key
|
||||
person.validate()
|
||||
|
||||
invalid = ('9d159858-549b-4975-9f98-dd2f987c113g',
|
||||
'9d159858-549b-4975-9f98-dd2f987c113')
|
||||
invalid = (
|
||||
"9d159858-549b-4975-9f98-dd2f987c113g",
|
||||
"9d159858-549b-4975-9f98-dd2f987c113",
|
||||
)
|
||||
for api_key in invalid:
|
||||
person.api_key = api_key
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
@@ -58,8 +57,10 @@ class TestUUIDField(MongoDBTestCase):
|
||||
person.api_key = api_key
|
||||
person.validate()
|
||||
|
||||
invalid = ('9d159858-549b-4975-9f98-dd2f987c113g',
|
||||
'9d159858-549b-4975-9f98-dd2f987c113')
|
||||
invalid = (
|
||||
"9d159858-549b-4975-9f98-dd2f987c113g",
|
||||
"9d159858-549b-4975-9f98-dd2f987c113",
|
||||
)
|
||||
for api_key in invalid:
|
||||
person.api_key = api_key
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
|
||||
Reference in New Issue
Block a user