ran unittest2pytest
This commit is contained in:
@@ -7,6 +7,7 @@ import six
|
||||
|
||||
from mongoengine import *
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
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"
|
||||
@@ -31,8 +32,8 @@ class TestBinaryField(MongoDBTestCase):
|
||||
attachment.save()
|
||||
|
||||
attachment_1 = Attachment.objects().first()
|
||||
self.assertEqual(MIME_TYPE, attachment_1.content_type)
|
||||
self.assertEqual(BLOB, six.binary_type(attachment_1.blob))
|
||||
assert MIME_TYPE == attachment_1.content_type
|
||||
assert BLOB == six.binary_type(attachment_1.blob)
|
||||
|
||||
def test_validation_succeeds(self):
|
||||
"""Ensure that valid values can be assigned to binary fields.
|
||||
@@ -45,13 +46,15 @@ class TestBinaryField(MongoDBTestCase):
|
||||
blob = BinaryField(max_bytes=4)
|
||||
|
||||
attachment_required = AttachmentRequired()
|
||||
self.assertRaises(ValidationError, attachment_required.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
attachment_required.validate()
|
||||
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")
|
||||
self.assertRaises(ValidationError, AttachmentSizeLimit(blob=_5_BYTES).validate)
|
||||
with pytest.raises(ValidationError):
|
||||
AttachmentSizeLimit(blob=_5_BYTES).validate()
|
||||
AttachmentSizeLimit(blob=_4_BYTES).validate()
|
||||
|
||||
def test_validation_fails(self):
|
||||
@@ -61,7 +64,8 @@ class TestBinaryField(MongoDBTestCase):
|
||||
blob = BinaryField()
|
||||
|
||||
for invalid_data in (2, u"Im_a_unicode", ["some_str"]):
|
||||
self.assertRaises(ValidationError, Attachment(blob=invalid_data).validate)
|
||||
with pytest.raises(ValidationError):
|
||||
Attachment(blob=invalid_data).validate()
|
||||
|
||||
def test__primary(self):
|
||||
class Attachment(Document):
|
||||
@@ -70,10 +74,10 @@ class TestBinaryField(MongoDBTestCase):
|
||||
Attachment.drop_collection()
|
||||
binary_id = uuid.uuid4().bytes
|
||||
att = Attachment(id=binary_id).save()
|
||||
self.assertEqual(1, Attachment.objects.count())
|
||||
self.assertEqual(1, Attachment.objects.filter(id=att.id).count())
|
||||
assert 1 == Attachment.objects.count()
|
||||
assert 1 == Attachment.objects.filter(id=att.id).count()
|
||||
att.delete()
|
||||
self.assertEqual(0, Attachment.objects.count())
|
||||
assert 0 == Attachment.objects.count()
|
||||
|
||||
def test_primary_filter_by_binary_pk_as_str(self):
|
||||
class Attachment(Document):
|
||||
@@ -82,9 +86,9 @@ class TestBinaryField(MongoDBTestCase):
|
||||
Attachment.drop_collection()
|
||||
binary_id = uuid.uuid4().bytes
|
||||
att = Attachment(id=binary_id).save()
|
||||
self.assertEqual(1, Attachment.objects.filter(id=binary_id).count())
|
||||
assert 1 == Attachment.objects.filter(id=binary_id).count()
|
||||
att.delete()
|
||||
self.assertEqual(0, Attachment.objects.count())
|
||||
assert 0 == Attachment.objects.count()
|
||||
|
||||
def test_match_querying_with_bytes(self):
|
||||
class MyDocument(Document):
|
||||
@@ -94,7 +98,7 @@ class TestBinaryField(MongoDBTestCase):
|
||||
|
||||
doc = MyDocument(bin_field=BIN_VALUE).save()
|
||||
matched_doc = MyDocument.objects(bin_field=BIN_VALUE).first()
|
||||
self.assertEqual(matched_doc.id, doc.id)
|
||||
assert matched_doc.id == doc.id
|
||||
|
||||
def test_match_querying_with_binary(self):
|
||||
class MyDocument(Document):
|
||||
@@ -105,7 +109,7 @@ class TestBinaryField(MongoDBTestCase):
|
||||
doc = MyDocument(bin_field=BIN_VALUE).save()
|
||||
|
||||
matched_doc = MyDocument.objects(bin_field=Binary(BIN_VALUE)).first()
|
||||
self.assertEqual(matched_doc.id, doc.id)
|
||||
assert matched_doc.id == doc.id
|
||||
|
||||
def test_modify_operation__set(self):
|
||||
"""Ensures no regression of bug #1127"""
|
||||
@@ -119,11 +123,11 @@ class TestBinaryField(MongoDBTestCase):
|
||||
doc = MyDocument.objects(some_field="test").modify(
|
||||
upsert=True, new=True, set__bin_field=BIN_VALUE
|
||||
)
|
||||
self.assertEqual(doc.some_field, "test")
|
||||
assert doc.some_field == "test"
|
||||
if six.PY3:
|
||||
self.assertEqual(doc.bin_field, BIN_VALUE)
|
||||
assert doc.bin_field == BIN_VALUE
|
||||
else:
|
||||
self.assertEqual(doc.bin_field, Binary(BIN_VALUE))
|
||||
assert doc.bin_field == Binary(BIN_VALUE)
|
||||
|
||||
def test_update_one(self):
|
||||
"""Ensures no regression of bug #1127"""
|
||||
@@ -139,9 +143,9 @@ class TestBinaryField(MongoDBTestCase):
|
||||
n_updated = MyDocument.objects(bin_field=bin_data).update_one(
|
||||
bin_field=BIN_VALUE
|
||||
)
|
||||
self.assertEqual(n_updated, 1)
|
||||
assert n_updated == 1
|
||||
fetched = MyDocument.objects.with_id(doc.id)
|
||||
if six.PY3:
|
||||
self.assertEqual(fetched.bin_field, BIN_VALUE)
|
||||
assert fetched.bin_field == BIN_VALUE
|
||||
else:
|
||||
self.assertEqual(fetched.bin_field, Binary(BIN_VALUE))
|
||||
assert fetched.bin_field == Binary(BIN_VALUE)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase, get_as_pymongo
|
||||
import pytest
|
||||
|
||||
|
||||
class TestBooleanField(MongoDBTestCase):
|
||||
@@ -11,7 +12,7 @@ class TestBooleanField(MongoDBTestCase):
|
||||
|
||||
person = Person(admin=True)
|
||||
person.save()
|
||||
self.assertEqual(get_as_pymongo(person), {"_id": person.id, "admin": True})
|
||||
assert get_as_pymongo(person) == {"_id": person.id, "admin": True}
|
||||
|
||||
def test_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to boolean
|
||||
@@ -26,11 +27,14 @@ class TestBooleanField(MongoDBTestCase):
|
||||
person.validate()
|
||||
|
||||
person.admin = 2
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.admin = "Yes"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.admin = "False"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
def test_weirdness_constructor(self):
|
||||
"""When attribute is set in contructor, it gets cast into a bool
|
||||
@@ -42,7 +46,7 @@ class TestBooleanField(MongoDBTestCase):
|
||||
admin = BooleanField()
|
||||
|
||||
new_person = Person(admin="False")
|
||||
self.assertTrue(new_person.admin)
|
||||
assert new_person.admin
|
||||
|
||||
new_person = Person(admin="0")
|
||||
self.assertTrue(new_person.admin)
|
||||
assert new_person.admin
|
||||
|
||||
@@ -4,6 +4,7 @@ from decimal import Decimal
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestCachedReferenceField(MongoDBTestCase):
|
||||
@@ -46,29 +47,29 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
a = Animal(name="Leopard", tag="heavy")
|
||||
a.save()
|
||||
|
||||
self.assertEqual(Animal._cached_reference_fields, [Ocorrence.animal])
|
||||
assert Animal._cached_reference_fields == [Ocorrence.animal]
|
||||
o = Ocorrence(person="teste", animal=a)
|
||||
o.save()
|
||||
|
||||
p = Ocorrence(person="Wilson")
|
||||
p.save()
|
||||
|
||||
self.assertEqual(Ocorrence.objects(animal=None).count(), 1)
|
||||
assert Ocorrence.objects(animal=None).count() == 1
|
||||
|
||||
self.assertEqual(a.to_mongo(fields=["tag"]), {"tag": "heavy", "_id": a.pk})
|
||||
assert a.to_mongo(fields=["tag"]) == {"tag": "heavy", "_id": a.pk}
|
||||
|
||||
self.assertEqual(o.to_mongo()["animal"]["tag"], "heavy")
|
||||
assert o.to_mongo()["animal"]["tag"] == "heavy"
|
||||
|
||||
# counts
|
||||
Ocorrence(person="teste 2").save()
|
||||
Ocorrence(person="teste 3").save()
|
||||
|
||||
count = Ocorrence.objects(animal__tag="heavy").count()
|
||||
self.assertEqual(count, 1)
|
||||
assert count == 1
|
||||
|
||||
ocorrence = Ocorrence.objects(animal__tag="heavy").first()
|
||||
self.assertEqual(ocorrence.person, "teste")
|
||||
self.assertIsInstance(ocorrence.animal, Animal)
|
||||
assert ocorrence.person == "teste"
|
||||
assert isinstance(ocorrence.animal, Animal)
|
||||
|
||||
def test_with_decimal(self):
|
||||
class PersonAuto(Document):
|
||||
@@ -88,10 +89,11 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
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}},
|
||||
)
|
||||
assert 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):
|
||||
@@ -131,18 +133,15 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
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},
|
||||
},
|
||||
)
|
||||
assert 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)
|
||||
assert SocialData.objects(person__group=g2).count() == 1
|
||||
assert SocialData.objects(person__group=g2).first() == s2
|
||||
|
||||
def test_cached_reference_field_push_with_fields(self):
|
||||
class Product(Document):
|
||||
@@ -157,26 +156,20 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
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}],
|
||||
},
|
||||
)
|
||||
assert Basket.objects._collection.find_one() == {
|
||||
"_id": basket.pk,
|
||||
"products": [{"_id": product1.pk, "name": product1.name}],
|
||||
}
|
||||
# push to list
|
||||
basket.update(push__products=product2)
|
||||
basket.reload()
|
||||
self.assertEqual(
|
||||
Basket.objects._collection.find_one(),
|
||||
{
|
||||
"_id": basket.pk,
|
||||
"products": [
|
||||
{"_id": product1.pk, "name": product1.name},
|
||||
{"_id": product2.pk, "name": product2.name},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert Basket.objects._collection.find_one() == {
|
||||
"_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):
|
||||
@@ -194,37 +187,31 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
a2.save()
|
||||
|
||||
a2 = Person.objects.with_id(a2.id)
|
||||
self.assertEqual(a2.father.tp, a1.tp)
|
||||
assert 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"},
|
||||
},
|
||||
)
|
||||
assert 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).count(), 1)
|
||||
assert Person.objects(father=a1)._query == {"father._id": a1.pk}
|
||||
assert 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"},
|
||||
},
|
||||
)
|
||||
assert 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):
|
||||
with pytest.raises(InvalidDocumentError):
|
||||
|
||||
class Test(Document):
|
||||
name = StringField()
|
||||
@@ -255,15 +242,12 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
a1.save()
|
||||
|
||||
a2.reload()
|
||||
self.assertEqual(
|
||||
dict(a2.to_mongo()),
|
||||
{
|
||||
"_id": a2.pk,
|
||||
"name": "Wilson Junior",
|
||||
"tp": "pf",
|
||||
"father": {"_id": a1.pk, "tp": "pf"},
|
||||
},
|
||||
)
|
||||
assert 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):
|
||||
@@ -284,15 +268,12 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
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"},
|
||||
},
|
||||
)
|
||||
assert 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):
|
||||
@@ -320,28 +301,29 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
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")
|
||||
assert dict(a.to_mongo(fields=["tag", "owner.tp"])) == {
|
||||
"_id": a.pk,
|
||||
"tag": "heavy",
|
||||
"owner": {"t": "u"},
|
||||
}
|
||||
assert o.to_mongo()["animal"]["tag"] == "heavy"
|
||||
assert o.to_mongo()["animal"]["owner"]["t"] == "u"
|
||||
|
||||
# Check to_mongo with fields
|
||||
self.assertNotIn("animal", o.to_mongo(fields=["person"]))
|
||||
assert "animal" not in 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()
|
||||
self.assertEqual(count, 1)
|
||||
assert count == 1
|
||||
|
||||
ocorrence = Ocorrence.objects(
|
||||
animal__tag="heavy", animal__owner__tp="u"
|
||||
).first()
|
||||
self.assertEqual(ocorrence.person, "teste")
|
||||
self.assertIsInstance(ocorrence.animal, Animal)
|
||||
assert ocorrence.person == "teste"
|
||||
assert isinstance(ocorrence.animal, Animal)
|
||||
|
||||
def test_cached_reference_embedded_list_fields(self):
|
||||
class Owner(EmbeddedDocument):
|
||||
@@ -370,13 +352,14 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
|
||||
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"]}},
|
||||
)
|
||||
assert 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"])
|
||||
assert o.to_mongo()["animal"]["tag"] == "heavy"
|
||||
assert o.to_mongo()["animal"]["owner"]["tags"] == ["cool", "funny"]
|
||||
|
||||
# counts
|
||||
Ocorrence(person="teste 2").save()
|
||||
@@ -385,10 +368,10 @@ class TestCachedReferenceField(MongoDBTestCase):
|
||||
query = Ocorrence.objects(
|
||||
animal__tag="heavy", animal__owner__tags="cool"
|
||||
)._query
|
||||
self.assertEqual(query, {"animal.owner.tags": "cool", "animal.tag": "heavy"})
|
||||
assert query == {"animal.owner.tags": "cool", "animal.tag": "heavy"}
|
||||
|
||||
ocorrence = Ocorrence.objects(
|
||||
animal__tag="heavy", animal__owner__tags="cool"
|
||||
).first()
|
||||
self.assertEqual(ocorrence.person, "teste 2")
|
||||
self.assertIsInstance(ocorrence.animal, Animal)
|
||||
assert ocorrence.person == "teste 2"
|
||||
assert isinstance(ocorrence.animal, Animal)
|
||||
|
||||
@@ -28,7 +28,7 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1)
|
||||
assert log.date == d1
|
||||
|
||||
# Post UTC - microseconds are rounded (down) nearest millisecond - with
|
||||
# default datetimefields
|
||||
@@ -36,7 +36,7 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1)
|
||||
assert log.date == d1
|
||||
|
||||
# Pre UTC dates microseconds below 1000 are dropped - with default
|
||||
# datetimefields
|
||||
@@ -44,7 +44,7 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1)
|
||||
assert log.date == d1
|
||||
|
||||
# Pre UTC microseconds above 1000 is wonky - with default datetimefields
|
||||
# log.date has an invalid microsecond value so I can't construct
|
||||
@@ -54,9 +54,9 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1)
|
||||
assert log.date == d1
|
||||
log1 = LogEntry.objects.get(date=d1)
|
||||
self.assertEqual(log, log1)
|
||||
assert log == log1
|
||||
|
||||
# Test string padding
|
||||
microsecond = map(int, [math.pow(10, x) for x in range(6)])
|
||||
@@ -64,7 +64,7 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
|
||||
for values in itertools.product([2014], mm, dd, hh, ii, ss, microsecond):
|
||||
stored = LogEntry(date=datetime.datetime(*values)).to_mongo()["date"]
|
||||
self.assertTrue(
|
||||
assert (
|
||||
re.match("^\d{4},\d{2},\d{2},\d{2},\d{2},\d{2},\d{6}$", stored)
|
||||
is not None
|
||||
)
|
||||
@@ -73,7 +73,7 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
stored = LogEntry(date_with_dots=datetime.datetime(2014, 1, 1)).to_mongo()[
|
||||
"date_with_dots"
|
||||
]
|
||||
self.assertTrue(
|
||||
assert (
|
||||
re.match("^\d{4}.\d{2}.\d{2}.\d{2}.\d{2}.\d{2}.\d{6}$", stored) is not None
|
||||
)
|
||||
|
||||
@@ -93,40 +93,40 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
log.save()
|
||||
|
||||
log1 = LogEntry.objects.get(date=d1)
|
||||
self.assertEqual(log, log1)
|
||||
assert log == log1
|
||||
|
||||
# create extra 59 log entries for a total of 60
|
||||
for i in range(1951, 2010):
|
||||
d = datetime.datetime(i, 1, 1, 0, 0, 1, 999)
|
||||
LogEntry(date=d).save()
|
||||
|
||||
self.assertEqual(LogEntry.objects.count(), 60)
|
||||
assert LogEntry.objects.count() == 60
|
||||
|
||||
# Test ordering
|
||||
logs = LogEntry.objects.order_by("date")
|
||||
i = 0
|
||||
while i < 59:
|
||||
self.assertTrue(logs[i].date <= logs[i + 1].date)
|
||||
assert logs[i].date <= logs[i + 1].date
|
||||
i += 1
|
||||
|
||||
logs = LogEntry.objects.order_by("-date")
|
||||
i = 0
|
||||
while i < 59:
|
||||
self.assertTrue(logs[i].date >= logs[i + 1].date)
|
||||
assert logs[i].date >= logs[i + 1].date
|
||||
i += 1
|
||||
|
||||
# Test searching
|
||||
logs = LogEntry.objects.filter(date__gte=datetime.datetime(1980, 1, 1))
|
||||
self.assertEqual(logs.count(), 30)
|
||||
assert logs.count() == 30
|
||||
|
||||
logs = LogEntry.objects.filter(date__lte=datetime.datetime(1980, 1, 1))
|
||||
self.assertEqual(logs.count(), 30)
|
||||
assert logs.count() == 30
|
||||
|
||||
logs = LogEntry.objects.filter(
|
||||
date__lte=datetime.datetime(2011, 1, 1),
|
||||
date__gte=datetime.datetime(2000, 1, 1),
|
||||
)
|
||||
self.assertEqual(logs.count(), 10)
|
||||
assert logs.count() == 10
|
||||
|
||||
LogEntry.drop_collection()
|
||||
|
||||
@@ -137,17 +137,17 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
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)
|
||||
assert log.date < next_log.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)
|
||||
assert log.date > next_log.date
|
||||
|
||||
logs = LogEntry.objects.filter(
|
||||
date__lte=datetime.datetime(2015, 1, 1, 0, 0, 0, 10000)
|
||||
)
|
||||
self.assertEqual(logs.count(), 4)
|
||||
assert logs.count() == 4
|
||||
|
||||
def test_no_default_value(self):
|
||||
class Log(Document):
|
||||
@@ -156,11 +156,11 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
Log.drop_collection()
|
||||
|
||||
log = Log()
|
||||
self.assertIsNone(log.timestamp)
|
||||
assert log.timestamp is None
|
||||
log.save()
|
||||
|
||||
fetched_log = Log.objects.with_id(log.id)
|
||||
self.assertIsNone(fetched_log.timestamp)
|
||||
assert fetched_log.timestamp is None
|
||||
|
||||
def test_default_static_value(self):
|
||||
NOW = datetime.datetime.utcnow()
|
||||
@@ -171,11 +171,11 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
Log.drop_collection()
|
||||
|
||||
log = Log()
|
||||
self.assertEqual(log.timestamp, NOW)
|
||||
assert log.timestamp == NOW
|
||||
log.save()
|
||||
|
||||
fetched_log = Log.objects.with_id(log.id)
|
||||
self.assertEqual(fetched_log.timestamp, NOW)
|
||||
assert fetched_log.timestamp == NOW
|
||||
|
||||
def test_default_callable(self):
|
||||
NOW = datetime.datetime.utcnow()
|
||||
@@ -186,8 +186,8 @@ class ComplexDateTimeFieldTest(MongoDBTestCase):
|
||||
Log.drop_collection()
|
||||
|
||||
log = Log()
|
||||
self.assertGreaterEqual(log.timestamp, NOW)
|
||||
assert log.timestamp >= NOW
|
||||
log.save()
|
||||
|
||||
fetched_log = Log.objects.with_id(log.id)
|
||||
self.assertGreaterEqual(fetched_log.timestamp, NOW)
|
||||
assert fetched_log.timestamp >= NOW
|
||||
|
||||
@@ -10,6 +10,7 @@ except ImportError:
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestDateField(MongoDBTestCase):
|
||||
@@ -23,7 +24,8 @@ class TestDateField(MongoDBTestCase):
|
||||
dt = DateField()
|
||||
|
||||
md = MyDoc(dt="")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
with pytest.raises(ValidationError):
|
||||
md.save()
|
||||
|
||||
def test_date_from_whitespace_string(self):
|
||||
"""
|
||||
@@ -35,7 +37,8 @@ class TestDateField(MongoDBTestCase):
|
||||
dt = DateField()
|
||||
|
||||
md = MyDoc(dt=" ")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
with pytest.raises(ValidationError):
|
||||
md.save()
|
||||
|
||||
def test_default_values_today(self):
|
||||
"""Ensure that default field values are used when creating
|
||||
@@ -47,9 +50,9 @@ class TestDateField(MongoDBTestCase):
|
||||
|
||||
person = Person()
|
||||
person.validate()
|
||||
self.assertEqual(person.day, person.day)
|
||||
self.assertEqual(person.day, datetime.date.today())
|
||||
self.assertEqual(person._data["day"], person.day)
|
||||
assert person.day == person.day
|
||||
assert person.day == datetime.date.today()
|
||||
assert person._data["day"] == person.day
|
||||
|
||||
def test_date(self):
|
||||
"""Tests showing pymongo date fields
|
||||
@@ -67,7 +70,7 @@ class TestDateField(MongoDBTestCase):
|
||||
log.date = datetime.date.today()
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, datetime.date.today())
|
||||
assert log.date == datetime.date.today()
|
||||
|
||||
d1 = datetime.datetime(1970, 1, 1, 0, 0, 1, 999)
|
||||
d2 = datetime.datetime(1970, 1, 1, 0, 0, 1)
|
||||
@@ -75,16 +78,16 @@ class TestDateField(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1.date())
|
||||
self.assertEqual(log.date, d2.date())
|
||||
assert log.date == d1.date()
|
||||
assert log.date == d2.date()
|
||||
|
||||
d1 = datetime.datetime(1970, 1, 1, 0, 0, 1, 9999)
|
||||
d2 = datetime.datetime(1970, 1, 1, 0, 0, 1, 9000)
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1.date())
|
||||
self.assertEqual(log.date, d2.date())
|
||||
assert log.date == d1.date()
|
||||
assert log.date == d2.date()
|
||||
|
||||
if not six.PY3:
|
||||
# Pre UTC dates microseconds below 1000 are dropped
|
||||
@@ -94,8 +97,8 @@ class TestDateField(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date, d1.date())
|
||||
self.assertEqual(log.date, d2.date())
|
||||
assert log.date == d1.date()
|
||||
assert log.date == d2.date()
|
||||
|
||||
def test_regular_usage(self):
|
||||
"""Tests for regular datetime fields"""
|
||||
@@ -113,35 +116,35 @@ class TestDateField(MongoDBTestCase):
|
||||
|
||||
for query in (d1, d1.isoformat(" ")):
|
||||
log1 = LogEntry.objects.get(date=query)
|
||||
self.assertEqual(log, log1)
|
||||
assert log == log1
|
||||
|
||||
if dateutil:
|
||||
log1 = LogEntry.objects.get(date=d1.isoformat("T"))
|
||||
self.assertEqual(log, log1)
|
||||
assert log == log1
|
||||
|
||||
# create additional 19 log entries for a total of 20
|
||||
for i in range(1971, 1990):
|
||||
d = datetime.datetime(i, 1, 1, 0, 0, 1)
|
||||
LogEntry(date=d).save()
|
||||
|
||||
self.assertEqual(LogEntry.objects.count(), 20)
|
||||
assert LogEntry.objects.count() == 20
|
||||
|
||||
# Test ordering
|
||||
logs = LogEntry.objects.order_by("date")
|
||||
i = 0
|
||||
while i < 19:
|
||||
self.assertTrue(logs[i].date <= logs[i + 1].date)
|
||||
assert logs[i].date <= logs[i + 1].date
|
||||
i += 1
|
||||
|
||||
logs = LogEntry.objects.order_by("-date")
|
||||
i = 0
|
||||
while i < 19:
|
||||
self.assertTrue(logs[i].date >= logs[i + 1].date)
|
||||
assert logs[i].date >= logs[i + 1].date
|
||||
i += 1
|
||||
|
||||
# Test searching
|
||||
logs = LogEntry.objects.filter(date__gte=datetime.datetime(1980, 1, 1))
|
||||
self.assertEqual(logs.count(), 10)
|
||||
assert logs.count() == 10
|
||||
|
||||
def test_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to datetime
|
||||
@@ -166,6 +169,8 @@ class TestDateField(MongoDBTestCase):
|
||||
log.validate()
|
||||
|
||||
log.time = -1
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
log.time = "ABC"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
|
||||
@@ -11,6 +11,7 @@ from mongoengine import *
|
||||
from mongoengine import connection
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestDateTimeField(MongoDBTestCase):
|
||||
@@ -24,7 +25,8 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
dt = DateTimeField()
|
||||
|
||||
md = MyDoc(dt="")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
with pytest.raises(ValidationError):
|
||||
md.save()
|
||||
|
||||
def test_datetime_from_whitespace_string(self):
|
||||
"""
|
||||
@@ -36,7 +38,8 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
dt = DateTimeField()
|
||||
|
||||
md = MyDoc(dt=" ")
|
||||
self.assertRaises(ValidationError, md.save)
|
||||
with pytest.raises(ValidationError):
|
||||
md.save()
|
||||
|
||||
def test_default_value_utcnow(self):
|
||||
"""Ensure that default field values are used when creating
|
||||
@@ -50,11 +53,9 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
person = Person()
|
||||
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)
|
||||
assert person.created - utcnow < dt.timedelta(seconds=1)
|
||||
assert person_created_t0 == person.created # make sure it does not change
|
||||
assert person._data["created"] == person.created
|
||||
|
||||
def test_handling_microseconds(self):
|
||||
"""Tests showing pymongo datetime fields handling of microseconds.
|
||||
@@ -74,7 +75,7 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.date = dt.date.today()
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertEqual(log.date.date(), dt.date.today())
|
||||
assert log.date.date() == dt.date.today()
|
||||
|
||||
# Post UTC - microseconds are rounded (down) nearest millisecond and
|
||||
# dropped
|
||||
@@ -84,8 +85,8 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertNotEqual(log.date, d1)
|
||||
self.assertEqual(log.date, d2)
|
||||
assert log.date != d1
|
||||
assert log.date == d2
|
||||
|
||||
# Post UTC - microseconds are rounded (down) nearest millisecond
|
||||
d1 = dt.datetime(1970, 1, 1, 0, 0, 1, 9999)
|
||||
@@ -93,8 +94,8 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertNotEqual(log.date, d1)
|
||||
self.assertEqual(log.date, d2)
|
||||
assert log.date != d1
|
||||
assert log.date == d2
|
||||
|
||||
if not six.PY3:
|
||||
# Pre UTC dates microseconds below 1000 are dropped
|
||||
@@ -104,8 +105,8 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.date = d1
|
||||
log.save()
|
||||
log.reload()
|
||||
self.assertNotEqual(log.date, d1)
|
||||
self.assertEqual(log.date, d2)
|
||||
assert log.date != d1
|
||||
assert log.date == d2
|
||||
|
||||
def test_regular_usage(self):
|
||||
"""Tests for regular datetime fields"""
|
||||
@@ -123,43 +124,43 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
|
||||
for query in (d1, d1.isoformat(" ")):
|
||||
log1 = LogEntry.objects.get(date=query)
|
||||
self.assertEqual(log, log1)
|
||||
assert log == log1
|
||||
|
||||
if dateutil:
|
||||
log1 = LogEntry.objects.get(date=d1.isoformat("T"))
|
||||
self.assertEqual(log, log1)
|
||||
assert log == log1
|
||||
|
||||
# create additional 19 log entries for a total of 20
|
||||
for i in range(1971, 1990):
|
||||
d = dt.datetime(i, 1, 1, 0, 0, 1)
|
||||
LogEntry(date=d).save()
|
||||
|
||||
self.assertEqual(LogEntry.objects.count(), 20)
|
||||
assert LogEntry.objects.count() == 20
|
||||
|
||||
# Test ordering
|
||||
logs = LogEntry.objects.order_by("date")
|
||||
i = 0
|
||||
while i < 19:
|
||||
self.assertTrue(logs[i].date <= logs[i + 1].date)
|
||||
assert logs[i].date <= logs[i + 1].date
|
||||
i += 1
|
||||
|
||||
logs = LogEntry.objects.order_by("-date")
|
||||
i = 0
|
||||
while i < 19:
|
||||
self.assertTrue(logs[i].date >= logs[i + 1].date)
|
||||
assert logs[i].date >= logs[i + 1].date
|
||||
i += 1
|
||||
|
||||
# Test searching
|
||||
logs = LogEntry.objects.filter(date__gte=dt.datetime(1980, 1, 1))
|
||||
self.assertEqual(logs.count(), 10)
|
||||
assert logs.count() == 10
|
||||
|
||||
logs = LogEntry.objects.filter(date__lte=dt.datetime(1980, 1, 1))
|
||||
self.assertEqual(logs.count(), 10)
|
||||
assert logs.count() == 10
|
||||
|
||||
logs = LogEntry.objects.filter(
|
||||
date__lte=dt.datetime(1980, 1, 1), date__gte=dt.datetime(1975, 1, 1)
|
||||
)
|
||||
self.assertEqual(logs.count(), 5)
|
||||
assert logs.count() == 5
|
||||
|
||||
def test_datetime_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to datetime
|
||||
@@ -187,15 +188,20 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
log.validate()
|
||||
|
||||
log.time = -1
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
log.time = "ABC"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
log.time = "2019-05-16 21:GARBAGE:12"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
log.time = "2019-05-16 21:42:57.GARBAGE"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
log.time = "2019-05-16 21:42:57.123.456"
|
||||
self.assertRaises(ValidationError, log.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
log.validate()
|
||||
|
||||
def test_parse_datetime_as_str(self):
|
||||
class DTDoc(Document):
|
||||
@@ -206,15 +212,16 @@ class TestDateTimeField(MongoDBTestCase):
|
||||
# make sure that passing a parsable datetime works
|
||||
dtd = DTDoc()
|
||||
dtd.date = date_str
|
||||
self.assertIsInstance(dtd.date, six.string_types)
|
||||
assert isinstance(dtd.date, six.string_types)
|
||||
dtd.save()
|
||||
dtd.reload()
|
||||
|
||||
self.assertIsInstance(dtd.date, dt.datetime)
|
||||
self.assertEqual(str(dtd.date), date_str)
|
||||
assert isinstance(dtd.date, dt.datetime)
|
||||
assert str(dtd.date) == date_str
|
||||
|
||||
dtd.date = "January 1st, 9999999999"
|
||||
self.assertRaises(ValidationError, dtd.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
dtd.validate()
|
||||
|
||||
|
||||
class TestDateTimeTzAware(MongoDBTestCase):
|
||||
@@ -235,4 +242,4 @@ class TestDateTimeTzAware(MongoDBTestCase):
|
||||
|
||||
log = LogEntry.objects.first()
|
||||
log.time = dt.datetime(2013, 1, 1, 0, 0, 0)
|
||||
self.assertEqual(["time"], log._changed_fields)
|
||||
assert ["time"] == log._changed_fields
|
||||
|
||||
@@ -4,6 +4,7 @@ from decimal import Decimal
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestDecimalField(MongoDBTestCase):
|
||||
@@ -18,21 +19,26 @@ class TestDecimalField(MongoDBTestCase):
|
||||
|
||||
Person(height=Decimal("1.89")).save()
|
||||
person = Person.objects.first()
|
||||
self.assertEqual(person.height, Decimal("1.89"))
|
||||
assert person.height == Decimal("1.89")
|
||||
|
||||
person.height = "2.0"
|
||||
person.save()
|
||||
person.height = 0.01
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.height = Decimal("0.01")
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.height = Decimal("4.0")
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.height = "something invalid"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
person_2 = Person(height="something invalid")
|
||||
self.assertRaises(ValidationError, person_2.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person_2.validate()
|
||||
|
||||
def test_comparison(self):
|
||||
class Person(Document):
|
||||
@@ -45,11 +51,11 @@ class TestDecimalField(MongoDBTestCase):
|
||||
Person(money=8).save()
|
||||
Person(money=10).save()
|
||||
|
||||
self.assertEqual(2, Person.objects(money__gt=Decimal("7")).count())
|
||||
self.assertEqual(2, Person.objects(money__gt=7).count())
|
||||
self.assertEqual(2, Person.objects(money__gt="7").count())
|
||||
assert 2 == Person.objects(money__gt=Decimal("7")).count()
|
||||
assert 2 == Person.objects(money__gt=7).count()
|
||||
assert 2 == Person.objects(money__gt="7").count()
|
||||
|
||||
self.assertEqual(3, Person.objects(money__gte="7").count())
|
||||
assert 3 == Person.objects(money__gte="7").count()
|
||||
|
||||
def test_storage(self):
|
||||
class Person(Document):
|
||||
@@ -87,7 +93,7 @@ class TestDecimalField(MongoDBTestCase):
|
||||
]
|
||||
expected.extend(expected)
|
||||
actual = list(Person.objects.exclude("id").as_pymongo())
|
||||
self.assertEqual(expected, actual)
|
||||
assert expected == actual
|
||||
|
||||
# How it comes out locally
|
||||
expected = [
|
||||
@@ -101,4 +107,4 @@ class TestDecimalField(MongoDBTestCase):
|
||||
expected.extend(expected)
|
||||
for field_name in ["float_value", "string_value"]:
|
||||
actual = list(Person.objects().scalar(field_name))
|
||||
self.assertEqual(expected, actual)
|
||||
assert expected == actual
|
||||
|
||||
@@ -3,6 +3,7 @@ from mongoengine import *
|
||||
from mongoengine.base import BaseDict
|
||||
|
||||
from tests.utils import MongoDBTestCase, get_as_pymongo
|
||||
import pytest
|
||||
|
||||
|
||||
class TestDictField(MongoDBTestCase):
|
||||
@@ -14,7 +15,7 @@ class TestDictField(MongoDBTestCase):
|
||||
|
||||
info = {"testkey": "testvalue"}
|
||||
post = BlogPost(info=info).save()
|
||||
self.assertEqual(get_as_pymongo(post), {"_id": post.id, "info": info})
|
||||
assert get_as_pymongo(post) == {"_id": post.id, "info": info}
|
||||
|
||||
def test_general_things(self):
|
||||
"""Ensure that dict types work as expected."""
|
||||
@@ -26,25 +27,32 @@ class TestDictField(MongoDBTestCase):
|
||||
|
||||
post = BlogPost()
|
||||
post.info = "my post"
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = ["test", "test"]
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = {"$title": "test"}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = {"nested": {"$title": "test"}}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = {"the.title": "test"}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = {"nested": {"the.title": "test"}}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = {1: "test"}
|
||||
self.assertRaises(ValidationError, post.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post.validate()
|
||||
|
||||
post.info = {"title": "test"}
|
||||
post.save()
|
||||
@@ -61,33 +69,27 @@ class TestDictField(MongoDBTestCase):
|
||||
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__details__test__exact="test").count(), 1
|
||||
)
|
||||
assert BlogPost.objects.count() == 4
|
||||
assert BlogPost.objects.filter(info__title__exact="test").count() == 1
|
||||
assert 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"])
|
||||
assert "te$t" in post["info"]["details"]
|
||||
|
||||
# Confirm handles non strings or non existing keys
|
||||
self.assertEqual(
|
||||
BlogPost.objects.filter(info__details__test__exact=5).count(), 0
|
||||
)
|
||||
self.assertEqual(
|
||||
BlogPost.objects.filter(info__made_up__test__exact="test").count(), 0
|
||||
)
|
||||
assert BlogPost.objects.filter(info__details__test__exact=5).count() == 0
|
||||
assert BlogPost.objects.filter(info__made_up__test__exact="test").count() == 0
|
||||
|
||||
post = BlogPost.objects.create(info={"title": "original"})
|
||||
post.info.update({"title": "updated"})
|
||||
post.save()
|
||||
post.reload()
|
||||
self.assertEqual("updated", post.info["title"])
|
||||
assert "updated" == post.info["title"]
|
||||
|
||||
post.info.setdefault("authors", [])
|
||||
post.save()
|
||||
post.reload()
|
||||
self.assertEqual([], post.info["authors"])
|
||||
assert [] == post.info["authors"]
|
||||
|
||||
def test_dictfield_dump_document(self):
|
||||
"""Ensure a DictField can handle another document's dump."""
|
||||
@@ -114,10 +116,8 @@ class TestDictField(MongoDBTestCase):
|
||||
).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": {}}}
|
||||
)
|
||||
assert isinstance(doc.field, dict)
|
||||
assert 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(
|
||||
@@ -125,7 +125,7 @@ class TestDictField(MongoDBTestCase):
|
||||
).save()
|
||||
doc = Doc(field=to_embed_child.to_mongo().to_dict())
|
||||
doc.save()
|
||||
self.assertIsInstance(doc.field, dict)
|
||||
assert isinstance(doc.field, dict)
|
||||
expected = {
|
||||
"_id": 2,
|
||||
"_cls": "ToEmbedParent.ToEmbedChild",
|
||||
@@ -135,7 +135,7 @@ class TestDictField(MongoDBTestCase):
|
||||
"recursive": {},
|
||||
},
|
||||
}
|
||||
self.assertEqual(doc.field, expected)
|
||||
assert doc.field == expected
|
||||
|
||||
def test_dictfield_strict(self):
|
||||
"""Ensure that dict field handles validation if provided a strict field type."""
|
||||
@@ -150,7 +150,7 @@ class TestDictField(MongoDBTestCase):
|
||||
e.save()
|
||||
|
||||
# try creating an invalid mapping
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
e.mapping["somestring"] = "abc"
|
||||
e.save()
|
||||
|
||||
@@ -184,22 +184,21 @@ class TestDictField(MongoDBTestCase):
|
||||
e.save()
|
||||
|
||||
e2 = Simple.objects.get(id=e.id)
|
||||
self.assertIsInstance(e2.mapping["somestring"], StringSetting)
|
||||
self.assertIsInstance(e2.mapping["someint"], IntegerSetting)
|
||||
assert isinstance(e2.mapping["somestring"], StringSetting)
|
||||
assert isinstance(e2.mapping["someint"], IntegerSetting)
|
||||
|
||||
# Test querying
|
||||
self.assertEqual(Simple.objects.filter(mapping__someint__value=42).count(), 1)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__number=1).count(), 1
|
||||
assert Simple.objects.filter(mapping__someint__value=42).count() == 1
|
||||
assert Simple.objects.filter(mapping__nested_dict__number=1).count() == 1
|
||||
assert (
|
||||
Simple.objects.filter(mapping__nested_dict__complex__value=42).count() == 1
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__complex__value=42).count(), 1
|
||||
assert (
|
||||
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
|
||||
assert (
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value="foo").count()
|
||||
== 1
|
||||
)
|
||||
|
||||
# Confirm can update
|
||||
@@ -207,11 +206,13 @@ class TestDictField(MongoDBTestCase):
|
||||
Simple.objects().update(
|
||||
set__mapping__nested_dict__list__1=StringSetting(value="Boo")
|
||||
)
|
||||
self.assertEqual(
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value="foo").count(), 0
|
||||
assert (
|
||||
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
|
||||
assert (
|
||||
Simple.objects.filter(mapping__nested_dict__list__1__value="Boo").count()
|
||||
== 1
|
||||
)
|
||||
|
||||
def test_push_dict(self):
|
||||
@@ -221,12 +222,12 @@ class TestDictField(MongoDBTestCase):
|
||||
doc = MyModel(events=[{"a": 1}]).save()
|
||||
raw_doc = get_as_pymongo(doc)
|
||||
expected_raw_doc = {"_id": doc.id, "events": [{"a": 1}]}
|
||||
self.assertEqual(raw_doc, expected_raw_doc)
|
||||
assert 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}, {}]}
|
||||
self.assertEqual(raw_doc, expected_raw_doc)
|
||||
assert raw_doc == expected_raw_doc
|
||||
|
||||
def test_ensure_unique_default_instances(self):
|
||||
"""Ensure that every field has it's own unique default instance."""
|
||||
@@ -239,8 +240,8 @@ class TestDictField(MongoDBTestCase):
|
||||
d1.data["foo"] = "bar"
|
||||
d1.data2["foo"] = "bar"
|
||||
d2 = D()
|
||||
self.assertEqual(d2.data, {})
|
||||
self.assertEqual(d2.data2, {})
|
||||
assert d2.data == {}
|
||||
assert d2.data2 == {}
|
||||
|
||||
def test_dict_field_invalid_dict_value(self):
|
||||
class DictFieldTest(Document):
|
||||
@@ -250,11 +251,13 @@ class TestDictField(MongoDBTestCase):
|
||||
|
||||
test = DictFieldTest(dictionary=None)
|
||||
test.dictionary # Just access to test getter
|
||||
self.assertRaises(ValidationError, test.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
test.validate()
|
||||
|
||||
test = DictFieldTest(dictionary=False)
|
||||
test.dictionary # Just access to test getter
|
||||
self.assertRaises(ValidationError, test.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
test.validate()
|
||||
|
||||
def test_dict_field_raises_validation_error_if_wrongly_assign_embedded_doc(self):
|
||||
class DictFieldTest(Document):
|
||||
@@ -267,12 +270,10 @@ class TestDictField(MongoDBTestCase):
|
||||
|
||||
embed = Embedded(name="garbage")
|
||||
doc = DictFieldTest(dictionary=embed)
|
||||
with self.assertRaises(ValidationError) as ctx_err:
|
||||
with pytest.raises(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)
|
||||
)
|
||||
assert "'dictionary'" in str(ctx_err.exception)
|
||||
assert "Only dictionaries may be used in a DictField" in str(ctx_err.exception)
|
||||
|
||||
def test_atomic_update_dict_field(self):
|
||||
"""Ensure that the entire DictField can be atomically updated."""
|
||||
@@ -287,11 +288,11 @@ class TestDictField(MongoDBTestCase):
|
||||
e.save()
|
||||
e.update(set__mapping={"ints": [3, 4]})
|
||||
e.reload()
|
||||
self.assertEqual(BaseDict, type(e.mapping))
|
||||
self.assertEqual({"ints": [3, 4]}, e.mapping)
|
||||
assert BaseDict == type(e.mapping)
|
||||
assert {"ints": [3, 4]} == e.mapping
|
||||
|
||||
# try creating an invalid mapping
|
||||
with self.assertRaises(ValueError):
|
||||
with pytest.raises(ValueError):
|
||||
e.update(set__mapping={"somestrings": ["foo", "bar"]})
|
||||
|
||||
def test_dictfield_with_referencefield_complex_nesting_cases(self):
|
||||
@@ -329,13 +330,13 @@ class TestDictField(MongoDBTestCase):
|
||||
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)
|
||||
assert isinstance(s.mapping0["someint"], Doc)
|
||||
assert isinstance(s.mapping1["someint"], Doc)
|
||||
assert isinstance(s.mapping2["someint"][0], Doc)
|
||||
assert isinstance(s.mapping3["someint"][0], Doc)
|
||||
assert isinstance(s.mapping4["someint"]["d"], Doc)
|
||||
assert isinstance(s.mapping5["someint"]["d"], Doc)
|
||||
assert isinstance(s.mapping6["someint"][0]["d"], Doc)
|
||||
assert isinstance(s.mapping7["someint"][0]["d"], Doc)
|
||||
assert isinstance(s.mapping8["someint"][0]["d"][0], Doc)
|
||||
assert isinstance(s.mapping9["someint"][0]["d"][0], Doc)
|
||||
|
||||
@@ -5,6 +5,7 @@ from unittest import SkipTest
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestEmailField(MongoDBTestCase):
|
||||
@@ -27,7 +28,8 @@ class TestEmailField(MongoDBTestCase):
|
||||
user.validate()
|
||||
|
||||
user = User(email="ross@example.com.")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
# unicode domain
|
||||
user = User(email=u"user@пример.рф")
|
||||
@@ -35,11 +37,13 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
# invalid unicode domain
|
||||
user = User(email=u"user@пример")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
# invalid data type
|
||||
user = User(email=123)
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
def test_email_field_unicode_user(self):
|
||||
# Don't run this test on pypy3, which doesn't support unicode regex:
|
||||
@@ -52,7 +56,8 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
# unicode user shouldn't validate by default...
|
||||
user = User(email=u"Dörte@Sörensen.example.com")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
# ...but it should be fine with allow_utf8_user set to True
|
||||
class User(Document):
|
||||
@@ -67,7 +72,8 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
# localhost domain shouldn't validate by default...
|
||||
user = User(email="me@localhost")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
# ...but it should be fine if it's whitelisted
|
||||
class User(Document):
|
||||
@@ -82,9 +88,9 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
invalid_idn = ".google.com"
|
||||
user = User(email="me@%s" % invalid_idn)
|
||||
with self.assertRaises(ValidationError) as ctx_err:
|
||||
with pytest.raises(ValidationError) as ctx_err:
|
||||
user.validate()
|
||||
self.assertIn("domain failed IDN encoding", str(ctx_err.exception))
|
||||
assert "domain failed IDN encoding" in str(ctx_err.exception)
|
||||
|
||||
def test_email_field_ip_domain(self):
|
||||
class User(Document):
|
||||
@@ -96,13 +102,16 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
# IP address as a domain shouldn't validate by default...
|
||||
user = User(email=valid_ipv4)
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
user = User(email=valid_ipv6)
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
user = User(email=invalid_ip)
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
# ...but it should be fine with allow_ip_domain set to True
|
||||
class User(Document):
|
||||
@@ -116,7 +125,8 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
# invalid IP should still fail validation
|
||||
user = User(email=invalid_ip)
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
def test_email_field_honors_regex(self):
|
||||
class User(Document):
|
||||
@@ -124,8 +134,9 @@ class TestEmailField(MongoDBTestCase):
|
||||
|
||||
# Fails regex validation
|
||||
user = User(email="me@foo.com")
|
||||
self.assertRaises(ValidationError, user.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
user.validate()
|
||||
|
||||
# Passes regex validation
|
||||
user = User(email="me@example.com")
|
||||
self.assertIsNone(user.validate())
|
||||
assert user.validate() is None
|
||||
|
||||
@@ -13,6 +13,7 @@ from mongoengine import (
|
||||
)
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
@@ -21,13 +22,13 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
name = StringField()
|
||||
|
||||
field = EmbeddedDocumentField(MyDoc)
|
||||
self.assertEqual(field.document_type_obj, MyDoc)
|
||||
assert field.document_type_obj == MyDoc
|
||||
|
||||
field2 = EmbeddedDocumentField("MyDoc")
|
||||
self.assertEqual(field2.document_type_obj, "MyDoc")
|
||||
assert field2.document_type_obj == "MyDoc"
|
||||
|
||||
def test___init___throw_error_if_document_type_is_not_EmbeddedDocument(self):
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
EmbeddedDocumentField(dict)
|
||||
|
||||
def test_document_type_throw_error_if_not_EmbeddedDocument_subclass(self):
|
||||
@@ -35,11 +36,11 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
name = StringField()
|
||||
|
||||
emb = EmbeddedDocumentField("MyDoc")
|
||||
with self.assertRaises(ValidationError) as ctx:
|
||||
with pytest.raises(ValidationError) as ctx:
|
||||
emb.document_type
|
||||
self.assertIn(
|
||||
"Invalid embedded document class provided to an EmbeddedDocumentField",
|
||||
str(ctx.exception),
|
||||
assert (
|
||||
"Invalid embedded document class provided to an EmbeddedDocumentField"
|
||||
in str(ctx.exception)
|
||||
)
|
||||
|
||||
def test_embedded_document_field_only_allow_subclasses_of_embedded_document(self):
|
||||
@@ -47,12 +48,12 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
class MyDoc(Document):
|
||||
name = StringField()
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
|
||||
class MyFailingDoc(Document):
|
||||
emb = EmbeddedDocumentField(MyDoc)
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
|
||||
class MyFailingdoc2(Document):
|
||||
emb = EmbeddedDocumentField("MyDoc")
|
||||
@@ -71,24 +72,24 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
p = Person(settings=AdminSettings(foo1="bar1", foo2="bar2"), name="John").save()
|
||||
|
||||
# Test non exiting attribute
|
||||
with self.assertRaises(InvalidQueryError) as ctx_err:
|
||||
with pytest.raises(InvalidQueryError) as ctx_err:
|
||||
Person.objects(settings__notexist="bar").first()
|
||||
self.assertEqual(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
assert unicode(ctx_err.exception) == u'Cannot resolve field "notexist"'
|
||||
|
||||
with self.assertRaises(LookUpError):
|
||||
with pytest.raises(LookUpError):
|
||||
Person.objects.only("settings.notexist")
|
||||
|
||||
# Test existing attribute
|
||||
self.assertEqual(Person.objects(settings__foo1="bar1").first().id, p.id)
|
||||
assert 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)
|
||||
assert only_p.settings.foo1 == p.settings.foo1
|
||||
assert only_p.settings.foo2 is None
|
||||
assert only_p.name is None
|
||||
|
||||
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)
|
||||
assert exclude_p.settings.foo1 is None
|
||||
assert exclude_p.settings.foo2 == p.settings.foo2
|
||||
assert exclude_p.name == p.name
|
||||
|
||||
def test_query_embedded_document_attribute_with_inheritance(self):
|
||||
class BaseSettings(EmbeddedDocument):
|
||||
@@ -107,17 +108,17 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
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(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
with pytest.raises(InvalidQueryError) as ctx_err:
|
||||
assert Person.objects(settings__notexist="bar").first().id == p.id
|
||||
assert 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)
|
||||
assert Person.objects(settings__base_foo="basefoo").first().id == p.id
|
||||
assert 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")
|
||||
self.assertIsNone(only_p.settings.sub_foo)
|
||||
assert only_p.settings.base_foo == "basefoo"
|
||||
assert only_p.settings.sub_foo is None
|
||||
|
||||
def test_query_list_embedded_document_with_inheritance(self):
|
||||
class Post(EmbeddedDocument):
|
||||
@@ -137,14 +138,14 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
|
||||
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)
|
||||
self.assertEqual(records[0].id, record_movie.id)
|
||||
assert len(records) == 1
|
||||
assert records[0].id == record_movie.id
|
||||
|
||||
records = list(Record.objects(posts__content=record_text.posts[0].content))
|
||||
self.assertEqual(len(records), 1)
|
||||
self.assertEqual(records[0].id, record_text.id)
|
||||
assert len(records) == 1
|
||||
assert records[0].id == record_text.id
|
||||
|
||||
self.assertEqual(Record.objects(posts__title="foo").count(), 2)
|
||||
assert Record.objects(posts__title="foo").count() == 2
|
||||
|
||||
|
||||
class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
@@ -167,13 +168,13 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
person.save()
|
||||
|
||||
person = Person.objects.first()
|
||||
self.assertIsInstance(person.like, Car)
|
||||
assert isinstance(person.like, Car)
|
||||
|
||||
person.like = Dish(food="arroz", number=15)
|
||||
person.save()
|
||||
|
||||
person = Person.objects.first()
|
||||
self.assertIsInstance(person.like, Dish)
|
||||
assert isinstance(person.like, Dish)
|
||||
|
||||
def test_generic_embedded_document_choices(self):
|
||||
"""Ensure you can limit GenericEmbeddedDocument choices."""
|
||||
@@ -193,13 +194,14 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
person = Person(name="Test User")
|
||||
person.like = Car(name="Fiat")
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
person.like = Dish(food="arroz", number=15)
|
||||
person.save()
|
||||
|
||||
person = Person.objects.first()
|
||||
self.assertIsInstance(person.like, Dish)
|
||||
assert isinstance(person.like, Dish)
|
||||
|
||||
def test_generic_list_embedded_document_choices(self):
|
||||
"""Ensure you can limit GenericEmbeddedDocument choices inside
|
||||
@@ -221,13 +223,14 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
person = Person(name="Test User")
|
||||
person.likes = [Car(name="Fiat")]
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
person.likes = [Dish(food="arroz", number=15)]
|
||||
person.save()
|
||||
|
||||
person = Person.objects.first()
|
||||
self.assertIsInstance(person.likes[0], Dish)
|
||||
assert isinstance(person.likes[0], Dish)
|
||||
|
||||
def test_choices_validation_documents(self):
|
||||
"""
|
||||
@@ -263,7 +266,8 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
|
||||
# Single Entry Failure
|
||||
post = BlogPost(comments=[ModeratorComments(author="mod1", message="message1")])
|
||||
self.assertRaises(ValidationError, post.save)
|
||||
with pytest.raises(ValidationError):
|
||||
post.save()
|
||||
|
||||
# Mixed Entry Failure
|
||||
post = BlogPost(
|
||||
@@ -272,7 +276,8 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
UserComments(author="user2", message="message2"),
|
||||
]
|
||||
)
|
||||
self.assertRaises(ValidationError, post.save)
|
||||
with pytest.raises(ValidationError):
|
||||
post.save()
|
||||
|
||||
def test_choices_validation_documents_inheritance(self):
|
||||
"""
|
||||
@@ -311,16 +316,16 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
p2 = Person(settings=NonAdminSettings(foo2="bar2")).save()
|
||||
|
||||
# Test non exiting attribute
|
||||
with self.assertRaises(InvalidQueryError) as ctx_err:
|
||||
with pytest.raises(InvalidQueryError) as ctx_err:
|
||||
Person.objects(settings__notexist="bar").first()
|
||||
self.assertEqual(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
assert unicode(ctx_err.exception) == u'Cannot resolve field "notexist"'
|
||||
|
||||
with self.assertRaises(LookUpError):
|
||||
with pytest.raises(LookUpError):
|
||||
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)
|
||||
assert Person.objects(settings__foo1="bar1").first().id == p1.id
|
||||
assert Person.objects(settings__foo2="bar2").first().id == p2.id
|
||||
|
||||
def test_query_generic_embedded_document_attribute_with_inheritance(self):
|
||||
class BaseSettings(EmbeddedDocument):
|
||||
@@ -339,10 +344,10 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
|
||||
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(unicode(ctx_err.exception), u'Cannot resolve field "notexist"')
|
||||
with pytest.raises(InvalidQueryError) as ctx_err:
|
||||
assert Person.objects(settings__notexist="bar").first().id == p.id
|
||||
assert 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)
|
||||
assert Person.objects(settings__base_foo="basefoo").first().id == p.id
|
||||
assert Person.objects(settings__sub_foo="subfoo").first().id == p.id
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -64,13 +64,13 @@ class TestFileField(MongoDBTestCase):
|
||||
putfile.save()
|
||||
|
||||
result = PutFile.objects.first()
|
||||
self.assertEqual(putfile, result)
|
||||
self.assertEqual(
|
||||
"%s" % result.the_file,
|
||||
"<GridFSProxy: hello (%s)>" % result.the_file.grid_id,
|
||||
assert putfile == result
|
||||
assert (
|
||||
"%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)
|
||||
assert result.the_file.read() == text
|
||||
assert result.the_file.content_type == content_type
|
||||
result.the_file.delete() # Remove file from GridFS
|
||||
PutFile.objects.delete()
|
||||
|
||||
@@ -85,9 +85,9 @@ class TestFileField(MongoDBTestCase):
|
||||
putfile.save()
|
||||
|
||||
result = PutFile.objects.first()
|
||||
self.assertEqual(putfile, result)
|
||||
self.assertEqual(result.the_file.read(), text)
|
||||
self.assertEqual(result.the_file.content_type, content_type)
|
||||
assert putfile == result
|
||||
assert result.the_file.read() == text
|
||||
assert result.the_file.content_type == content_type
|
||||
result.the_file.delete()
|
||||
|
||||
def test_file_fields_stream(self):
|
||||
@@ -111,19 +111,19 @@ class TestFileField(MongoDBTestCase):
|
||||
streamfile.save()
|
||||
|
||||
result = StreamFile.objects.first()
|
||||
self.assertEqual(streamfile, result)
|
||||
self.assertEqual(result.the_file.read(), text + more_text)
|
||||
self.assertEqual(result.the_file.content_type, content_type)
|
||||
assert streamfile == result
|
||||
assert result.the_file.read() == text + more_text
|
||||
assert result.the_file.content_type == content_type
|
||||
result.the_file.seek(0)
|
||||
self.assertEqual(result.the_file.tell(), 0)
|
||||
self.assertEqual(result.the_file.read(len(text)), text)
|
||||
self.assertEqual(result.the_file.tell(), len(text))
|
||||
self.assertEqual(result.the_file.read(len(more_text)), more_text)
|
||||
self.assertEqual(result.the_file.tell(), len(text + more_text))
|
||||
assert result.the_file.tell() == 0
|
||||
assert result.the_file.read(len(text)) == text
|
||||
assert result.the_file.tell() == len(text)
|
||||
assert result.the_file.read(len(more_text)) == more_text
|
||||
assert result.the_file.tell() == len(text + more_text)
|
||||
result.the_file.delete()
|
||||
|
||||
# Ensure deleted file returns None
|
||||
self.assertTrue(result.the_file.read() is None)
|
||||
assert result.the_file.read() is None
|
||||
|
||||
def test_file_fields_stream_after_none(self):
|
||||
"""Ensure that a file field can be written to after it has been saved as
|
||||
@@ -148,19 +148,19 @@ class TestFileField(MongoDBTestCase):
|
||||
streamfile.save()
|
||||
|
||||
result = StreamFile.objects.first()
|
||||
self.assertEqual(streamfile, result)
|
||||
self.assertEqual(result.the_file.read(), text + more_text)
|
||||
assert streamfile == result
|
||||
assert result.the_file.read() == text + more_text
|
||||
# self.assertEqual(result.the_file.content_type, content_type)
|
||||
result.the_file.seek(0)
|
||||
self.assertEqual(result.the_file.tell(), 0)
|
||||
self.assertEqual(result.the_file.read(len(text)), text)
|
||||
self.assertEqual(result.the_file.tell(), len(text))
|
||||
self.assertEqual(result.the_file.read(len(more_text)), more_text)
|
||||
self.assertEqual(result.the_file.tell(), len(text + more_text))
|
||||
assert result.the_file.tell() == 0
|
||||
assert result.the_file.read(len(text)) == text
|
||||
assert result.the_file.tell() == len(text)
|
||||
assert result.the_file.read(len(more_text)) == more_text
|
||||
assert result.the_file.tell() == len(text + more_text)
|
||||
result.the_file.delete()
|
||||
|
||||
# Ensure deleted file returns None
|
||||
self.assertTrue(result.the_file.read() is None)
|
||||
assert result.the_file.read() is None
|
||||
|
||||
def test_file_fields_set(self):
|
||||
class SetFile(Document):
|
||||
@@ -176,16 +176,16 @@ class TestFileField(MongoDBTestCase):
|
||||
setfile.save()
|
||||
|
||||
result = SetFile.objects.first()
|
||||
self.assertEqual(setfile, result)
|
||||
self.assertEqual(result.the_file.read(), text)
|
||||
assert setfile == result
|
||||
assert result.the_file.read() == text
|
||||
|
||||
# Try replacing file with new one
|
||||
result.the_file.replace(more_text)
|
||||
result.save()
|
||||
|
||||
result = SetFile.objects.first()
|
||||
self.assertEqual(setfile, result)
|
||||
self.assertEqual(result.the_file.read(), more_text)
|
||||
assert setfile == result
|
||||
assert result.the_file.read() == more_text
|
||||
result.the_file.delete()
|
||||
|
||||
def test_file_field_no_default(self):
|
||||
@@ -205,28 +205,28 @@ class TestFileField(MongoDBTestCase):
|
||||
doc_b = GridDocument.objects.with_id(doc_a.id)
|
||||
doc_b.the_file.replace(f, filename="doc_b")
|
||||
doc_b.save()
|
||||
self.assertNotEqual(doc_b.the_file.grid_id, None)
|
||||
assert doc_b.the_file.grid_id != None
|
||||
|
||||
# Test it matches
|
||||
doc_c = GridDocument.objects.with_id(doc_b.id)
|
||||
self.assertEqual(doc_b.the_file.grid_id, doc_c.the_file.grid_id)
|
||||
assert doc_b.the_file.grid_id == doc_c.the_file.grid_id
|
||||
|
||||
# Test with default
|
||||
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)
|
||||
assert doc_d.the_file.grid_id == doc_e.the_file.grid_id
|
||||
|
||||
doc_e.the_file.replace(f, filename="doc_e")
|
||||
doc_e.save()
|
||||
|
||||
doc_f = GridDocument.objects.with_id(doc_e.id)
|
||||
self.assertEqual(doc_e.the_file.grid_id, doc_f.the_file.grid_id)
|
||||
assert doc_e.the_file.grid_id == doc_f.the_file.grid_id
|
||||
|
||||
db = GridDocument._get_db()
|
||||
grid_fs = gridfs.GridFS(db)
|
||||
self.assertEqual(["doc_b", "doc_e"], grid_fs.list())
|
||||
assert ["doc_b", "doc_e"] == grid_fs.list()
|
||||
|
||||
def test_file_uniqueness(self):
|
||||
"""Ensure that each instance of a FileField is unique
|
||||
@@ -246,8 +246,8 @@ class TestFileField(MongoDBTestCase):
|
||||
test_file_dupe = TestFile()
|
||||
data = test_file_dupe.the_file.read() # Should be None
|
||||
|
||||
self.assertNotEqual(test_file.name, test_file_dupe.name)
|
||||
self.assertNotEqual(test_file.the_file.read(), data)
|
||||
assert test_file.name != test_file_dupe.name
|
||||
assert test_file.the_file.read() != data
|
||||
|
||||
TestFile.drop_collection()
|
||||
|
||||
@@ -268,8 +268,8 @@ class TestFileField(MongoDBTestCase):
|
||||
marmot.save()
|
||||
|
||||
marmot = Animal.objects.get()
|
||||
self.assertEqual(marmot.photo.content_type, "image/jpeg")
|
||||
self.assertEqual(marmot.photo.foo, "bar")
|
||||
assert marmot.photo.content_type == "image/jpeg"
|
||||
assert marmot.photo.foo == "bar"
|
||||
|
||||
def test_file_reassigning(self):
|
||||
class TestFile(Document):
|
||||
@@ -278,12 +278,12 @@ class TestFileField(MongoDBTestCase):
|
||||
TestFile.drop_collection()
|
||||
|
||||
test_file = TestFile(the_file=get_file(TEST_IMAGE_PATH)).save()
|
||||
self.assertEqual(test_file.the_file.get().length, 8313)
|
||||
assert test_file.the_file.get().length == 8313
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
test_file.the_file = get_file(TEST_IMAGE2_PATH)
|
||||
test_file.save()
|
||||
self.assertEqual(test_file.the_file.get().length, 4971)
|
||||
assert test_file.the_file.get().length == 4971
|
||||
|
||||
def test_file_boolean(self):
|
||||
"""Ensure that a boolean test of a FileField indicates its presence
|
||||
@@ -295,13 +295,13 @@ class TestFileField(MongoDBTestCase):
|
||||
TestFile.drop_collection()
|
||||
|
||||
test_file = TestFile()
|
||||
self.assertFalse(bool(test_file.the_file))
|
||||
assert not bool(test_file.the_file)
|
||||
test_file.the_file.put(six.b("Hello, World!"), content_type="text/plain")
|
||||
test_file.save()
|
||||
self.assertTrue(bool(test_file.the_file))
|
||||
assert bool(test_file.the_file)
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
self.assertEqual(test_file.the_file.content_type, "text/plain")
|
||||
assert test_file.the_file.content_type == "text/plain"
|
||||
|
||||
def test_file_cmp(self):
|
||||
"""Test comparing against other types"""
|
||||
@@ -310,7 +310,7 @@ class TestFileField(MongoDBTestCase):
|
||||
the_file = FileField()
|
||||
|
||||
test_file = TestFile()
|
||||
self.assertNotIn(test_file.the_file, [{"test": 1}])
|
||||
assert test_file.the_file not in [{"test": 1}]
|
||||
|
||||
def test_file_disk_space(self):
|
||||
""" Test disk space usage when we delete/replace a file """
|
||||
@@ -330,16 +330,16 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
files = db.fs.files.find()
|
||||
chunks = db.fs.chunks.find()
|
||||
self.assertEqual(len(list(files)), 1)
|
||||
self.assertEqual(len(list(chunks)), 1)
|
||||
assert len(list(files)) == 1
|
||||
assert len(list(chunks)) == 1
|
||||
|
||||
# Deleting the docoument should delete the files
|
||||
testfile.delete()
|
||||
|
||||
files = db.fs.files.find()
|
||||
chunks = db.fs.chunks.find()
|
||||
self.assertEqual(len(list(files)), 0)
|
||||
self.assertEqual(len(list(chunks)), 0)
|
||||
assert len(list(files)) == 0
|
||||
assert len(list(chunks)) == 0
|
||||
|
||||
# Test case where we don't store a file in the first place
|
||||
testfile = TestFile()
|
||||
@@ -347,15 +347,15 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
files = db.fs.files.find()
|
||||
chunks = db.fs.chunks.find()
|
||||
self.assertEqual(len(list(files)), 0)
|
||||
self.assertEqual(len(list(chunks)), 0)
|
||||
assert len(list(files)) == 0
|
||||
assert len(list(chunks)) == 0
|
||||
|
||||
testfile.delete()
|
||||
|
||||
files = db.fs.files.find()
|
||||
chunks = db.fs.chunks.find()
|
||||
self.assertEqual(len(list(files)), 0)
|
||||
self.assertEqual(len(list(chunks)), 0)
|
||||
assert len(list(files)) == 0
|
||||
assert len(list(chunks)) == 0
|
||||
|
||||
# Test case where we overwrite the file
|
||||
testfile = TestFile()
|
||||
@@ -368,15 +368,15 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
files = db.fs.files.find()
|
||||
chunks = db.fs.chunks.find()
|
||||
self.assertEqual(len(list(files)), 1)
|
||||
self.assertEqual(len(list(chunks)), 1)
|
||||
assert len(list(files)) == 1
|
||||
assert len(list(chunks)) == 1
|
||||
|
||||
testfile.delete()
|
||||
|
||||
files = db.fs.files.find()
|
||||
chunks = db.fs.chunks.find()
|
||||
self.assertEqual(len(list(files)), 0)
|
||||
self.assertEqual(len(list(chunks)), 0)
|
||||
assert len(list(files)) == 0
|
||||
assert len(list(chunks)) == 0
|
||||
|
||||
def test_image_field(self):
|
||||
if not HAS_PIL:
|
||||
@@ -396,9 +396,7 @@ class TestFileField(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
|
||||
)
|
||||
assert "%s" % e == "Invalid image: cannot identify image file %s" % f
|
||||
|
||||
t = TestImage()
|
||||
t.image.put(get_file(TEST_IMAGE_PATH))
|
||||
@@ -406,11 +404,11 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.format, "PNG")
|
||||
assert t.image.format == "PNG"
|
||||
|
||||
w, h = t.image.size
|
||||
self.assertEqual(w, 371)
|
||||
self.assertEqual(h, 76)
|
||||
assert w == 371
|
||||
assert h == 76
|
||||
|
||||
t.image.delete()
|
||||
|
||||
@@ -424,12 +422,12 @@ class TestFileField(MongoDBTestCase):
|
||||
TestFile.drop_collection()
|
||||
|
||||
test_file = TestFile(the_file=get_file(TEST_IMAGE_PATH)).save()
|
||||
self.assertEqual(test_file.the_file.size, (371, 76))
|
||||
assert test_file.the_file.size == (371, 76)
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
test_file.the_file = get_file(TEST_IMAGE2_PATH)
|
||||
test_file.save()
|
||||
self.assertEqual(test_file.the_file.size, (45, 101))
|
||||
assert test_file.the_file.size == (45, 101)
|
||||
|
||||
def test_image_field_resize(self):
|
||||
if not HAS_PIL:
|
||||
@@ -446,11 +444,11 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.format, "PNG")
|
||||
assert t.image.format == "PNG"
|
||||
w, h = t.image.size
|
||||
|
||||
self.assertEqual(w, 185)
|
||||
self.assertEqual(h, 37)
|
||||
assert w == 185
|
||||
assert h == 37
|
||||
|
||||
t.image.delete()
|
||||
|
||||
@@ -469,11 +467,11 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.format, "PNG")
|
||||
assert t.image.format == "PNG"
|
||||
w, h = t.image.size
|
||||
|
||||
self.assertEqual(w, 185)
|
||||
self.assertEqual(h, 37)
|
||||
assert w == 185
|
||||
assert h == 37
|
||||
|
||||
t.image.delete()
|
||||
|
||||
@@ -492,9 +490,9 @@ class TestFileField(MongoDBTestCase):
|
||||
|
||||
t = TestImage.objects.first()
|
||||
|
||||
self.assertEqual(t.image.thumbnail.format, "PNG")
|
||||
self.assertEqual(t.image.thumbnail.width, 92)
|
||||
self.assertEqual(t.image.thumbnail.height, 18)
|
||||
assert t.image.thumbnail.format == "PNG"
|
||||
assert t.image.thumbnail.width == 92
|
||||
assert t.image.thumbnail.height == 18
|
||||
|
||||
t.image.delete()
|
||||
|
||||
@@ -518,17 +516,17 @@ class TestFileField(MongoDBTestCase):
|
||||
test_file.save()
|
||||
|
||||
data = get_db("test_files").macumba.files.find_one()
|
||||
self.assertEqual(data.get("name"), "hello.txt")
|
||||
assert data.get("name") == "hello.txt"
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
self.assertEqual(test_file.the_file.read(), six.b("Hello, World!"))
|
||||
assert test_file.the_file.read() == six.b("Hello, World!")
|
||||
|
||||
test_file = TestFile.objects.first()
|
||||
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!"))
|
||||
assert test_file.the_file.read() == six.b("HELLO, WORLD!")
|
||||
|
||||
def test_copyable(self):
|
||||
class PutFile(Document):
|
||||
@@ -546,8 +544,8 @@ class TestFileField(MongoDBTestCase):
|
||||
class TestFile(Document):
|
||||
name = StringField()
|
||||
|
||||
self.assertEqual(putfile, copy.copy(putfile))
|
||||
self.assertEqual(putfile, copy.deepcopy(putfile))
|
||||
assert putfile == copy.copy(putfile)
|
||||
assert putfile == copy.deepcopy(putfile)
|
||||
|
||||
def test_get_image_by_grid_id(self):
|
||||
|
||||
@@ -569,9 +567,7 @@ class TestFileField(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()
|
||||
)
|
||||
assert 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"""
|
||||
@@ -593,9 +589,9 @@ class TestFileField(MongoDBTestCase):
|
||||
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].get().length, 8313)
|
||||
assert marmot.photos[0].content_type == "image/jpeg"
|
||||
assert marmot.photos[0].foo == "bar"
|
||||
assert marmot.photos[0].get().length == 8313
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -4,6 +4,7 @@ import six
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestFloatField(MongoDBTestCase):
|
||||
@@ -16,8 +17,8 @@ class TestFloatField(MongoDBTestCase):
|
||||
TestDocument(float_fld=None).save()
|
||||
TestDocument(float_fld=1).save()
|
||||
|
||||
self.assertEqual(1, TestDocument.objects(float_fld__ne=None).count())
|
||||
self.assertEqual(1, TestDocument.objects(float_fld__ne=1).count())
|
||||
assert 1 == TestDocument.objects(float_fld__ne=None).count()
|
||||
assert 1 == TestDocument.objects(float_fld__ne=1).count()
|
||||
|
||||
def test_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to float fields.
|
||||
@@ -34,16 +35,20 @@ class TestFloatField(MongoDBTestCase):
|
||||
person.validate()
|
||||
|
||||
person.height = "2.0"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
person.height = 0.01
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
person.height = 4.0
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
person_2 = Person(height="something invalid")
|
||||
self.assertRaises(ValidationError, person_2.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person_2.validate()
|
||||
|
||||
big_person = BigPerson()
|
||||
|
||||
@@ -55,4 +60,5 @@ class TestFloatField(MongoDBTestCase):
|
||||
big_person.validate()
|
||||
|
||||
big_person.height = 2 ** 100000 # Too big for a float value
|
||||
self.assertRaises(ValidationError, big_person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
big_person.validate()
|
||||
|
||||
@@ -11,7 +11,7 @@ class TestGeoField(MongoDBTestCase):
|
||||
Cls(loc=loc).validate()
|
||||
self.fail("Should not validate the location {0}".format(loc))
|
||||
except ValidationError as e:
|
||||
self.assertEqual(expected, e.to_dict()["loc"])
|
||||
assert expected == e.to_dict()["loc"]
|
||||
|
||||
def test_geopoint_validation(self):
|
||||
class Location(Document):
|
||||
@@ -299,7 +299,7 @@ class TestGeoField(MongoDBTestCase):
|
||||
location = GeoPointField()
|
||||
|
||||
geo_indicies = Event._geo_indices()
|
||||
self.assertEqual(geo_indicies, [{"fields": [("location", "2d")]}])
|
||||
assert geo_indicies == [{"fields": [("location", "2d")]}]
|
||||
|
||||
def test_geopoint_embedded_indexes(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields on
|
||||
@@ -315,7 +315,7 @@ class TestGeoField(MongoDBTestCase):
|
||||
venue = EmbeddedDocumentField(Venue)
|
||||
|
||||
geo_indicies = Event._geo_indices()
|
||||
self.assertEqual(geo_indicies, [{"fields": [("venue.location", "2d")]}])
|
||||
assert geo_indicies == [{"fields": [("venue.location", "2d")]}]
|
||||
|
||||
def test_indexes_2dsphere(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields.
|
||||
@@ -328,9 +328,9 @@ class TestGeoField(MongoDBTestCase):
|
||||
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)
|
||||
assert {"fields": [("line", "2dsphere")]} in geo_indicies
|
||||
assert {"fields": [("polygon", "2dsphere")]} in geo_indicies
|
||||
assert {"fields": [("point", "2dsphere")]} in geo_indicies
|
||||
|
||||
def test_indexes_2dsphere_embedded(self):
|
||||
"""Ensure that indexes are created automatically for GeoPointFields.
|
||||
@@ -347,9 +347,9 @@ class TestGeoField(MongoDBTestCase):
|
||||
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)
|
||||
assert {"fields": [("venue.line", "2dsphere")]} in geo_indicies
|
||||
assert {"fields": [("venue.polygon", "2dsphere")]} in geo_indicies
|
||||
assert {"fields": [("venue.point", "2dsphere")]} in geo_indicies
|
||||
|
||||
def test_geo_indexes_recursion(self):
|
||||
class Location(Document):
|
||||
@@ -365,12 +365,12 @@ class TestGeoField(MongoDBTestCase):
|
||||
|
||||
Parent(name="Berlin").save()
|
||||
info = Parent._get_collection().index_information()
|
||||
self.assertNotIn("location_2d", info)
|
||||
assert "location_2d" not in info
|
||||
info = Location._get_collection().index_information()
|
||||
self.assertIn("location_2d", info)
|
||||
assert "location_2d" in info
|
||||
|
||||
self.assertEqual(len(Parent._geo_indices()), 0)
|
||||
self.assertEqual(len(Location._geo_indices()), 1)
|
||||
assert len(Parent._geo_indices()) == 0
|
||||
assert len(Location._geo_indices()) == 1
|
||||
|
||||
def test_geo_indexes_auto_index(self):
|
||||
|
||||
@@ -381,16 +381,16 @@ class TestGeoField(MongoDBTestCase):
|
||||
|
||||
meta = {"indexes": [[("location", "2dsphere"), ("datetime", 1)]]}
|
||||
|
||||
self.assertEqual([], Log._geo_indices())
|
||||
assert [] == Log._geo_indices()
|
||||
|
||||
Log.drop_collection()
|
||||
Log.ensure_indexes()
|
||||
|
||||
info = Log._get_collection().index_information()
|
||||
self.assertEqual(
|
||||
info["location_2dsphere_datetime_1"]["key"],
|
||||
[("location", "2dsphere"), ("datetime", 1)],
|
||||
)
|
||||
assert info["location_2dsphere_datetime_1"]["key"] == [
|
||||
("location", "2dsphere"),
|
||||
("datetime", 1),
|
||||
]
|
||||
|
||||
# Test listing explicitly
|
||||
class Log(Document):
|
||||
@@ -401,16 +401,16 @@ class TestGeoField(MongoDBTestCase):
|
||||
"indexes": [{"fields": [("location", "2dsphere"), ("datetime", 1)]}]
|
||||
}
|
||||
|
||||
self.assertEqual([], Log._geo_indices())
|
||||
assert [] == Log._geo_indices()
|
||||
|
||||
Log.drop_collection()
|
||||
Log.ensure_indexes()
|
||||
|
||||
info = Log._get_collection().index_information()
|
||||
self.assertEqual(
|
||||
info["location_2dsphere_datetime_1"]["key"],
|
||||
[("location", "2dsphere"), ("datetime", 1)],
|
||||
)
|
||||
assert info["location_2dsphere_datetime_1"]["key"] == [
|
||||
("location", "2dsphere"),
|
||||
("datetime", 1),
|
||||
]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestIntField(MongoDBTestCase):
|
||||
@@ -23,11 +24,14 @@ class TestIntField(MongoDBTestCase):
|
||||
person.validate()
|
||||
|
||||
person.age = -1
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.age = 120
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
person.age = "ten"
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
def test_ne_operator(self):
|
||||
class TestDocument(Document):
|
||||
@@ -38,5 +42,5 @@ class TestIntField(MongoDBTestCase):
|
||||
TestDocument(int_fld=None).save()
|
||||
TestDocument(int_fld=1).save()
|
||||
|
||||
self.assertEqual(1, TestDocument.objects(int_fld__ne=None).count())
|
||||
self.assertEqual(1, TestDocument.objects(int_fld__ne=1).count())
|
||||
assert 1 == TestDocument.objects(int_fld__ne=None).count()
|
||||
assert 1 == TestDocument.objects(int_fld__ne=1).count()
|
||||
|
||||
@@ -5,13 +5,15 @@ from mongoengine import *
|
||||
from mongoengine.base import LazyReference
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestLazyReferenceField(MongoDBTestCase):
|
||||
def test_lazy_reference_config(self):
|
||||
# Make sure ReferenceField only accepts a document class or a string
|
||||
# with a document class name.
|
||||
self.assertRaises(ValidationError, LazyReferenceField, EmbeddedDocument)
|
||||
with pytest.raises(ValidationError):
|
||||
LazyReferenceField(EmbeddedDocument)
|
||||
|
||||
def test___repr__(self):
|
||||
class Animal(Document):
|
||||
@@ -25,7 +27,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
animal = Animal()
|
||||
oc = Ocurrence(animal=animal)
|
||||
self.assertIn("LazyReference", repr(oc.animal))
|
||||
assert "LazyReference" in repr(oc.animal)
|
||||
|
||||
def test___getattr___unknown_attr_raises_attribute_error(self):
|
||||
class Animal(Document):
|
||||
@@ -39,7 +41,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
animal = Animal().save()
|
||||
oc = Ocurrence(animal=animal)
|
||||
with self.assertRaises(AttributeError):
|
||||
with pytest.raises(AttributeError):
|
||||
oc.animal.not_exist
|
||||
|
||||
def test_lazy_reference_simple(self):
|
||||
@@ -57,19 +59,19 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
Ocurrence(person="test", animal=animal).save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
assert isinstance(p.animal, LazyReference)
|
||||
fetched_animal = p.animal.fetch()
|
||||
self.assertEqual(fetched_animal, animal)
|
||||
assert fetched_animal == animal
|
||||
# `fetch` keep cache on referenced document by default...
|
||||
animal.tag = "not so heavy"
|
||||
animal.save()
|
||||
double_fetch = p.animal.fetch()
|
||||
self.assertIs(fetched_animal, double_fetch)
|
||||
self.assertEqual(double_fetch.tag, "heavy")
|
||||
assert fetched_animal is double_fetch
|
||||
assert double_fetch.tag == "heavy"
|
||||
# ...unless specified otherwise
|
||||
fetch_force = p.animal.fetch(force=True)
|
||||
self.assertIsNot(fetch_force, fetched_animal)
|
||||
self.assertEqual(fetch_force.tag, "not so heavy")
|
||||
assert fetch_force is not fetched_animal
|
||||
assert fetch_force.tag == "not so heavy"
|
||||
|
||||
def test_lazy_reference_fetch_invalid_ref(self):
|
||||
class Animal(Document):
|
||||
@@ -87,8 +89,8 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
Ocurrence(person="test", animal=animal).save()
|
||||
animal.delete()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
with self.assertRaises(DoesNotExist):
|
||||
assert isinstance(p.animal, LazyReference)
|
||||
with pytest.raises(DoesNotExist):
|
||||
p.animal.fetch()
|
||||
|
||||
def test_lazy_reference_set(self):
|
||||
@@ -122,7 +124,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
):
|
||||
p = Ocurrence(person="test", animal=ref).save()
|
||||
p.reload()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
assert isinstance(p.animal, LazyReference)
|
||||
p.animal.fetch()
|
||||
|
||||
def test_lazy_reference_bad_set(self):
|
||||
@@ -149,7 +151,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
DBRef(baddoc._get_collection_name(), animal.pk),
|
||||
LazyReference(BadDoc, animal.pk),
|
||||
):
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
p = Ocurrence(person="test", animal=bad).save()
|
||||
|
||||
def test_lazy_reference_query_conversion(self):
|
||||
@@ -179,14 +181,14 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
self.assertEqual(post.id, post1.id)
|
||||
assert post.id == post1.id
|
||||
|
||||
post = BlogPost.objects(author=m2).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
# Same thing by passing a LazyReference instance
|
||||
post = BlogPost.objects(author=LazyReference(Member, m2.pk)).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
def test_lazy_reference_query_conversion_dbref(self):
|
||||
"""Ensure that LazyReferenceFields can be queried using objects and values
|
||||
@@ -215,14 +217,14 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
self.assertEqual(post.id, post1.id)
|
||||
assert post.id == post1.id
|
||||
|
||||
post = BlogPost.objects(author=m2).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
# Same thing by passing a LazyReference instance
|
||||
post = BlogPost.objects(author=LazyReference(Member, m2.pk)).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
def test_lazy_reference_passthrough(self):
|
||||
class Animal(Document):
|
||||
@@ -239,20 +241,20 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
Ocurrence(animal=animal, animal_passthrough=animal).save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
with self.assertRaises(KeyError):
|
||||
assert isinstance(p.animal, LazyReference)
|
||||
with pytest.raises(KeyError):
|
||||
p.animal["name"]
|
||||
with self.assertRaises(AttributeError):
|
||||
with pytest.raises(AttributeError):
|
||||
p.animal.name
|
||||
self.assertEqual(p.animal.pk, animal.pk)
|
||||
assert p.animal.pk == animal.pk
|
||||
|
||||
self.assertEqual(p.animal_passthrough.name, "Leopard")
|
||||
self.assertEqual(p.animal_passthrough["name"], "Leopard")
|
||||
assert p.animal_passthrough.name == "Leopard"
|
||||
assert p.animal_passthrough["name"] == "Leopard"
|
||||
|
||||
# Should not be able to access referenced document's methods
|
||||
with self.assertRaises(AttributeError):
|
||||
with pytest.raises(AttributeError):
|
||||
p.animal.save
|
||||
with self.assertRaises(KeyError):
|
||||
with pytest.raises(KeyError):
|
||||
p.animal["save"]
|
||||
|
||||
def test_lazy_reference_not_set(self):
|
||||
@@ -269,7 +271,7 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
Ocurrence(person="foo").save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIs(p.animal, None)
|
||||
assert p.animal is None
|
||||
|
||||
def test_lazy_reference_equality(self):
|
||||
class Animal(Document):
|
||||
@@ -280,12 +282,12 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
animalref = LazyReference(Animal, animal.pk)
|
||||
self.assertEqual(animal, animalref)
|
||||
self.assertEqual(animalref, animal)
|
||||
assert animal == animalref
|
||||
assert animalref == animal
|
||||
|
||||
other_animalref = LazyReference(Animal, ObjectId("54495ad94c934721ede76f90"))
|
||||
self.assertNotEqual(animal, other_animalref)
|
||||
self.assertNotEqual(other_animalref, animal)
|
||||
assert animal != other_animalref
|
||||
assert other_animalref != animal
|
||||
|
||||
def test_lazy_reference_embedded(self):
|
||||
class Animal(Document):
|
||||
@@ -308,12 +310,12 @@ class TestLazyReferenceField(MongoDBTestCase):
|
||||
animal2 = Animal(name="cheeta").save()
|
||||
|
||||
def check_fields_type(occ):
|
||||
self.assertIsInstance(occ.direct, LazyReference)
|
||||
assert isinstance(occ.direct, LazyReference)
|
||||
for elem in occ.in_list:
|
||||
self.assertIsInstance(elem, LazyReference)
|
||||
self.assertIsInstance(occ.in_embedded.direct, LazyReference)
|
||||
assert isinstance(elem, LazyReference)
|
||||
assert isinstance(occ.in_embedded.direct, LazyReference)
|
||||
for elem in occ.in_embedded.in_list:
|
||||
self.assertIsInstance(elem, LazyReference)
|
||||
assert isinstance(elem, LazyReference)
|
||||
|
||||
occ = Ocurrence(
|
||||
in_list=[animal1, animal2],
|
||||
@@ -346,19 +348,19 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
Ocurrence(person="test", animal=animal).save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIsInstance(p.animal, LazyReference)
|
||||
assert isinstance(p.animal, LazyReference)
|
||||
fetched_animal = p.animal.fetch()
|
||||
self.assertEqual(fetched_animal, animal)
|
||||
assert fetched_animal == animal
|
||||
# `fetch` keep cache on referenced document by default...
|
||||
animal.tag = "not so heavy"
|
||||
animal.save()
|
||||
double_fetch = p.animal.fetch()
|
||||
self.assertIs(fetched_animal, double_fetch)
|
||||
self.assertEqual(double_fetch.tag, "heavy")
|
||||
assert fetched_animal is double_fetch
|
||||
assert double_fetch.tag == "heavy"
|
||||
# ...unless specified otherwise
|
||||
fetch_force = p.animal.fetch(force=True)
|
||||
self.assertIsNot(fetch_force, fetched_animal)
|
||||
self.assertEqual(fetch_force.tag, "not so heavy")
|
||||
assert fetch_force is not fetched_animal
|
||||
assert fetch_force.tag == "not so heavy"
|
||||
|
||||
def test_generic_lazy_reference_choices(self):
|
||||
class Animal(Document):
|
||||
@@ -385,13 +387,13 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
occ_animal = Ocurrence(living_thing=animal, thing=animal).save()
|
||||
occ_vegetal = Ocurrence(living_thing=vegetal, thing=vegetal).save()
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
Ocurrence(living_thing=mineral).save()
|
||||
|
||||
occ = Ocurrence.objects.get(living_thing=animal)
|
||||
self.assertEqual(occ, occ_animal)
|
||||
self.assertIsInstance(occ.thing, LazyReference)
|
||||
self.assertIsInstance(occ.living_thing, LazyReference)
|
||||
assert occ == occ_animal
|
||||
assert isinstance(occ.thing, LazyReference)
|
||||
assert isinstance(occ.living_thing, LazyReference)
|
||||
|
||||
occ.thing = vegetal
|
||||
occ.living_thing = vegetal
|
||||
@@ -399,7 +401,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
occ.thing = mineral
|
||||
occ.living_thing = mineral
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
occ.save()
|
||||
|
||||
def test_generic_lazy_reference_set(self):
|
||||
@@ -434,7 +436,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
):
|
||||
p = Ocurrence(person="test", animal=ref).save()
|
||||
p.reload()
|
||||
self.assertIsInstance(p.animal, (LazyReference, Document))
|
||||
assert isinstance(p.animal, (LazyReference, Document))
|
||||
p.animal.fetch()
|
||||
|
||||
def test_generic_lazy_reference_bad_set(self):
|
||||
@@ -455,7 +457,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
animal = Animal(name="Leopard", tag="heavy").save()
|
||||
baddoc = BadDoc().save()
|
||||
for bad in (42, "foo", baddoc, LazyReference(BadDoc, animal.pk)):
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
p = Ocurrence(person="test", animal=bad).save()
|
||||
|
||||
def test_generic_lazy_reference_query_conversion(self):
|
||||
@@ -481,14 +483,14 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
self.assertEqual(post.id, post1.id)
|
||||
assert post.id == post1.id
|
||||
|
||||
post = BlogPost.objects(author=m2).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
# Same thing by passing a LazyReference instance
|
||||
post = BlogPost.objects(author=LazyReference(Member, m2.pk)).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
def test_generic_lazy_reference_not_set(self):
|
||||
class Animal(Document):
|
||||
@@ -504,7 +506,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
|
||||
Ocurrence(person="foo").save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertIs(p.animal, None)
|
||||
assert p.animal is None
|
||||
|
||||
def test_generic_lazy_reference_accepts_string_instead_of_class(self):
|
||||
class Animal(Document):
|
||||
@@ -521,7 +523,7 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
animal = Animal().save()
|
||||
Ocurrence(animal=animal).save()
|
||||
p = Ocurrence.objects.get()
|
||||
self.assertEqual(p.animal, animal)
|
||||
assert p.animal == animal
|
||||
|
||||
def test_generic_lazy_reference_embedded(self):
|
||||
class Animal(Document):
|
||||
@@ -544,12 +546,12 @@ class TestGenericLazyReferenceField(MongoDBTestCase):
|
||||
animal2 = Animal(name="cheeta").save()
|
||||
|
||||
def check_fields_type(occ):
|
||||
self.assertIsInstance(occ.direct, LazyReference)
|
||||
assert isinstance(occ.direct, LazyReference)
|
||||
for elem in occ.in_list:
|
||||
self.assertIsInstance(elem, LazyReference)
|
||||
self.assertIsInstance(occ.in_embedded.direct, LazyReference)
|
||||
assert isinstance(elem, LazyReference)
|
||||
assert isinstance(occ.in_embedded.direct, LazyReference)
|
||||
for elem in occ.in_embedded.in_list:
|
||||
self.assertIsInstance(elem, LazyReference)
|
||||
assert isinstance(elem, LazyReference)
|
||||
|
||||
occ = Ocurrence(
|
||||
in_list=[animal1, animal2],
|
||||
|
||||
@@ -10,6 +10,7 @@ from mongoengine import *
|
||||
from mongoengine.connection import get_db
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestLongField(MongoDBTestCase):
|
||||
@@ -24,10 +25,10 @@ class TestLongField(MongoDBTestCase):
|
||||
|
||||
doc = TestLongFieldConsideredAsInt64(some_long=42).save()
|
||||
db = get_db()
|
||||
self.assertIsInstance(
|
||||
assert isinstance(
|
||||
db.test_long_field_considered_as_int64.find()[0]["some_long"], Int64
|
||||
)
|
||||
self.assertIsInstance(doc.some_long, six.integer_types)
|
||||
assert isinstance(doc.some_long, six.integer_types)
|
||||
|
||||
def test_long_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to long fields.
|
||||
@@ -41,11 +42,14 @@ class TestLongField(MongoDBTestCase):
|
||||
doc.validate()
|
||||
|
||||
doc.value = -1
|
||||
self.assertRaises(ValidationError, doc.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
doc.validate()
|
||||
doc.value = 120
|
||||
self.assertRaises(ValidationError, doc.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
doc.validate()
|
||||
doc.value = "ten"
|
||||
self.assertRaises(ValidationError, doc.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
doc.validate()
|
||||
|
||||
def test_long_ne_operator(self):
|
||||
class TestDocument(Document):
|
||||
@@ -56,4 +60,4 @@ class TestLongField(MongoDBTestCase):
|
||||
TestDocument(long_fld=None).save()
|
||||
TestDocument(long_fld=1).save()
|
||||
|
||||
self.assertEqual(1, TestDocument.objects(long_fld__ne=None).count())
|
||||
assert 1 == TestDocument.objects(long_fld__ne=None).count()
|
||||
|
||||
@@ -4,6 +4,7 @@ import datetime
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestMapField(MongoDBTestCase):
|
||||
@@ -19,11 +20,11 @@ class TestMapField(MongoDBTestCase):
|
||||
e.mapping["someint"] = 1
|
||||
e.save()
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
e.mapping["somestring"] = "abc"
|
||||
e.save()
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
|
||||
class NoDeclaredType(Document):
|
||||
mapping = MapField()
|
||||
@@ -51,10 +52,10 @@ class TestMapField(MongoDBTestCase):
|
||||
e.save()
|
||||
|
||||
e2 = Extensible.objects.get(id=e.id)
|
||||
self.assertIsInstance(e2.mapping["somestring"], StringSetting)
|
||||
self.assertIsInstance(e2.mapping["someint"], IntegerSetting)
|
||||
assert isinstance(e2.mapping["somestring"], StringSetting)
|
||||
assert isinstance(e2.mapping["someint"], IntegerSetting)
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
with pytest.raises(ValidationError):
|
||||
e.mapping["someint"] = 123
|
||||
e.save()
|
||||
|
||||
@@ -74,9 +75,9 @@ class TestMapField(MongoDBTestCase):
|
||||
Test.objects.update_one(inc__my_map__DICTIONARY_KEY__number=1)
|
||||
|
||||
test = Test.objects.get()
|
||||
self.assertEqual(test.my_map["DICTIONARY_KEY"].number, 2)
|
||||
assert test.my_map["DICTIONARY_KEY"].number == 2
|
||||
doc = self.db.test.find_one()
|
||||
self.assertEqual(doc["x"]["DICTIONARY_KEY"]["i"], 2)
|
||||
assert doc["x"]["DICTIONARY_KEY"]["i"] == 2
|
||||
|
||||
def test_mapfield_numerical_index(self):
|
||||
"""Ensure that MapField accept numeric strings as indexes."""
|
||||
@@ -116,13 +117,13 @@ class TestMapField(MongoDBTestCase):
|
||||
actions={"friends": Action(operation="drink", object="beer")},
|
||||
).save()
|
||||
|
||||
self.assertEqual(1, Log.objects(visited__friends__exists=True).count())
|
||||
assert 1 == Log.objects(visited__friends__exists=True).count()
|
||||
|
||||
self.assertEqual(
|
||||
1,
|
||||
Log.objects(
|
||||
assert (
|
||||
1
|
||||
== Log.objects(
|
||||
actions__friends__operation="drink", actions__friends__object="beer"
|
||||
).count(),
|
||||
).count()
|
||||
)
|
||||
|
||||
def test_map_field_unicode(self):
|
||||
@@ -139,7 +140,7 @@ class TestMapField(MongoDBTestCase):
|
||||
|
||||
tree.save()
|
||||
|
||||
self.assertEqual(
|
||||
BlogPost.objects.get(id=tree.id).info_dict[u"éééé"].description,
|
||||
u"VALUE: éééé",
|
||||
assert (
|
||||
BlogPost.objects.get(id=tree.id).info_dict[u"éééé"].description
|
||||
== u"VALUE: éééé"
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ from bson import DBRef, SON
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestReferenceField(MongoDBTestCase):
|
||||
@@ -24,19 +25,22 @@ class TestReferenceField(MongoDBTestCase):
|
||||
|
||||
# Make sure ReferenceField only accepts a document class or a string
|
||||
# with a document class name.
|
||||
self.assertRaises(ValidationError, ReferenceField, EmbeddedDocument)
|
||||
with pytest.raises(ValidationError):
|
||||
ReferenceField(EmbeddedDocument)
|
||||
|
||||
user = User(name="Test User")
|
||||
|
||||
# Ensure that the referenced object must have been saved
|
||||
post1 = BlogPost(content="Chips and gravy taste good.")
|
||||
post1.author = user
|
||||
self.assertRaises(ValidationError, post1.save)
|
||||
with pytest.raises(ValidationError):
|
||||
post1.save()
|
||||
|
||||
# Check that an invalid object type cannot be used
|
||||
post2 = BlogPost(content="Chips and chilli taste good.")
|
||||
post1.author = post2
|
||||
self.assertRaises(ValidationError, post1.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post1.validate()
|
||||
|
||||
# Ensure ObjectID's are accepted as references
|
||||
user_object_id = user.pk
|
||||
@@ -52,7 +56,8 @@ class TestReferenceField(MongoDBTestCase):
|
||||
# Make sure referencing a saved document of the *wrong* type fails
|
||||
post2.save()
|
||||
post1.author = post2
|
||||
self.assertRaises(ValidationError, post1.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
post1.validate()
|
||||
|
||||
def test_objectid_reference_fields(self):
|
||||
"""Make sure storing Object ID references works."""
|
||||
@@ -67,7 +72,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
Person(name="Ross", parent=p1.pk).save()
|
||||
|
||||
p = Person.objects.get(name="Ross")
|
||||
self.assertEqual(p.parent, p1)
|
||||
assert p.parent == p1
|
||||
|
||||
def test_dbref_reference_fields(self):
|
||||
"""Make sure storing references as bson.dbref.DBRef works."""
|
||||
@@ -81,13 +86,12 @@ class TestReferenceField(MongoDBTestCase):
|
||||
p1 = Person(name="John").save()
|
||||
Person(name="Ross", parent=p1).save()
|
||||
|
||||
self.assertEqual(
|
||||
Person._get_collection().find_one({"name": "Ross"})["parent"],
|
||||
DBRef("person", p1.pk),
|
||||
assert Person._get_collection().find_one({"name": "Ross"})["parent"] == DBRef(
|
||||
"person", p1.pk
|
||||
)
|
||||
|
||||
p = Person.objects.get(name="Ross")
|
||||
self.assertEqual(p.parent, p1)
|
||||
assert p.parent == p1
|
||||
|
||||
def test_dbref_to_mongo(self):
|
||||
"""Make sure that calling to_mongo on a ReferenceField which
|
||||
@@ -100,9 +104,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
parent = ReferenceField("self", dbref=False)
|
||||
|
||||
p = Person(name="Steve", parent=DBRef("person", "abcdefghijklmnop"))
|
||||
self.assertEqual(
|
||||
p.to_mongo(), SON([("name", u"Steve"), ("parent", "abcdefghijklmnop")])
|
||||
)
|
||||
assert p.to_mongo() == SON([("name", u"Steve"), ("parent", "abcdefghijklmnop")])
|
||||
|
||||
def test_objectid_reference_fields(self):
|
||||
class Person(Document):
|
||||
@@ -116,10 +118,10 @@ class TestReferenceField(MongoDBTestCase):
|
||||
|
||||
col = Person._get_collection()
|
||||
data = col.find_one({"name": "Ross"})
|
||||
self.assertEqual(data["parent"], p1.pk)
|
||||
assert data["parent"] == p1.pk
|
||||
|
||||
p = Person.objects.get(name="Ross")
|
||||
self.assertEqual(p.parent, p1)
|
||||
assert p.parent == p1
|
||||
|
||||
def test_undefined_reference(self):
|
||||
"""Ensure that ReferenceFields may reference undefined Documents.
|
||||
@@ -144,14 +146,14 @@ class TestReferenceField(MongoDBTestCase):
|
||||
me.save()
|
||||
|
||||
obj = Product.objects(company=ten_gen).first()
|
||||
self.assertEqual(obj, mongodb)
|
||||
self.assertEqual(obj.company, ten_gen)
|
||||
assert obj == mongodb
|
||||
assert obj.company == ten_gen
|
||||
|
||||
obj = Product.objects(company=None).first()
|
||||
self.assertEqual(obj, me)
|
||||
assert obj == me
|
||||
|
||||
obj = Product.objects.get(company=None)
|
||||
self.assertEqual(obj, me)
|
||||
assert obj == me
|
||||
|
||||
def test_reference_query_conversion(self):
|
||||
"""Ensure that ReferenceFields can be queried using objects and values
|
||||
@@ -180,10 +182,10 @@ class TestReferenceField(MongoDBTestCase):
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
self.assertEqual(post.id, post1.id)
|
||||
assert post.id == post1.id
|
||||
|
||||
post = BlogPost.objects(author=m2).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
def test_reference_query_conversion_dbref(self):
|
||||
"""Ensure that ReferenceFields can be queried using objects and values
|
||||
@@ -212,7 +214,7 @@ class TestReferenceField(MongoDBTestCase):
|
||||
post2.save()
|
||||
|
||||
post = BlogPost.objects(author=m1).first()
|
||||
self.assertEqual(post.id, post1.id)
|
||||
assert post.id == post1.id
|
||||
|
||||
post = BlogPost.objects(author=m2).first()
|
||||
self.assertEqual(post.id, post2.id)
|
||||
assert post.id == post2.id
|
||||
|
||||
@@ -18,17 +18,17 @@ class TestSequenceField(MongoDBTestCase):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
assert ids == range(1, 11)
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
Person.id.set_next_value(1000)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 1000)
|
||||
assert c["next"] == 1000
|
||||
|
||||
def test_sequence_field_get_next_value(self):
|
||||
class Person(Document):
|
||||
@@ -41,10 +41,10 @@ class TestSequenceField(MongoDBTestCase):
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), 11)
|
||||
assert Person.id.get_next_value() == 11
|
||||
self.db["mongoengine.counters"].drop()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), 1)
|
||||
assert Person.id.get_next_value() == 1
|
||||
|
||||
class Person(Document):
|
||||
id = SequenceField(primary_key=True, value_decorator=str)
|
||||
@@ -56,10 +56,10 @@ class TestSequenceField(MongoDBTestCase):
|
||||
for x in range(10):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), "11")
|
||||
assert Person.id.get_next_value() == "11"
|
||||
self.db["mongoengine.counters"].drop()
|
||||
|
||||
self.assertEqual(Person.id.get_next_value(), "1")
|
||||
assert Person.id.get_next_value() == "1"
|
||||
|
||||
def test_sequence_field_sequence_name(self):
|
||||
class Person(Document):
|
||||
@@ -73,17 +73,17 @@ class TestSequenceField(MongoDBTestCase):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "jelly.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
assert ids == range(1, 11)
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "jelly.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
Person.id.set_next_value(1000)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "jelly.id"})
|
||||
self.assertEqual(c["next"], 1000)
|
||||
assert c["next"] == 1000
|
||||
|
||||
def test_multiple_sequence_fields(self):
|
||||
class Person(Document):
|
||||
@@ -98,24 +98,24 @@ class TestSequenceField(MongoDBTestCase):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
assert ids == range(1, 11)
|
||||
|
||||
counters = [i.counter for i in Person.objects]
|
||||
self.assertEqual(counters, range(1, 11))
|
||||
assert counters == range(1, 11)
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
Person.id.set_next_value(1000)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 1000)
|
||||
assert c["next"] == 1000
|
||||
|
||||
Person.counter.set_next_value(999)
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.counter"})
|
||||
self.assertEqual(c["next"], 999)
|
||||
assert c["next"] == 999
|
||||
|
||||
def test_sequence_fields_reload(self):
|
||||
class Animal(Document):
|
||||
@@ -127,20 +127,20 @@ class TestSequenceField(MongoDBTestCase):
|
||||
|
||||
a = Animal(name="Boi").save()
|
||||
|
||||
self.assertEqual(a.counter, 1)
|
||||
assert a.counter == 1
|
||||
a.reload()
|
||||
self.assertEqual(a.counter, 1)
|
||||
assert a.counter == 1
|
||||
|
||||
a.counter = None
|
||||
self.assertEqual(a.counter, 2)
|
||||
assert a.counter == 2
|
||||
a.save()
|
||||
|
||||
self.assertEqual(a.counter, 2)
|
||||
assert a.counter == 2
|
||||
|
||||
a = Animal.objects.first()
|
||||
self.assertEqual(a.counter, 2)
|
||||
assert a.counter == 2
|
||||
a.reload()
|
||||
self.assertEqual(a.counter, 2)
|
||||
assert a.counter == 2
|
||||
|
||||
def test_multiple_sequence_fields_on_docs(self):
|
||||
class Animal(Document):
|
||||
@@ -160,22 +160,22 @@ class TestSequenceField(MongoDBTestCase):
|
||||
Person(name="Person %s" % x).save()
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "animal.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, range(1, 11))
|
||||
assert ids == range(1, 11)
|
||||
|
||||
id = [i.id for i in Animal.objects]
|
||||
self.assertEqual(id, range(1, 11))
|
||||
assert id == range(1, 11)
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "animal.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
def test_sequence_field_value_decorator(self):
|
||||
class Person(Document):
|
||||
@@ -190,13 +190,13 @@ class TestSequenceField(MongoDBTestCase):
|
||||
p.save()
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
ids = [i.id for i in Person.objects]
|
||||
self.assertEqual(ids, map(str, range(1, 11)))
|
||||
assert ids == map(str, range(1, 11))
|
||||
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "person.id"})
|
||||
self.assertEqual(c["next"], 10)
|
||||
assert c["next"] == 10
|
||||
|
||||
def test_embedded_sequence_field(self):
|
||||
class Comment(EmbeddedDocument):
|
||||
@@ -218,10 +218,10 @@ class TestSequenceField(MongoDBTestCase):
|
||||
],
|
||||
).save()
|
||||
c = self.db["mongoengine.counters"].find_one({"_id": "comment.id"})
|
||||
self.assertEqual(c["next"], 2)
|
||||
assert c["next"] == 2
|
||||
post = Post.objects.first()
|
||||
self.assertEqual(1, post.comments[0].id)
|
||||
self.assertEqual(2, post.comments[1].id)
|
||||
assert 1 == post.comments[0].id
|
||||
assert 2 == post.comments[1].id
|
||||
|
||||
def test_inherited_sequencefield(self):
|
||||
class Base(Document):
|
||||
@@ -241,16 +241,14 @@ class TestSequenceField(MongoDBTestCase):
|
||||
foo = Foo(name="Foo")
|
||||
foo.save()
|
||||
|
||||
self.assertTrue(
|
||||
"base.counter" in self.db["mongoengine.counters"].find().distinct("_id")
|
||||
)
|
||||
self.assertFalse(
|
||||
assert "base.counter" in self.db["mongoengine.counters"].find().distinct("_id")
|
||||
assert not (
|
||||
("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)
|
||||
assert foo.counter != bar.counter
|
||||
assert foo._fields["counter"].owner_document == Base
|
||||
assert bar._fields["counter"].owner_document == Base
|
||||
|
||||
def test_no_inherited_sequencefield(self):
|
||||
class Base(Document):
|
||||
@@ -269,13 +267,12 @@ class TestSequenceField(MongoDBTestCase):
|
||||
foo = Foo(name="Foo")
|
||||
foo.save()
|
||||
|
||||
self.assertFalse(
|
||||
assert not (
|
||||
"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)
|
||||
assert ("foo.counter" and "bar.counter") in self.db[
|
||||
"mongoengine.counters"
|
||||
].find().distinct("_id")
|
||||
assert foo.counter == bar.counter
|
||||
assert foo._fields["counter"].owner_document == Foo
|
||||
assert bar._fields["counter"].owner_document == Bar
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase
|
||||
import pytest
|
||||
|
||||
|
||||
class TestURLField(MongoDBTestCase):
|
||||
@@ -13,7 +14,8 @@ class TestURLField(MongoDBTestCase):
|
||||
|
||||
link = Link()
|
||||
link.url = "google"
|
||||
self.assertRaises(ValidationError, link.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
link.validate()
|
||||
|
||||
link.url = "http://www.google.com:8080"
|
||||
link.validate()
|
||||
@@ -29,11 +31,11 @@ class TestURLField(MongoDBTestCase):
|
||||
|
||||
# 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:
|
||||
with pytest.raises(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'])",
|
||||
assert (
|
||||
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):
|
||||
@@ -48,7 +50,8 @@ class TestURLField(MongoDBTestCase):
|
||||
|
||||
link = Link()
|
||||
link.url = "ws://google.com"
|
||||
self.assertRaises(ValidationError, link.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
link.validate()
|
||||
|
||||
scheme_link = SchemeLink()
|
||||
scheme_link.url = "ws://google.com"
|
||||
|
||||
@@ -4,6 +4,7 @@ import uuid
|
||||
from mongoengine import *
|
||||
|
||||
from tests.utils import MongoDBTestCase, get_as_pymongo
|
||||
import pytest
|
||||
|
||||
|
||||
class Person(Document):
|
||||
@@ -14,9 +15,7 @@ class TestUUIDField(MongoDBTestCase):
|
||||
def test_storage(self):
|
||||
uid = uuid.uuid4()
|
||||
person = Person(api_key=uid).save()
|
||||
self.assertEqual(
|
||||
get_as_pymongo(person), {"_id": person.id, "api_key": str(uid)}
|
||||
)
|
||||
assert get_as_pymongo(person) == {"_id": person.id, "api_key": str(uid)}
|
||||
|
||||
def test_field_string(self):
|
||||
"""Test UUID fields storing as String
|
||||
@@ -25,8 +24,8 @@ class TestUUIDField(MongoDBTestCase):
|
||||
|
||||
uu = uuid.uuid4()
|
||||
Person(api_key=uu).save()
|
||||
self.assertEqual(1, Person.objects(api_key=uu).count())
|
||||
self.assertEqual(uu, Person.objects.first().api_key)
|
||||
assert 1 == Person.objects(api_key=uu).count()
|
||||
assert uu == Person.objects.first().api_key
|
||||
|
||||
person = Person()
|
||||
valid = (uuid.uuid4(), uuid.uuid1())
|
||||
@@ -40,7 +39,8 @@ class TestUUIDField(MongoDBTestCase):
|
||||
)
|
||||
for api_key in invalid:
|
||||
person.api_key = api_key
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
def test_field_binary(self):
|
||||
"""Test UUID fields storing as Binary object."""
|
||||
@@ -48,8 +48,8 @@ class TestUUIDField(MongoDBTestCase):
|
||||
|
||||
uu = uuid.uuid4()
|
||||
Person(api_key=uu).save()
|
||||
self.assertEqual(1, Person.objects(api_key=uu).count())
|
||||
self.assertEqual(uu, Person.objects.first().api_key)
|
||||
assert 1 == Person.objects(api_key=uu).count()
|
||||
assert uu == Person.objects.first().api_key
|
||||
|
||||
person = Person()
|
||||
valid = (uuid.uuid4(), uuid.uuid1())
|
||||
@@ -63,4 +63,5 @@ class TestUUIDField(MongoDBTestCase):
|
||||
)
|
||||
for api_key in invalid:
|
||||
person.api_key = api_key
|
||||
self.assertRaises(ValidationError, person.validate)
|
||||
with pytest.raises(ValidationError):
|
||||
person.validate()
|
||||
|
||||
Reference in New Issue
Block a user