ran unittest2pytest

This commit is contained in:
Bastien Gérard
2019-08-30 16:13:30 +03:00
parent aa6ff8c84a
commit ac25f4b98b
46 changed files with 4247 additions and 4428 deletions

View File

@@ -2,66 +2,67 @@ import unittest
from mongoengine import *
from mongoengine.queryset import QueryFieldList
import pytest
class TestQueryFieldList(unittest.TestCase):
def test_empty(self):
q = QueryFieldList()
self.assertFalse(q)
assert not q
q = QueryFieldList(always_include=["_cls"])
self.assertFalse(q)
assert not q
def test_include_include(self):
q = QueryFieldList()
q += QueryFieldList(
fields=["a", "b"], value=QueryFieldList.ONLY, _only_called=True
)
self.assertEqual(q.as_dict(), {"a": 1, "b": 1})
assert q.as_dict() == {"a": 1, "b": 1}
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.ONLY)
self.assertEqual(q.as_dict(), {"a": 1, "b": 1, "c": 1})
assert q.as_dict() == {"a": 1, "b": 1, "c": 1}
def test_include_exclude(self):
q = QueryFieldList()
q += QueryFieldList(fields=["a", "b"], value=QueryFieldList.ONLY)
self.assertEqual(q.as_dict(), {"a": 1, "b": 1})
assert q.as_dict() == {"a": 1, "b": 1}
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.EXCLUDE)
self.assertEqual(q.as_dict(), {"a": 1})
assert q.as_dict() == {"a": 1}
def test_exclude_exclude(self):
q = QueryFieldList()
q += QueryFieldList(fields=["a", "b"], value=QueryFieldList.EXCLUDE)
self.assertEqual(q.as_dict(), {"a": 0, "b": 0})
assert q.as_dict() == {"a": 0, "b": 0}
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.EXCLUDE)
self.assertEqual(q.as_dict(), {"a": 0, "b": 0, "c": 0})
assert q.as_dict() == {"a": 0, "b": 0, "c": 0}
def test_exclude_include(self):
q = QueryFieldList()
q += QueryFieldList(fields=["a", "b"], value=QueryFieldList.EXCLUDE)
self.assertEqual(q.as_dict(), {"a": 0, "b": 0})
assert q.as_dict() == {"a": 0, "b": 0}
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.ONLY)
self.assertEqual(q.as_dict(), {"c": 1})
assert q.as_dict() == {"c": 1}
def test_always_include(self):
q = QueryFieldList(always_include=["x", "y"])
q += QueryFieldList(fields=["a", "b", "x"], value=QueryFieldList.EXCLUDE)
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.ONLY)
self.assertEqual(q.as_dict(), {"x": 1, "y": 1, "c": 1})
assert q.as_dict() == {"x": 1, "y": 1, "c": 1}
def test_reset(self):
q = QueryFieldList(always_include=["x", "y"])
q += QueryFieldList(fields=["a", "b", "x"], value=QueryFieldList.EXCLUDE)
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.ONLY)
self.assertEqual(q.as_dict(), {"x": 1, "y": 1, "c": 1})
assert q.as_dict() == {"x": 1, "y": 1, "c": 1}
q.reset()
self.assertFalse(q)
assert not q
q += QueryFieldList(fields=["b", "c"], value=QueryFieldList.ONLY)
self.assertEqual(q.as_dict(), {"x": 1, "y": 1, "b": 1, "c": 1})
assert q.as_dict() == {"x": 1, "y": 1, "b": 1, "c": 1}
def test_using_a_slice(self):
q = QueryFieldList()
q += QueryFieldList(fields=["a"], value={"$slice": 5})
self.assertEqual(q.as_dict(), {"a": {"$slice": 5}})
assert q.as_dict() == {"a": {"$slice": 5}}
class TestOnlyExcludeAll(unittest.TestCase):
@@ -90,25 +91,23 @@ class TestOnlyExcludeAll(unittest.TestCase):
only = ["b", "c"]
qs = MyDoc.objects.fields(**{i: 1 for i in include})
self.assertEqual(
qs._loaded_fields.as_dict(), {"a": 1, "b": 1, "c": 1, "d": 1, "e": 1}
)
assert qs._loaded_fields.as_dict() == {"a": 1, "b": 1, "c": 1, "d": 1, "e": 1}
qs = qs.only(*only)
self.assertEqual(qs._loaded_fields.as_dict(), {"b": 1, "c": 1})
assert qs._loaded_fields.as_dict() == {"b": 1, "c": 1}
qs = qs.exclude(*exclude)
self.assertEqual(qs._loaded_fields.as_dict(), {"b": 1, "c": 1})
assert qs._loaded_fields.as_dict() == {"b": 1, "c": 1}
qs = MyDoc.objects.fields(**{i: 1 for i in include})
qs = qs.exclude(*exclude)
self.assertEqual(qs._loaded_fields.as_dict(), {"a": 1, "b": 1, "c": 1})
assert qs._loaded_fields.as_dict() == {"a": 1, "b": 1, "c": 1}
qs = qs.only(*only)
self.assertEqual(qs._loaded_fields.as_dict(), {"b": 1, "c": 1})
assert qs._loaded_fields.as_dict() == {"b": 1, "c": 1}
qs = MyDoc.objects.exclude(*exclude)
qs = qs.fields(**{i: 1 for i in include})
self.assertEqual(qs._loaded_fields.as_dict(), {"a": 1, "b": 1, "c": 1})
assert qs._loaded_fields.as_dict() == {"a": 1, "b": 1, "c": 1}
qs = qs.only(*only)
self.assertEqual(qs._loaded_fields.as_dict(), {"b": 1, "c": 1})
assert qs._loaded_fields.as_dict() == {"b": 1, "c": 1}
def test_slicing(self):
class MyDoc(Document):
@@ -127,15 +126,16 @@ class TestOnlyExcludeAll(unittest.TestCase):
qs = qs.exclude(*exclude)
qs = qs.only(*only)
qs = qs.fields(slice__b=5)
self.assertEqual(qs._loaded_fields.as_dict(), {"b": {"$slice": 5}, "c": 1})
assert qs._loaded_fields.as_dict() == {"b": {"$slice": 5}, "c": 1}
qs = qs.fields(slice__c=[5, 1])
self.assertEqual(
qs._loaded_fields.as_dict(), {"b": {"$slice": 5}, "c": {"$slice": [5, 1]}}
)
assert qs._loaded_fields.as_dict() == {
"b": {"$slice": 5},
"c": {"$slice": [5, 1]},
}
qs = qs.exclude("c")
self.assertEqual(qs._loaded_fields.as_dict(), {"b": {"$slice": 5}})
assert qs._loaded_fields.as_dict() == {"b": {"$slice": 5}}
def test_mix_slice_with_other_fields(self):
class MyDoc(Document):
@@ -144,7 +144,7 @@ class TestOnlyExcludeAll(unittest.TestCase):
c = ListField()
qs = MyDoc.objects.fields(a=1, b=0, slice__c=2)
self.assertEqual(qs._loaded_fields.as_dict(), {"c": {"$slice": 2}, "a": 1})
assert qs._loaded_fields.as_dict() == {"c": {"$slice": 2}, "a": 1}
def test_only(self):
"""Ensure that QuerySet.only only returns the requested fields.
@@ -153,20 +153,20 @@ class TestOnlyExcludeAll(unittest.TestCase):
person.save()
obj = self.Person.objects.only("name").get()
self.assertEqual(obj.name, person.name)
self.assertEqual(obj.age, None)
assert obj.name == person.name
assert obj.age == None
obj = self.Person.objects.only("age").get()
self.assertEqual(obj.name, None)
self.assertEqual(obj.age, person.age)
assert obj.name == None
assert obj.age == person.age
obj = self.Person.objects.only("name", "age").get()
self.assertEqual(obj.name, person.name)
self.assertEqual(obj.age, person.age)
assert obj.name == person.name
assert obj.age == person.age
obj = self.Person.objects.only(*("id", "name")).get()
self.assertEqual(obj.name, person.name)
self.assertEqual(obj.age, None)
assert obj.name == person.name
assert obj.age == None
# Check polymorphism still works
class Employee(self.Person):
@@ -176,12 +176,12 @@ class TestOnlyExcludeAll(unittest.TestCase):
employee.save()
obj = self.Person.objects(id=employee.id).only("age").get()
self.assertIsInstance(obj, Employee)
assert isinstance(obj, Employee)
# Check field names are looked up properly
obj = Employee.objects(id=employee.id).only("salary").get()
self.assertEqual(obj.salary, employee.salary)
self.assertEqual(obj.name, None)
assert obj.salary == employee.salary
assert obj.name == None
def test_only_with_subfields(self):
class User(EmbeddedDocument):
@@ -215,29 +215,29 @@ class TestOnlyExcludeAll(unittest.TestCase):
post.save()
obj = BlogPost.objects.only("author.name").get()
self.assertEqual(obj.content, None)
self.assertEqual(obj.author.email, None)
self.assertEqual(obj.author.name, "Test User")
self.assertEqual(obj.comments, [])
assert obj.content == None
assert obj.author.email == None
assert obj.author.name == "Test User"
assert obj.comments == []
obj = BlogPost.objects.only("various.test_dynamic.some").get()
self.assertEqual(obj.various["test_dynamic"].some, True)
assert obj.various["test_dynamic"].some == True
obj = BlogPost.objects.only("content", "comments.title").get()
self.assertEqual(obj.content, "Had a good coffee today...")
self.assertEqual(obj.author, None)
self.assertEqual(obj.comments[0].title, "I aggree")
self.assertEqual(obj.comments[1].title, "Coffee")
self.assertEqual(obj.comments[0].text, None)
self.assertEqual(obj.comments[1].text, None)
assert obj.content == "Had a good coffee today..."
assert obj.author == None
assert obj.comments[0].title == "I aggree"
assert obj.comments[1].title == "Coffee"
assert obj.comments[0].text == None
assert obj.comments[1].text == None
obj = BlogPost.objects.only("comments").get()
self.assertEqual(obj.content, None)
self.assertEqual(obj.author, None)
self.assertEqual(obj.comments[0].title, "I aggree")
self.assertEqual(obj.comments[1].title, "Coffee")
self.assertEqual(obj.comments[0].text, "Great post!")
self.assertEqual(obj.comments[1].text, "I hate coffee")
assert obj.content == None
assert obj.author == None
assert obj.comments[0].title == "I aggree"
assert obj.comments[1].title == "Coffee"
assert obj.comments[0].text == "Great post!"
assert obj.comments[1].text == "I hate coffee"
BlogPost.drop_collection()
@@ -266,10 +266,10 @@ class TestOnlyExcludeAll(unittest.TestCase):
post.save()
obj = BlogPost.objects.exclude("author", "comments.text").get()
self.assertEqual(obj.author, None)
self.assertEqual(obj.content, "Had a good coffee today...")
self.assertEqual(obj.comments[0].title, "I aggree")
self.assertEqual(obj.comments[0].text, None)
assert obj.author == None
assert obj.content == "Had a good coffee today..."
assert obj.comments[0].title == "I aggree"
assert obj.comments[0].text == None
BlogPost.drop_collection()
@@ -301,18 +301,18 @@ class TestOnlyExcludeAll(unittest.TestCase):
email.save()
obj = Email.objects.exclude("content_type").exclude("body").get()
self.assertEqual(obj.sender, "me")
self.assertEqual(obj.to, "you")
self.assertEqual(obj.subject, "From Russia with Love")
self.assertEqual(obj.body, None)
self.assertEqual(obj.content_type, None)
assert obj.sender == "me"
assert obj.to == "you"
assert obj.subject == "From Russia with Love"
assert obj.body == None
assert obj.content_type == None
obj = Email.objects.only("sender", "to").exclude("body", "sender").get()
self.assertEqual(obj.sender, None)
self.assertEqual(obj.to, "you")
self.assertEqual(obj.subject, None)
self.assertEqual(obj.body, None)
self.assertEqual(obj.content_type, None)
assert obj.sender == None
assert obj.to == "you"
assert obj.subject == None
assert obj.body == None
assert obj.content_type == None
obj = (
Email.objects.exclude("attachments.content")
@@ -320,13 +320,13 @@ class TestOnlyExcludeAll(unittest.TestCase):
.only("to", "attachments.name")
.get()
)
self.assertEqual(obj.attachments[0].name, "file1.doc")
self.assertEqual(obj.attachments[0].content, None)
self.assertEqual(obj.sender, None)
self.assertEqual(obj.to, "you")
self.assertEqual(obj.subject, None)
self.assertEqual(obj.body, None)
self.assertEqual(obj.content_type, None)
assert obj.attachments[0].name == "file1.doc"
assert obj.attachments[0].content == None
assert obj.sender == None
assert obj.to == "you"
assert obj.subject == None
assert obj.body == None
assert obj.content_type == None
Email.drop_collection()
@@ -355,11 +355,11 @@ class TestOnlyExcludeAll(unittest.TestCase):
.all_fields()
.get()
)
self.assertEqual(obj.sender, "me")
self.assertEqual(obj.to, "you")
self.assertEqual(obj.subject, "From Russia with Love")
self.assertEqual(obj.body, "Hello!")
self.assertEqual(obj.content_type, "text/plain")
assert obj.sender == "me"
assert obj.to == "you"
assert obj.subject == "From Russia with Love"
assert obj.body == "Hello!"
assert obj.content_type == "text/plain"
Email.drop_collection()
@@ -377,27 +377,27 @@ class TestOnlyExcludeAll(unittest.TestCase):
# first three
numbers = Numbers.objects.fields(slice__n=3).get()
self.assertEqual(numbers.n, [0, 1, 2])
assert numbers.n == [0, 1, 2]
# last three
numbers = Numbers.objects.fields(slice__n=-3).get()
self.assertEqual(numbers.n, [-3, -2, -1])
assert numbers.n == [-3, -2, -1]
# skip 2, limit 3
numbers = Numbers.objects.fields(slice__n=[2, 3]).get()
self.assertEqual(numbers.n, [2, 3, 4])
assert numbers.n == [2, 3, 4]
# skip to fifth from last, limit 4
numbers = Numbers.objects.fields(slice__n=[-5, 4]).get()
self.assertEqual(numbers.n, [-5, -4, -3, -2])
assert numbers.n == [-5, -4, -3, -2]
# skip to fifth from last, limit 10
numbers = Numbers.objects.fields(slice__n=[-5, 10]).get()
self.assertEqual(numbers.n, [-5, -4, -3, -2, -1])
assert numbers.n == [-5, -4, -3, -2, -1]
# skip to fifth from last, limit 10 dict method
numbers = Numbers.objects.fields(n={"$slice": [-5, 10]}).get()
self.assertEqual(numbers.n, [-5, -4, -3, -2, -1])
assert numbers.n == [-5, -4, -3, -2, -1]
def test_slicing_nested_fields(self):
"""Ensure that query slicing an embedded array works.
@@ -417,27 +417,27 @@ class TestOnlyExcludeAll(unittest.TestCase):
# first three
numbers = Numbers.objects.fields(slice__embedded__n=3).get()
self.assertEqual(numbers.embedded.n, [0, 1, 2])
assert numbers.embedded.n == [0, 1, 2]
# last three
numbers = Numbers.objects.fields(slice__embedded__n=-3).get()
self.assertEqual(numbers.embedded.n, [-3, -2, -1])
assert numbers.embedded.n == [-3, -2, -1]
# skip 2, limit 3
numbers = Numbers.objects.fields(slice__embedded__n=[2, 3]).get()
self.assertEqual(numbers.embedded.n, [2, 3, 4])
assert numbers.embedded.n == [2, 3, 4]
# skip to fifth from last, limit 4
numbers = Numbers.objects.fields(slice__embedded__n=[-5, 4]).get()
self.assertEqual(numbers.embedded.n, [-5, -4, -3, -2])
assert numbers.embedded.n == [-5, -4, -3, -2]
# skip to fifth from last, limit 10
numbers = Numbers.objects.fields(slice__embedded__n=[-5, 10]).get()
self.assertEqual(numbers.embedded.n, [-5, -4, -3, -2, -1])
assert numbers.embedded.n == [-5, -4, -3, -2, -1]
# skip to fifth from last, limit 10 dict method
numbers = Numbers.objects.fields(embedded__n={"$slice": [-5, 10]}).get()
self.assertEqual(numbers.embedded.n, [-5, -4, -3, -2, -1])
assert numbers.embedded.n == [-5, -4, -3, -2, -1]
def test_exclude_from_subclasses_docs(self):
class Base(Document):
@@ -456,9 +456,10 @@ class TestOnlyExcludeAll(unittest.TestCase):
User(username="mongodb", password="secret").save()
user = Base.objects().exclude("password", "wibble").first()
self.assertEqual(user.password, None)
assert user.password == None
self.assertRaises(LookUpError, Base.objects.exclude, "made_up")
with pytest.raises(LookUpError):
Base.objects.exclude("made_up")
if __name__ == "__main__":

View File

@@ -48,14 +48,14 @@ class TestGeoQueries(MongoDBTestCase):
# note that "near" will show the san francisco event, too,
# although it sorts to last.
events = self.Event.objects(location__near=[-87.67892, 41.9120459])
self.assertEqual(events.count(), 3)
self.assertEqual(list(events), [event1, event3, event2])
assert events.count() == 3
assert list(events) == [event1, event3, event2]
# ensure ordering is respected by "near"
events = self.Event.objects(location__near=[-87.67892, 41.9120459])
events = events.order_by("-date")
self.assertEqual(events.count(), 3)
self.assertEqual(list(events), [event3, event1, event2])
assert events.count() == 3
assert list(events) == [event3, event1, event2]
def test_near_and_max_distance(self):
"""Ensure the "max_distance" operator works alongside the "near"
@@ -66,8 +66,8 @@ class TestGeoQueries(MongoDBTestCase):
# find events within 10 degrees of san francisco
point = [-122.415579, 37.7566023]
events = self.Event.objects(location__near=point, location__max_distance=10)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0], event2)
assert events.count() == 1
assert events[0] == event2
def test_near_and_min_distance(self):
"""Ensure the "min_distance" operator works alongside the "near"
@@ -78,7 +78,7 @@ class TestGeoQueries(MongoDBTestCase):
# find events at least 10 degrees away of san francisco
point = [-122.415579, 37.7566023]
events = self.Event.objects(location__near=point, location__min_distance=10)
self.assertEqual(events.count(), 2)
assert events.count() == 2
def test_within_distance(self):
"""Make sure the "within_distance" operator works."""
@@ -87,29 +87,29 @@ class TestGeoQueries(MongoDBTestCase):
# find events within 5 degrees of pitchfork office, chicago
point_and_distance = [[-87.67892, 41.9120459], 5]
events = self.Event.objects(location__within_distance=point_and_distance)
self.assertEqual(events.count(), 2)
assert events.count() == 2
events = list(events)
self.assertNotIn(event2, events)
self.assertIn(event1, events)
self.assertIn(event3, events)
assert event2 not in events
assert event1 in events
assert event3 in events
# find events within 10 degrees of san francisco
point_and_distance = [[-122.415579, 37.7566023], 10]
events = self.Event.objects(location__within_distance=point_and_distance)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0], event2)
assert events.count() == 1
assert events[0] == event2
# find events within 1 degree of greenpoint, broolyn, nyc, ny
point_and_distance = [[-73.9509714, 40.7237134], 1]
events = self.Event.objects(location__within_distance=point_and_distance)
self.assertEqual(events.count(), 0)
assert events.count() == 0
# ensure ordering is respected by "within_distance"
point_and_distance = [[-87.67892, 41.9120459], 10]
events = self.Event.objects(location__within_distance=point_and_distance)
events = events.order_by("-date")
self.assertEqual(events.count(), 2)
self.assertEqual(events[0], event3)
assert events.count() == 2
assert events[0] == event3
def test_within_box(self):
"""Ensure the "within_box" operator works."""
@@ -118,8 +118,8 @@ class TestGeoQueries(MongoDBTestCase):
# check that within_box works
box = [(-125.0, 35.0), (-100.0, 40.0)]
events = self.Event.objects(location__within_box=box)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0].id, event2.id)
assert events.count() == 1
assert events[0].id == event2.id
def test_within_polygon(self):
"""Ensure the "within_polygon" operator works."""
@@ -133,8 +133,8 @@ class TestGeoQueries(MongoDBTestCase):
(-87.656164, 41.898061),
]
events = self.Event.objects(location__within_polygon=polygon)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0].id, event1.id)
assert events.count() == 1
assert events[0].id == event1.id
polygon2 = [
(-1.742249, 54.033586),
@@ -142,7 +142,7 @@ class TestGeoQueries(MongoDBTestCase):
(-4.40094, 53.389881),
]
events = self.Event.objects(location__within_polygon=polygon2)
self.assertEqual(events.count(), 0)
assert events.count() == 0
def test_2dsphere_near(self):
"""Make sure the "near" operator works with a PointField, which
@@ -154,14 +154,14 @@ class TestGeoQueries(MongoDBTestCase):
# note that "near" will show the san francisco event, too,
# although it sorts to last.
events = self.Event.objects(location__near=[-87.67892, 41.9120459])
self.assertEqual(events.count(), 3)
self.assertEqual(list(events), [event1, event3, event2])
assert events.count() == 3
assert list(events) == [event1, event3, event2]
# ensure ordering is respected by "near"
events = self.Event.objects(location__near=[-87.67892, 41.9120459])
events = events.order_by("-date")
self.assertEqual(events.count(), 3)
self.assertEqual(list(events), [event3, event1, event2])
assert events.count() == 3
assert list(events) == [event3, event1, event2]
def test_2dsphere_near_and_max_distance(self):
"""Ensure the "max_distance" operator works alongside the "near"
@@ -172,21 +172,21 @@ class TestGeoQueries(MongoDBTestCase):
# find events within 10km of san francisco
point = [-122.415579, 37.7566023]
events = self.Event.objects(location__near=point, location__max_distance=10000)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0], event2)
assert events.count() == 1
assert events[0] == event2
# find events within 1km of greenpoint, broolyn, nyc, ny
events = self.Event.objects(
location__near=[-73.9509714, 40.7237134], location__max_distance=1000
)
self.assertEqual(events.count(), 0)
assert events.count() == 0
# ensure ordering is respected by "near"
events = self.Event.objects(
location__near=[-87.67892, 41.9120459], location__max_distance=10000
).order_by("-date")
self.assertEqual(events.count(), 2)
self.assertEqual(events[0], event3)
assert events.count() == 2
assert events[0] == event3
def test_2dsphere_geo_within_box(self):
"""Ensure the "geo_within_box" operator works with a 2dsphere
@@ -197,8 +197,8 @@ class TestGeoQueries(MongoDBTestCase):
# check that within_box works
box = [(-125.0, 35.0), (-100.0, 40.0)]
events = self.Event.objects(location__geo_within_box=box)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0].id, event2.id)
assert events.count() == 1
assert events[0].id == event2.id
def test_2dsphere_geo_within_polygon(self):
"""Ensure the "geo_within_polygon" operator works with a
@@ -214,8 +214,8 @@ class TestGeoQueries(MongoDBTestCase):
(-87.656164, 41.898061),
]
events = self.Event.objects(location__geo_within_polygon=polygon)
self.assertEqual(events.count(), 1)
self.assertEqual(events[0].id, event1.id)
assert events.count() == 1
assert events[0].id == event1.id
polygon2 = [
(-1.742249, 54.033586),
@@ -223,7 +223,7 @@ class TestGeoQueries(MongoDBTestCase):
(-4.40094, 53.389881),
]
events = self.Event.objects(location__geo_within_polygon=polygon2)
self.assertEqual(events.count(), 0)
assert events.count() == 0
def test_2dsphere_near_and_min_max_distance(self):
"""Ensure "min_distace" and "max_distance" operators work well
@@ -237,15 +237,15 @@ class TestGeoQueries(MongoDBTestCase):
location__min_distance=1000,
location__max_distance=10000,
).order_by("-date")
self.assertEqual(events.count(), 1)
self.assertEqual(events[0], event3)
assert events.count() == 1
assert events[0] == event3
# ensure ordering is respected by "near" with "min_distance"
events = self.Event.objects(
location__near=[-87.67892, 41.9120459], location__min_distance=10000
).order_by("-date")
self.assertEqual(events.count(), 1)
self.assertEqual(events[0], event2)
assert events.count() == 1
assert events[0] == event2
def test_2dsphere_geo_within_center(self):
"""Make sure the "geo_within_center" operator works with a
@@ -256,11 +256,11 @@ class TestGeoQueries(MongoDBTestCase):
# find events within 5 degrees of pitchfork office, chicago
point_and_distance = [[-87.67892, 41.9120459], 2]
events = self.Event.objects(location__geo_within_center=point_and_distance)
self.assertEqual(events.count(), 2)
assert events.count() == 2
events = list(events)
self.assertNotIn(event2, events)
self.assertIn(event1, events)
self.assertIn(event3, events)
assert event2 not in events
assert event1 in events
assert event3 in events
def _test_embedded(self, point_field_class):
"""Helper test method ensuring given point field class works
@@ -290,8 +290,8 @@ class TestGeoQueries(MongoDBTestCase):
# note that "near" will show the san francisco event, too,
# although it sorts to last.
events = Event.objects(venue__location__near=[-87.67892, 41.9120459])
self.assertEqual(events.count(), 3)
self.assertEqual(list(events), [event1, event3, event2])
assert events.count() == 3
assert list(events) == [event1, event3, event2]
def test_geo_spatial_embedded(self):
"""Make sure GeoPointField works properly in an embedded document."""
@@ -319,55 +319,55 @@ class TestGeoQueries(MongoDBTestCase):
# Finds both points because they are within 60 km of the reference
# point equidistant between them.
points = Point.objects(location__near_sphere=[-122, 37.5])
self.assertEqual(points.count(), 2)
assert points.count() == 2
# Same behavior for _within_spherical_distance
points = Point.objects(
location__within_spherical_distance=[[-122, 37.5], 60 / earth_radius]
)
self.assertEqual(points.count(), 2)
assert points.count() == 2
points = Point.objects(
location__near_sphere=[-122, 37.5], location__max_distance=60 / earth_radius
)
self.assertEqual(points.count(), 2)
assert points.count() == 2
# Test query works with max_distance, being farer from one point
points = Point.objects(
location__near_sphere=[-122, 37.8], location__max_distance=60 / earth_radius
)
close_point = points.first()
self.assertEqual(points.count(), 1)
assert points.count() == 1
# Test query works with min_distance, being farer from one point
points = Point.objects(
location__near_sphere=[-122, 37.8], location__min_distance=60 / earth_radius
)
self.assertEqual(points.count(), 1)
assert points.count() == 1
far_point = points.first()
self.assertNotEqual(close_point, far_point)
assert close_point != far_point
# Finds both points, but orders the north point first because it's
# closer to the reference point to the north.
points = Point.objects(location__near_sphere=[-122, 38.5])
self.assertEqual(points.count(), 2)
self.assertEqual(points[0].id, north_point.id)
self.assertEqual(points[1].id, south_point.id)
assert points.count() == 2
assert points[0].id == north_point.id
assert points[1].id == south_point.id
# Finds both points, but orders the south point first because it's
# closer to the reference point to the south.
points = Point.objects(location__near_sphere=[-122, 36.5])
self.assertEqual(points.count(), 2)
self.assertEqual(points[0].id, south_point.id)
self.assertEqual(points[1].id, north_point.id)
assert points.count() == 2
assert points[0].id == south_point.id
assert points[1].id == north_point.id
# Finds only one point because only the first point is within 60km of
# the reference point to the south.
points = Point.objects(
location__within_spherical_distance=[[-122, 36.5], 60 / earth_radius]
)
self.assertEqual(points.count(), 1)
self.assertEqual(points[0].id, south_point.id)
assert points.count() == 1
assert points[0].id == south_point.id
def test_linestring(self):
class Road(Document):
@@ -381,13 +381,13 @@ class TestGeoQueries(MongoDBTestCase):
# near
point = {"type": "Point", "coordinates": [40, 5]}
roads = Road.objects.filter(line__near=point["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__near=point).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__near={"$geometry": point}).count()
self.assertEqual(1, roads)
assert 1 == roads
# Within
polygon = {
@@ -395,37 +395,37 @@ class TestGeoQueries(MongoDBTestCase):
"coordinates": [[[40, 5], [40, 6], [41, 6], [41, 5], [40, 5]]],
}
roads = Road.objects.filter(line__geo_within=polygon["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__geo_within=polygon).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__geo_within={"$geometry": polygon}).count()
self.assertEqual(1, roads)
assert 1 == roads
# Intersects
line = {"type": "LineString", "coordinates": [[40, 5], [40, 6]]}
roads = Road.objects.filter(line__geo_intersects=line["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__geo_intersects=line).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__geo_intersects={"$geometry": line}).count()
self.assertEqual(1, roads)
assert 1 == roads
polygon = {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [41, 5], [40, 5]]],
}
roads = Road.objects.filter(line__geo_intersects=polygon["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__geo_intersects=polygon).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(line__geo_intersects={"$geometry": polygon}).count()
self.assertEqual(1, roads)
assert 1 == roads
def test_polygon(self):
class Road(Document):
@@ -439,13 +439,13 @@ class TestGeoQueries(MongoDBTestCase):
# near
point = {"type": "Point", "coordinates": [40, 5]}
roads = Road.objects.filter(poly__near=point["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__near=point).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__near={"$geometry": point}).count()
self.assertEqual(1, roads)
assert 1 == roads
# Within
polygon = {
@@ -453,37 +453,37 @@ class TestGeoQueries(MongoDBTestCase):
"coordinates": [[[40, 5], [40, 6], [41, 6], [41, 5], [40, 5]]],
}
roads = Road.objects.filter(poly__geo_within=polygon["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__geo_within=polygon).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__geo_within={"$geometry": polygon}).count()
self.assertEqual(1, roads)
assert 1 == roads
# Intersects
line = {"type": "LineString", "coordinates": [[40, 5], [41, 6]]}
roads = Road.objects.filter(poly__geo_intersects=line["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__geo_intersects=line).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__geo_intersects={"$geometry": line}).count()
self.assertEqual(1, roads)
assert 1 == roads
polygon = {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [41, 5], [40, 5]]],
}
roads = Road.objects.filter(poly__geo_intersects=polygon["coordinates"]).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__geo_intersects=polygon).count()
self.assertEqual(1, roads)
assert 1 == roads
roads = Road.objects.filter(poly__geo_intersects={"$geometry": polygon}).count()
self.assertEqual(1, roads)
assert 1 == roads
def test_aspymongo_with_only(self):
"""Ensure as_pymongo works with only"""
@@ -495,13 +495,10 @@ class TestGeoQueries(MongoDBTestCase):
p = Place(location=[24.946861267089844, 60.16311983618494])
p.save()
qs = Place.objects().only("location")
self.assertDictEqual(
qs.as_pymongo()[0]["location"],
{
u"type": u"Point",
u"coordinates": [24.946861267089844, 60.16311983618494],
},
)
assert qs.as_pymongo()[0]["location"] == {
u"type": u"Point",
u"coordinates": [24.946861267089844, 60.16311983618494],
}
def test_2dsphere_point_sets_correctly(self):
class Location(Document):
@@ -511,11 +508,11 @@ class TestGeoQueries(MongoDBTestCase):
Location(loc=[1, 2]).save()
loc = Location.objects.as_pymongo()[0]
self.assertEqual(loc["loc"], {"type": "Point", "coordinates": [1, 2]})
assert loc["loc"] == {"type": "Point", "coordinates": [1, 2]}
Location.objects.update(set__loc=[2, 1])
loc = Location.objects.as_pymongo()[0]
self.assertEqual(loc["loc"], {"type": "Point", "coordinates": [2, 1]})
assert loc["loc"] == {"type": "Point", "coordinates": [2, 1]}
def test_2dsphere_linestring_sets_correctly(self):
class Location(Document):
@@ -525,15 +522,11 @@ class TestGeoQueries(MongoDBTestCase):
Location(line=[[1, 2], [2, 2]]).save()
loc = Location.objects.as_pymongo()[0]
self.assertEqual(
loc["line"], {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}
)
assert loc["line"] == {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}
Location.objects.update(set__line=[[2, 1], [1, 2]])
loc = Location.objects.as_pymongo()[0]
self.assertEqual(
loc["line"], {"type": "LineString", "coordinates": [[2, 1], [1, 2]]}
)
assert loc["line"] == {"type": "LineString", "coordinates": [[2, 1], [1, 2]]}
def test_geojson_PolygonField(self):
class Location(Document):
@@ -543,17 +536,17 @@ class TestGeoQueries(MongoDBTestCase):
Location(poly=[[[40, 5], [40, 6], [41, 6], [40, 5]]]).save()
loc = Location.objects.as_pymongo()[0]
self.assertEqual(
loc["poly"],
{"type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]]},
)
assert loc["poly"] == {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]],
}
Location.objects.update(set__poly=[[[40, 4], [40, 6], [41, 6], [40, 4]]])
loc = Location.objects.as_pymongo()[0]
self.assertEqual(
loc["poly"],
{"type": "Polygon", "coordinates": [[[40, 4], [40, 6], [41, 6], [40, 4]]]},
)
assert loc["poly"] == {
"type": "Polygon",
"coordinates": [[[40, 4], [40, 6], [41, 6], [40, 4]]],
}
if __name__ == "__main__":

View File

@@ -14,14 +14,14 @@ class TestFindAndModify(unittest.TestCase):
Doc.drop_collection()
def assertDbEqual(self, docs):
self.assertEqual(list(Doc._collection.find().sort("id")), docs)
assert list(Doc._collection.find().sort("id")) == docs
def test_modify(self):
Doc(id=0, value=0).save()
doc = Doc(id=1, value=1).save()
old_doc = Doc.objects(id=1).modify(set__value=-1)
self.assertEqual(old_doc.to_json(), doc.to_json())
assert old_doc.to_json() == doc.to_json()
self.assertDbEqual([{"_id": 0, "value": 0}, {"_id": 1, "value": -1}])
def test_modify_with_new(self):
@@ -30,18 +30,18 @@ class TestFindAndModify(unittest.TestCase):
new_doc = Doc.objects(id=1).modify(set__value=-1, new=True)
doc.value = -1
self.assertEqual(new_doc.to_json(), doc.to_json())
assert new_doc.to_json() == doc.to_json()
self.assertDbEqual([{"_id": 0, "value": 0}, {"_id": 1, "value": -1}])
def test_modify_not_existing(self):
Doc(id=0, value=0).save()
self.assertEqual(Doc.objects(id=1).modify(set__value=-1), None)
assert Doc.objects(id=1).modify(set__value=-1) == None
self.assertDbEqual([{"_id": 0, "value": 0}])
def test_modify_with_upsert(self):
Doc(id=0, value=0).save()
old_doc = Doc.objects(id=1).modify(set__value=1, upsert=True)
self.assertEqual(old_doc, None)
assert old_doc == None
self.assertDbEqual([{"_id": 0, "value": 0}, {"_id": 1, "value": 1}])
def test_modify_with_upsert_existing(self):
@@ -49,13 +49,13 @@ class TestFindAndModify(unittest.TestCase):
doc = Doc(id=1, value=1).save()
old_doc = Doc.objects(id=1).modify(set__value=-1, upsert=True)
self.assertEqual(old_doc.to_json(), doc.to_json())
assert old_doc.to_json() == doc.to_json()
self.assertDbEqual([{"_id": 0, "value": 0}, {"_id": 1, "value": -1}])
def test_modify_with_upsert_with_new(self):
Doc(id=0, value=0).save()
new_doc = Doc.objects(id=1).modify(upsert=True, new=True, set__value=1)
self.assertEqual(new_doc.to_mongo(), {"_id": 1, "value": 1})
assert new_doc.to_mongo() == {"_id": 1, "value": 1}
self.assertDbEqual([{"_id": 0, "value": 0}, {"_id": 1, "value": 1}])
def test_modify_with_remove(self):
@@ -63,12 +63,12 @@ class TestFindAndModify(unittest.TestCase):
doc = Doc(id=1, value=1).save()
old_doc = Doc.objects(id=1).modify(remove=True)
self.assertEqual(old_doc.to_json(), doc.to_json())
assert old_doc.to_json() == doc.to_json()
self.assertDbEqual([{"_id": 0, "value": 0}])
def test_find_and_modify_with_remove_not_existing(self):
Doc(id=0, value=0).save()
self.assertEqual(Doc.objects(id=1).modify(remove=True), None)
assert Doc.objects(id=1).modify(remove=True) == None
self.assertDbEqual([{"_id": 0, "value": 0}])
def test_modify_with_order_by(self):
@@ -78,7 +78,7 @@ class TestFindAndModify(unittest.TestCase):
doc = Doc(id=3, value=0).save()
old_doc = Doc.objects().order_by("-id").modify(set__value=-1)
self.assertEqual(old_doc.to_json(), doc.to_json())
assert old_doc.to_json() == doc.to_json()
self.assertDbEqual(
[
{"_id": 0, "value": 3},
@@ -93,7 +93,7 @@ class TestFindAndModify(unittest.TestCase):
Doc(id=1, value=1).save()
old_doc = Doc.objects(id=1).only("id").modify(set__value=-1)
self.assertEqual(old_doc.to_mongo(), {"_id": 1})
assert old_doc.to_mongo() == {"_id": 1}
self.assertDbEqual([{"_id": 0, "value": 0}, {"_id": 1, "value": -1}])
def test_modify_with_push(self):
@@ -106,23 +106,23 @@ class TestFindAndModify(unittest.TestCase):
# Push a new tag via modify with new=False (default).
BlogPost(id=blog.id).modify(push__tags="code")
self.assertEqual(blog.tags, [])
assert blog.tags == []
blog.reload()
self.assertEqual(blog.tags, ["code"])
assert blog.tags == ["code"]
# Push a new tag via modify with new=True.
blog = BlogPost.objects(id=blog.id).modify(push__tags="java", new=True)
self.assertEqual(blog.tags, ["code", "java"])
assert blog.tags == ["code", "java"]
# Push a new tag with a positional argument.
blog = BlogPost.objects(id=blog.id).modify(push__tags__0="python", new=True)
self.assertEqual(blog.tags, ["python", "code", "java"])
assert blog.tags == ["python", "code", "java"]
# Push multiple new tags with a positional argument.
blog = BlogPost.objects(id=blog.id).modify(
push__tags__1=["go", "rust"], new=True
)
self.assertEqual(blog.tags, ["python", "go", "rust", "code", "java"])
assert blog.tags == ["python", "go", "rust", "code", "java"]
if __name__ == "__main__":

View File

@@ -37,13 +37,13 @@ class TestQuerysetPickable(MongoDBTestCase):
loadedQs = self._get_loaded(qs)
self.assertEqual(qs.count(), loadedQs.count())
assert qs.count() == loadedQs.count()
# can update loadedQs
loadedQs.update(age=23)
# check
self.assertEqual(Person.objects.first().age, 23)
assert Person.objects.first().age == 23
def test_pickle_support_filtration(self):
Person.objects.create(name="Alice", age=22)
@@ -51,9 +51,9 @@ class TestQuerysetPickable(MongoDBTestCase):
Person.objects.create(name="Bob", age=23)
qs = Person.objects.filter(age__gte=22)
self.assertEqual(qs.count(), 2)
assert qs.count() == 2
loaded = self._get_loaded(qs)
self.assertEqual(loaded.count(), 2)
self.assertEqual(loaded.filter(name="Bob").first().age, 23)
assert loaded.count() == 2
assert loaded.filter(name="Bob").first().age == 23

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,7 @@ from bson.son import SON
from mongoengine import *
from mongoengine.queryset import Q, transform
import pytest
class TestTransform(unittest.TestCase):
@@ -13,23 +14,16 @@ class TestTransform(unittest.TestCase):
def test_transform_query(self):
"""Ensure that the _transform_query function operates correctly.
"""
self.assertEqual(
transform.query(name="test", age=30), {"name": "test", "age": 30}
)
self.assertEqual(transform.query(age__lt=30), {"age": {"$lt": 30}})
self.assertEqual(
transform.query(age__gt=20, age__lt=50), {"age": {"$gt": 20, "$lt": 50}}
)
self.assertEqual(
transform.query(age=20, age__gt=50),
{"$and": [{"age": {"$gt": 50}}, {"age": 20}]},
)
self.assertEqual(
transform.query(friend__age__gte=30), {"friend.age": {"$gte": 30}}
)
self.assertEqual(
transform.query(name__exists=True), {"name": {"$exists": True}}
)
assert transform.query(name="test", age=30) == {"name": "test", "age": 30}
assert transform.query(age__lt=30) == {"age": {"$lt": 30}}
assert transform.query(age__gt=20, age__lt=50) == {
"age": {"$gt": 20, "$lt": 50}
}
assert transform.query(age=20, age__gt=50) == {
"$and": [{"age": {"$gt": 50}}, {"age": 20}]
}
assert transform.query(friend__age__gte=30) == {"friend.age": {"$gte": 30}}
assert transform.query(name__exists=True) == {"name": {"$exists": True}}
def test_transform_update(self):
class LisDoc(Document):
@@ -54,17 +48,17 @@ class TestTransform(unittest.TestCase):
("push", "$push"),
):
update = transform.update(DicDoc, **{"%s__dictField__test" % k: doc})
self.assertIsInstance(update[v]["dictField.test"], dict)
assert isinstance(update[v]["dictField.test"], dict)
# Update special cases
update = transform.update(DicDoc, unset__dictField__test=doc)
self.assertEqual(update["$unset"]["dictField.test"], 1)
assert update["$unset"]["dictField.test"] == 1
update = transform.update(DicDoc, pull__dictField__test=doc)
self.assertIsInstance(update["$pull"]["dictField"]["test"], dict)
assert isinstance(update["$pull"]["dictField"]["test"], dict)
update = transform.update(LisDoc, pull__foo__in=["a"])
self.assertEqual(update, {"$pull": {"foo": {"$in": ["a"]}}})
assert update == {"$pull": {"foo": {"$in": ["a"]}}}
def test_transform_update_push(self):
"""Ensure the differences in behvaior between 'push' and 'push_all'"""
@@ -73,10 +67,10 @@ class TestTransform(unittest.TestCase):
tags = ListField(StringField())
update = transform.update(BlogPost, push__tags=["mongo", "db"])
self.assertEqual(update, {"$push": {"tags": ["mongo", "db"]}})
assert update == {"$push": {"tags": ["mongo", "db"]}}
update = transform.update(BlogPost, push_all__tags=["mongo", "db"])
self.assertEqual(update, {"$push": {"tags": {"$each": ["mongo", "db"]}}})
assert update == {"$push": {"tags": {"$each": ["mongo", "db"]}}}
def test_transform_update_no_operator_default_to_set(self):
"""Ensure the differences in behvaior between 'push' and 'push_all'"""
@@ -85,7 +79,7 @@ class TestTransform(unittest.TestCase):
tags = ListField(StringField())
update = transform.update(BlogPost, tags=["mongo", "db"])
self.assertEqual(update, {"$set": {"tags": ["mongo", "db"]}})
assert update == {"$set": {"tags": ["mongo", "db"]}}
def test_query_field_name(self):
"""Ensure that the correct field name is used when querying.
@@ -106,18 +100,18 @@ class TestTransform(unittest.TestCase):
post = BlogPost(**data)
post.save()
self.assertIn("postTitle", BlogPost.objects(title=data["title"])._query)
self.assertFalse("title" in BlogPost.objects(title=data["title"])._query)
self.assertEqual(BlogPost.objects(title=data["title"]).count(), 1)
assert "postTitle" in BlogPost.objects(title=data["title"])._query
assert not ("title" in BlogPost.objects(title=data["title"])._query)
assert BlogPost.objects(title=data["title"]).count() == 1
self.assertIn("_id", BlogPost.objects(pk=post.id)._query)
self.assertEqual(BlogPost.objects(pk=post.id).count(), 1)
assert "_id" in BlogPost.objects(pk=post.id)._query
assert BlogPost.objects(pk=post.id).count() == 1
self.assertIn(
"postComments.commentContent",
BlogPost.objects(comments__content="test")._query,
assert (
"postComments.commentContent"
in BlogPost.objects(comments__content="test")._query
)
self.assertEqual(BlogPost.objects(comments__content="test").count(), 1)
assert BlogPost.objects(comments__content="test").count() == 1
BlogPost.drop_collection()
@@ -135,9 +129,9 @@ class TestTransform(unittest.TestCase):
post = BlogPost(**data)
post.save()
self.assertIn("_id", BlogPost.objects(pk=data["title"])._query)
self.assertIn("_id", BlogPost.objects(title=data["title"])._query)
self.assertEqual(BlogPost.objects(pk=data["title"]).count(), 1)
assert "_id" in BlogPost.objects(pk=data["title"])._query
assert "_id" in BlogPost.objects(title=data["title"])._query
assert BlogPost.objects(pk=data["title"]).count() == 1
BlogPost.drop_collection()
@@ -163,7 +157,7 @@ class TestTransform(unittest.TestCase):
q2 = B.objects.filter(a__in=[a1, a2])
q2 = q2.filter(a=a1)._query
self.assertEqual(q1, q2)
assert q1 == q2
def test_raw_query_and_Q_objects(self):
"""
@@ -179,11 +173,11 @@ class TestTransform(unittest.TestCase):
meta = {"allow_inheritance": False}
query = Foo.objects(__raw__={"$nor": [{"name": "bar"}]})._query
self.assertEqual(query, {"$nor": [{"name": "bar"}]})
assert query == {"$nor": [{"name": "bar"}]}
q1 = {"$or": [{"a": 1}, {"b": 1}]}
query = Foo.objects(Q(__raw__=q1) & Q(c=1))._query
self.assertEqual(query, {"$or": [{"a": 1}, {"b": 1}], "c": 1})
assert query == {"$or": [{"a": 1}, {"b": 1}], "c": 1}
def test_raw_and_merging(self):
class Doc(Document):
@@ -200,51 +194,39 @@ class TestTransform(unittest.TestCase):
}
)._query
self.assertEqual(
raw_query,
{
"deleted": False,
"scraped": "yes",
"$nor": [
{"views.extracted": "no"},
{"attachments.views.extracted": "no"},
],
},
)
assert raw_query == {
"deleted": False,
"scraped": "yes",
"$nor": [{"views.extracted": "no"}, {"attachments.views.extracted": "no"}],
}
def test_geojson_PointField(self):
class Location(Document):
loc = PointField()
update = transform.update(Location, set__loc=[1, 2])
self.assertEqual(
update, {"$set": {"loc": {"type": "Point", "coordinates": [1, 2]}}}
)
assert update == {"$set": {"loc": {"type": "Point", "coordinates": [1, 2]}}}
update = transform.update(
Location, set__loc={"type": "Point", "coordinates": [1, 2]}
)
self.assertEqual(
update, {"$set": {"loc": {"type": "Point", "coordinates": [1, 2]}}}
)
assert update == {"$set": {"loc": {"type": "Point", "coordinates": [1, 2]}}}
def test_geojson_LineStringField(self):
class Location(Document):
line = LineStringField()
update = transform.update(Location, set__line=[[1, 2], [2, 2]])
self.assertEqual(
update,
{"$set": {"line": {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}}},
)
assert update == {
"$set": {"line": {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}}
}
update = transform.update(
Location, set__line={"type": "LineString", "coordinates": [[1, 2], [2, 2]]}
)
self.assertEqual(
update,
{"$set": {"line": {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}}},
)
assert update == {
"$set": {"line": {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}}
}
def test_geojson_PolygonField(self):
class Location(Document):
@@ -253,17 +235,14 @@ class TestTransform(unittest.TestCase):
update = transform.update(
Location, set__poly=[[[40, 5], [40, 6], [41, 6], [40, 5]]]
)
self.assertEqual(
update,
{
"$set": {
"poly": {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]],
}
assert update == {
"$set": {
"poly": {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]],
}
},
)
}
}
update = transform.update(
Location,
@@ -272,17 +251,14 @@ class TestTransform(unittest.TestCase):
"coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]],
},
)
self.assertEqual(
update,
{
"$set": {
"poly": {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]],
}
assert update == {
"$set": {
"poly": {
"type": "Polygon",
"coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]],
}
},
)
}
}
def test_type(self):
class Doc(Document):
@@ -291,10 +267,10 @@ class TestTransform(unittest.TestCase):
Doc(df=True).save()
Doc(df=7).save()
Doc(df="df").save()
self.assertEqual(Doc.objects(df__type=1).count(), 0) # double
self.assertEqual(Doc.objects(df__type=8).count(), 1) # bool
self.assertEqual(Doc.objects(df__type=2).count(), 1) # str
self.assertEqual(Doc.objects(df__type=16).count(), 1) # int
assert Doc.objects(df__type=1).count() == 0 # double
assert Doc.objects(df__type=8).count() == 1 # bool
assert Doc.objects(df__type=2).count() == 1 # str
assert Doc.objects(df__type=16).count() == 1 # int
def test_last_field_name_like_operator(self):
class EmbeddedItem(EmbeddedDocument):
@@ -309,12 +285,12 @@ class TestTransform(unittest.TestCase):
doc = Doc(item=EmbeddedItem(type="axe", name="Heroic axe"))
doc.save()
self.assertEqual(1, Doc.objects(item__type__="axe").count())
self.assertEqual(1, Doc.objects(item__name__="Heroic axe").count())
assert 1 == Doc.objects(item__type__="axe").count()
assert 1 == Doc.objects(item__name__="Heroic axe").count()
Doc.objects(id=doc.id).update(set__item__type__="sword")
self.assertEqual(1, Doc.objects(item__type__="sword").count())
self.assertEqual(0, Doc.objects(item__type__="axe").count())
assert 1 == Doc.objects(item__type__="sword").count()
assert 0 == Doc.objects(item__type__="axe").count()
def test_understandable_error_raised(self):
class Event(Document):
@@ -324,7 +300,7 @@ class TestTransform(unittest.TestCase):
box = [(35.0, -125.0), (40.0, -100.0)]
# I *meant* to execute location__within_box=box
events = Event.objects(location__within=box)
with self.assertRaises(InvalidQueryError):
with pytest.raises(InvalidQueryError):
events.count()
def test_update_pull_for_list_fields(self):
@@ -347,24 +323,20 @@ class TestTransform(unittest.TestCase):
word = Word(word="abc", index=1)
update = transform.update(MainDoc, pull__content__text=word)
self.assertEqual(
update, {"$pull": {"content.text": SON([("word", u"abc"), ("index", 1)])}}
)
assert update == {
"$pull": {"content.text": SON([("word", u"abc"), ("index", 1)])}
}
update = transform.update(MainDoc, pull__content__heading="xyz")
self.assertEqual(update, {"$pull": {"content.heading": "xyz"}})
assert update == {"$pull": {"content.heading": "xyz"}}
update = transform.update(MainDoc, pull__content__text__word__in=["foo", "bar"])
self.assertEqual(
update, {"$pull": {"content.text": {"word": {"$in": ["foo", "bar"]}}}}
)
assert update == {"$pull": {"content.text": {"word": {"$in": ["foo", "bar"]}}}}
update = transform.update(
MainDoc, pull__content__text__word__nin=["foo", "bar"]
)
self.assertEqual(
update, {"$pull": {"content.text": {"word": {"$nin": ["foo", "bar"]}}}}
)
assert update == {"$pull": {"content.text": {"word": {"$nin": ["foo", "bar"]}}}}
if __name__ == "__main__":

View File

@@ -7,6 +7,7 @@ from bson import ObjectId
from mongoengine import *
from mongoengine.errors import InvalidQueryError
from mongoengine.queryset import Q
import pytest
class TestQ(unittest.TestCase):
@@ -35,10 +36,10 @@ class TestQ(unittest.TestCase):
age = IntField()
query = {"$or": [{"age": {"$gte": 18}}, {"name": "test"}]}
self.assertEqual((q1 | q2 | q3 | q4 | q5).to_query(Person), query)
assert (q1 | q2 | q3 | q4 | q5).to_query(Person) == query
query = {"age": {"$gte": 18}, "name": "test"}
self.assertEqual((q1 & q2 & q3 & q4 & q5).to_query(Person), query)
assert (q1 & q2 & q3 & q4 & q5).to_query(Person) == query
def test_q_with_dbref(self):
"""Ensure Q objects handle DBRefs correctly"""
@@ -53,8 +54,8 @@ class TestQ(unittest.TestCase):
user = User.objects.create()
Post.objects.create(created_user=user)
self.assertEqual(Post.objects.filter(created_user=user).count(), 1)
self.assertEqual(Post.objects.filter(Q(created_user=user)).count(), 1)
assert Post.objects.filter(created_user=user).count() == 1
assert Post.objects.filter(Q(created_user=user)).count() == 1
def test_and_combination(self):
"""Ensure that Q-objects correctly AND together.
@@ -65,12 +66,10 @@ class TestQ(unittest.TestCase):
y = StringField()
query = (Q(x__lt=7) & Q(x__lt=3)).to_query(TestDoc)
self.assertEqual(query, {"$and": [{"x": {"$lt": 7}}, {"x": {"$lt": 3}}]})
assert query == {"$and": [{"x": {"$lt": 7}}, {"x": {"$lt": 3}}]}
query = (Q(y="a") & Q(x__lt=7) & Q(x__lt=3)).to_query(TestDoc)
self.assertEqual(
query, {"$and": [{"y": "a"}, {"x": {"$lt": 7}}, {"x": {"$lt": 3}}]}
)
assert query == {"$and": [{"y": "a"}, {"x": {"$lt": 7}}, {"x": {"$lt": 3}}]}
# Check normal cases work without an error
query = Q(x__lt=7) & Q(x__gt=3)
@@ -78,7 +77,7 @@ class TestQ(unittest.TestCase):
q1 = Q(x__lt=7)
q2 = Q(x__gt=3)
query = (q1 & q2).to_query(TestDoc)
self.assertEqual(query, {"x": {"$lt": 7, "$gt": 3}})
assert query == {"x": {"$lt": 7, "$gt": 3}}
# More complex nested example
query = Q(x__lt=100) & Q(y__ne="NotMyString")
@@ -87,7 +86,7 @@ class TestQ(unittest.TestCase):
"x": {"$lt": 100, "$gt": -100},
"y": {"$ne": "NotMyString", "$in": ["a", "b", "c"]},
}
self.assertEqual(query.to_query(TestDoc), mongo_query)
assert query.to_query(TestDoc) == mongo_query
def test_or_combination(self):
"""Ensure that Q-objects correctly OR together.
@@ -99,7 +98,7 @@ class TestQ(unittest.TestCase):
q1 = Q(x__lt=3)
q2 = Q(x__gt=7)
query = (q1 | q2).to_query(TestDoc)
self.assertEqual(query, {"$or": [{"x": {"$lt": 3}}, {"x": {"$gt": 7}}]})
assert query == {"$or": [{"x": {"$lt": 3}}, {"x": {"$gt": 7}}]}
def test_and_or_combination(self):
"""Ensure that Q-objects handle ANDing ORed components.
@@ -113,15 +112,12 @@ class TestQ(unittest.TestCase):
query = Q(x__gt=0) | Q(x__exists=False)
query &= Q(x__lt=100)
self.assertEqual(
query.to_query(TestDoc),
{
"$and": [
{"$or": [{"x": {"$gt": 0}}, {"x": {"$exists": False}}]},
{"x": {"$lt": 100}},
]
},
)
assert query.to_query(TestDoc) == {
"$and": [
{"$or": [{"x": {"$gt": 0}}, {"x": {"$exists": False}}]},
{"x": {"$lt": 100}},
]
}
q1 = Q(x__gt=0) | Q(x__exists=False)
q2 = Q(x__lt=100) | Q(y=True)
@@ -131,16 +127,13 @@ class TestQ(unittest.TestCase):
TestDoc(x=10).save()
TestDoc(y=True).save()
self.assertEqual(
query,
{
"$and": [
{"$or": [{"x": {"$gt": 0}}, {"x": {"$exists": False}}]},
{"$or": [{"x": {"$lt": 100}}, {"y": True}]},
]
},
)
self.assertEqual(2, TestDoc.objects(q1 & q2).count())
assert query == {
"$and": [
{"$or": [{"x": {"$gt": 0}}, {"x": {"$exists": False}}]},
{"$or": [{"x": {"$lt": 100}}, {"y": True}]},
]
}
assert 2 == TestDoc.objects(q1 & q2).count()
def test_or_and_or_combination(self):
"""Ensure that Q-objects handle ORing ANDed ORed components. :)
@@ -160,26 +153,23 @@ class TestQ(unittest.TestCase):
q2 = Q(x__lt=100) & (Q(y=False) | Q(y__exists=False))
query = (q1 | q2).to_query(TestDoc)
self.assertEqual(
query,
{
"$or": [
{
"$and": [
{"x": {"$gt": 0}},
{"$or": [{"y": True}, {"y": {"$exists": False}}]},
]
},
{
"$and": [
{"x": {"$lt": 100}},
{"$or": [{"y": False}, {"y": {"$exists": False}}]},
]
},
]
},
)
self.assertEqual(2, TestDoc.objects(q1 | q2).count())
assert query == {
"$or": [
{
"$and": [
{"x": {"$gt": 0}},
{"$or": [{"y": True}, {"y": {"$exists": False}}]},
]
},
{
"$and": [
{"x": {"$lt": 100}},
{"$or": [{"y": False}, {"y": {"$exists": False}}]},
]
},
]
}
assert 2 == TestDoc.objects(q1 | q2).count()
def test_multiple_occurence_in_field(self):
class Test(Document):
@@ -192,8 +182,8 @@ class TestQ(unittest.TestCase):
q3 = q1 & q2
query = q3.to_query(Test)
self.assertEqual(query["$and"][0], q1.to_query(Test))
self.assertEqual(query["$and"][1], q2.to_query(Test))
assert query["$and"][0] == q1.to_query(Test)
assert query["$and"][1] == q2.to_query(Test)
def test_q_clone(self):
class TestDoc(Document):
@@ -207,15 +197,15 @@ class TestQ(unittest.TestCase):
# Check normal cases work without an error
test = TestDoc.objects(Q(x__lt=7) & Q(x__gt=3))
self.assertEqual(test.count(), 3)
assert test.count() == 3
test2 = test.clone()
self.assertEqual(test2.count(), 3)
self.assertNotEqual(test2, test)
assert test2.count() == 3
assert test2 != test
test3 = test2.filter(x=6)
self.assertEqual(test3.count(), 1)
self.assertEqual(test.count(), 3)
assert test3.count() == 1
assert test.count() == 3
def test_q(self):
"""Ensure that Q objects may be used to query for documents.
@@ -252,19 +242,19 @@ class TestQ(unittest.TestCase):
# Check ObjectId lookup works
obj = BlogPost.objects(id=post1.id).first()
self.assertEqual(obj, post1)
assert obj == post1
# Check Q object combination with one does not exist
q = BlogPost.objects(Q(title="Test 5") | Q(published=True))
posts = [post.id for post in q]
published_posts = (post2, post3)
self.assertTrue(all(obj.id in posts for obj in published_posts))
assert all(obj.id in posts for obj in published_posts)
q = BlogPost.objects(Q(title="Test 1") | Q(published=True))
posts = [post.id for post in q]
published_posts = (post1, post2, post3, post5, post6)
self.assertTrue(all(obj.id in posts for obj in published_posts))
assert all(obj.id in posts for obj in published_posts)
# Check Q object combination
date = datetime.datetime(2010, 1, 10)
@@ -272,9 +262,9 @@ class TestQ(unittest.TestCase):
posts = [post.id for post in q]
published_posts = (post1, post2, post3, post4)
self.assertTrue(all(obj.id in posts for obj in published_posts))
assert all(obj.id in posts for obj in published_posts)
self.assertFalse(any(obj.id in posts for obj in [post5, post6]))
assert not any(obj.id in posts for obj in [post5, post6])
BlogPost.drop_collection()
@@ -284,15 +274,15 @@ class TestQ(unittest.TestCase):
self.Person(name="user3", age=30).save()
self.Person(name="user4", age=40).save()
self.assertEqual(self.Person.objects(Q(age__in=[20])).count(), 2)
self.assertEqual(self.Person.objects(Q(age__in=[20, 30])).count(), 3)
assert self.Person.objects(Q(age__in=[20])).count() == 2
assert self.Person.objects(Q(age__in=[20, 30])).count() == 3
# Test invalid query objs
with self.assertRaises(InvalidQueryError):
with pytest.raises(InvalidQueryError):
self.Person.objects("user1")
# filter should fail, too
with self.assertRaises(InvalidQueryError):
with pytest.raises(InvalidQueryError):
self.Person.objects.filter("user1")
def test_q_regex(self):
@@ -302,31 +292,31 @@ class TestQ(unittest.TestCase):
person.save()
obj = self.Person.objects(Q(name=re.compile("^Gui"))).first()
self.assertEqual(obj, person)
assert obj == person
obj = self.Person.objects(Q(name=re.compile("^gui"))).first()
self.assertEqual(obj, None)
assert obj == None
obj = self.Person.objects(Q(name=re.compile("^gui", re.I))).first()
self.assertEqual(obj, person)
assert obj == person
obj = self.Person.objects(Q(name__not=re.compile("^bob"))).first()
self.assertEqual(obj, person)
assert obj == person
obj = self.Person.objects(Q(name__not=re.compile("^Gui"))).first()
self.assertEqual(obj, None)
assert obj == None
def test_q_repr(self):
self.assertEqual(repr(Q()), "Q(**{})")
self.assertEqual(repr(Q(name="test")), "Q(**{'name': 'test'})")
assert repr(Q()) == "Q(**{})"
assert repr(Q(name="test")) == "Q(**{'name': 'test'})"
self.assertEqual(
repr(Q(name="test") & Q(age__gte=18)),
"(Q(**{'name': 'test'}) & Q(**{'age__gte': 18}))",
assert (
repr(Q(name="test") & Q(age__gte=18))
== "(Q(**{'name': 'test'}) & Q(**{'age__gte': 18}))"
)
self.assertEqual(
repr(Q(name="test") | Q(age__gte=18)),
"(Q(**{'name': 'test'}) | Q(**{'age__gte': 18}))",
assert (
repr(Q(name="test") | Q(age__gte=18))
== "(Q(**{'name': 'test'}) | Q(**{'age__gte': 18}))"
)
def test_q_lists(self):
@@ -341,8 +331,8 @@ class TestQ(unittest.TestCase):
BlogPost(tags=["python", "mongo"]).save()
BlogPost(tags=["python"]).save()
self.assertEqual(BlogPost.objects(Q(tags="mongo")).count(), 1)
self.assertEqual(BlogPost.objects(Q(tags="python")).count(), 2)
assert BlogPost.objects(Q(tags="mongo")).count() == 1
assert BlogPost.objects(Q(tags="python")).count() == 2
BlogPost.drop_collection()
@@ -355,12 +345,12 @@ class TestQ(unittest.TestCase):
pk = ObjectId()
User(email="example@example.com", pk=pk).save()
self.assertEqual(
1,
User.objects.filter(Q(email="example@example.com") | Q(name="John Doe"))
assert (
1
== User.objects.filter(Q(email="example@example.com") | Q(name="John Doe"))
.limit(2)
.filter(pk=pk)
.count(),
.count()
)
def test_chained_q_or_filtering(self):
@@ -376,14 +366,12 @@ class TestQ(unittest.TestCase):
Item(postables=[Post(name="a"), Post(name="c")]).save()
Item(postables=[Post(name="a"), Post(name="b"), Post(name="c")]).save()
self.assertEqual(
Item.objects(Q(postables__name="a") & Q(postables__name="b")).count(), 2
assert (
Item.objects(Q(postables__name="a") & Q(postables__name="b")).count() == 2
)
self.assertEqual(
Item.objects.filter(postables__name="a")
.filter(postables__name="b")
.count(),
2,
assert (
Item.objects.filter(postables__name="a").filter(postables__name="b").count()
== 2
)