improve tests health (flake8 warnings)

This commit is contained in:
Bastien Gérard 2019-09-01 15:03:29 +03:00
parent c61c6a8525
commit bc0c55e49a
34 changed files with 97 additions and 111 deletions

View File

@ -1,8 +1,9 @@
import unittest import unittest
import pytest
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
__all__ = ("TestDynamicDocument",) __all__ = ("TestDynamicDocument",)

View File

@ -5,11 +5,11 @@ from datetime import datetime
from nose.plugins.skip import SkipTest from nose.plugins.skip import SkipTest
from pymongo.collation import Collation from pymongo.collation import Collation
from pymongo.errors import OperationFailure from pymongo.errors import OperationFailure
import pytest
from six import iteritems from six import iteritems
from mongoengine import * from mongoengine import *
from mongoengine.connection import get_db from mongoengine.connection import get_db
import pytest
class TestIndexes(unittest.TestCase): class TestIndexes(unittest.TestCase):

View File

@ -2,6 +2,7 @@
import unittest import unittest
import warnings import warnings
import pytest
from six import iteritems from six import iteritems
from mongoengine import ( from mongoengine import (
@ -17,7 +18,6 @@ from mongoengine import (
from mongoengine.pymongo_support import list_collection_names from mongoengine.pymongo_support import list_collection_names
from tests.fixtures import Base from tests.fixtures import Base
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestInheritance(MongoDBTestCase): class TestInheritance(MongoDBTestCase):
@ -335,9 +335,7 @@ class TestInheritance(MongoDBTestCase):
name = StringField() name = StringField()
# can't inherit because Animal didn't explicitly allow inheritance # can't inherit because Animal didn't explicitly allow inheritance
with pytest.raises( with pytest.raises(ValueError, match="Document Animal may not be subclassed"):
ValueError, match="Document Animal may not be subclassed"
) as exc_info:
class Dog(Animal): class Dog(Animal):
pass pass
@ -475,7 +473,7 @@ class TestInheritance(MongoDBTestCase):
meta = {"abstract": True, "allow_inheritance": False} meta = {"abstract": True, "allow_inheritance": False}
city = City(continent="asia") city = City(continent="asia")
assert None == city.pk assert city.pk is None
# TODO: expected error? Shouldn't we create a new error type? # TODO: expected error? Shouldn't we create a new error type?
with pytest.raises(KeyError): with pytest.raises(KeyError):
setattr(city, "pk", 1) setattr(city, "pk", 1)

View File

@ -9,6 +9,7 @@ from datetime import datetime
import bson import bson
from bson import DBRef, ObjectId from bson import DBRef, ObjectId
from pymongo.errors import DuplicateKeyError from pymongo.errors import DuplicateKeyError
import pytest
from six import iteritems from six import iteritems
from mongoengine import * from mongoengine import *
@ -36,7 +37,6 @@ from tests.fixtures import (
PickleTest, PickleTest,
) )
from tests.utils import MongoDBTestCase, get_as_pymongo from tests.utils import MongoDBTestCase, get_as_pymongo
import pytest
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), "../fields/mongoengine.png") TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), "../fields/mongoengine.png")
@ -96,7 +96,7 @@ class TestInstance(MongoDBTestCase):
assert Log.objects.count() == 10 assert Log.objects.count() == 10
options = Log.objects._collection.options() options = Log.objects._collection.options()
assert options["capped"] == True assert options["capped"] is True
assert options["max"] == 10 assert options["max"] == 10
assert options["size"] == 4096 assert options["size"] == 4096
@ -122,7 +122,7 @@ class TestInstance(MongoDBTestCase):
Log().save() Log().save()
options = Log.objects._collection.options() options = Log.objects._collection.options()
assert options["capped"] == True assert options["capped"] is True
assert options["max"] == 10 assert options["max"] == 10
assert options["size"] == 10 * 2 ** 20 assert options["size"] == 10 * 2 ** 20
@ -150,7 +150,7 @@ class TestInstance(MongoDBTestCase):
Log().save() Log().save()
options = Log.objects._collection.options() options = Log.objects._collection.options()
assert options["capped"] == True assert options["capped"] is True
assert options["size"] >= 10000 assert options["size"] >= 10000
# Check that the document with odd max_size value can be recreated # Check that the document with odd max_size value can be recreated
@ -350,7 +350,7 @@ class TestInstance(MongoDBTestCase):
name = StringField() name = StringField()
meta = {"allow_inheritance": True} meta = {"allow_inheritance": True}
with pytest.raises(ValueError, match="Cannot override primary key field") as e: with pytest.raises(ValueError, match="Cannot override primary key field"):
class EmailUser(User): class EmailUser(User):
email = StringField(primary_key=True) email = StringField(primary_key=True)
@ -620,7 +620,7 @@ class TestInstance(MongoDBTestCase):
f.reload() f.reload()
def test_reload_of_non_strict_with_special_field_name(self): def test_reload_of_non_strict_with_special_field_name(self):
"""Ensures reloading works for documents with meta strict == False.""" """Ensures reloading works for documents with meta strict is False."""
class Post(Document): class Post(Document):
meta = {"strict": False} meta = {"strict": False}
@ -832,13 +832,13 @@ class TestInstance(MongoDBTestCase):
t = TestDocument(status="published") t = TestDocument(status="published")
t.save(clean=False) t.save(clean=False)
assert t.status == "published" assert t.status == "published"
assert t.cleaned == False assert t.cleaned is False
t = TestDocument(status="published") t = TestDocument(status="published")
assert t.cleaned == False assert t.cleaned is False
t.save(clean=True) t.save(clean=True)
assert t.status == "published" assert t.status == "published"
assert t.cleaned == True assert t.cleaned is True
raw_doc = get_as_pymongo(t) raw_doc = get_as_pymongo(t)
# Make sure clean changes makes it to the db # Make sure clean changes makes it to the db
assert raw_doc == {"status": "published", "cleaned": True, "_id": t.id} assert raw_doc == {"status": "published", "cleaned": True, "_id": t.id}
@ -1600,7 +1600,7 @@ class TestInstance(MongoDBTestCase):
person = self.Person.objects.get() person = self.Person.objects.get()
assert person.name == "User" assert person.name == "User"
assert person.age == 21 assert person.age == 21
assert person.active == False assert person.active is False
def test__get_changed_fields_same_ids_reference_field_does_not_enters_infinite_loop_embedded_doc( def test__get_changed_fields_same_ids_reference_field_does_not_enters_infinite_loop_embedded_doc(
self, self,
@ -2521,9 +2521,9 @@ class TestInstance(MongoDBTestCase):
assert all_user_dic.get(u1, False) == "OK" assert all_user_dic.get(u1, False) == "OK"
assert all_user_dic.get(u2, False) == "OK" assert all_user_dic.get(u2, False) == "OK"
assert all_user_dic.get(u3, False) == "OK" assert all_user_dic.get(u3, False) == "OK"
assert all_user_dic.get(u4, False) == False # New object assert all_user_dic.get(u4, False) is False # New object
assert all_user_dic.get(b1, False) == False # Other object assert all_user_dic.get(b1, False) is False # Other object
assert all_user_dic.get(b2, False) == False # Other object assert all_user_dic.get(b2, False) is False # Other object
# Make sure docs are properly identified in a set (__hash__ is used # Make sure docs are properly identified in a set (__hash__ is used
# for hashing the docs). # for hashing the docs).
@ -3216,7 +3216,7 @@ class TestInstance(MongoDBTestCase):
def test_mixed_creation(self): def test_mixed_creation(self):
"""Document cannot be instantiated using mixed arguments.""" """Document cannot be instantiated using mixed arguments."""
with pytest.raises(TypeError) as exc_info: with pytest.raises(TypeError) as exc_info:
person = self.Person("Test User", age=42) self.Person("Test User", age=42)
expected_msg = ( expected_msg = (
"Instantiating a document with positional arguments is not " "Instantiating a document with positional arguments is not "
@ -3227,7 +3227,7 @@ class TestInstance(MongoDBTestCase):
def test_positional_creation_embedded(self): def test_positional_creation_embedded(self):
"""Embedded document cannot be created using positional arguments.""" """Embedded document cannot be created using positional arguments."""
with pytest.raises(TypeError) as exc_info: with pytest.raises(TypeError) as exc_info:
job = self.Job("Test Job", 4) self.Job("Test Job", 4)
expected_msg = ( expected_msg = (
"Instantiating a document with positional arguments is not " "Instantiating a document with positional arguments is not "
@ -3238,7 +3238,7 @@ class TestInstance(MongoDBTestCase):
def test_mixed_creation_embedded(self): def test_mixed_creation_embedded(self):
"""Embedded document cannot be created using mixed arguments.""" """Embedded document cannot be created using mixed arguments."""
with pytest.raises(TypeError) as exc_info: with pytest.raises(TypeError) as exc_info:
job = self.Job("Test Job", years=4) self.Job("Test Job", years=4)
expected_msg = ( expected_msg = (
"Instantiating a document with positional arguments is not " "Instantiating a document with positional arguments is not "
@ -3432,7 +3432,7 @@ class TestInstance(MongoDBTestCase):
meta = {"shard_key": ("id", "name")} meta = {"shard_key": ("id", "name")}
p = Person.from_json('{"name": "name", "age": 27}', created=True) p = Person.from_json('{"name": "name", "age": 27}', created=True)
assert p._created == True assert p._created is True
p.name = "new name" p.name = "new name"
p.id = "12345" p.id = "12345"
assert p.name == "new name" assert p.name == "new name"
@ -3450,7 +3450,7 @@ class TestInstance(MongoDBTestCase):
meta = {"shard_key": ("id", "name")} meta = {"shard_key": ("id", "name")}
p = Person._from_son({"name": "name", "age": 27}, created=True) p = Person._from_son({"name": "name", "age": 27}, created=True)
assert p._created == True assert p._created is True
p.name = "new name" p.name = "new name"
p.id = "12345" p.id = "12345"
assert p.name == "new name" assert p.name == "new name"
@ -3463,7 +3463,7 @@ class TestInstance(MongoDBTestCase):
Person.objects.delete() Person.objects.delete()
p = Person.from_json('{"name": "name"}', created=False) p = Person.from_json('{"name": "name"}', created=False)
assert p._created == False assert p._created is False
assert p.id is None assert p.id is None
# Make sure the document is subsequently persisted correctly. # Make sure the document is subsequently persisted correctly.
@ -3483,7 +3483,7 @@ class TestInstance(MongoDBTestCase):
p = Person.from_json( p = Person.from_json(
'{"_id": "5b85a8b04ec5dc2da388296e", "name": "name"}', created=False '{"_id": "5b85a8b04ec5dc2da388296e", "name": "name"}', created=False
) )
assert p._created == False assert p._created is False
assert p._changed_fields == [] assert p._changed_fields == []
assert p.name == "name" assert p.name == "name"
assert p.id == ObjectId("5b85a8b04ec5dc2da388296e") assert p.id == ObjectId("5b85a8b04ec5dc2da388296e")

View File

@ -2,9 +2,10 @@
import unittest import unittest
from datetime import datetime from datetime import datetime
import pytest
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestValidatorError(MongoDBTestCase): class TestValidatorError(MongoDBTestCase):

View File

@ -2,12 +2,11 @@
import uuid import uuid
from bson import Binary from bson import Binary
from nose.plugins.skip import SkipTest import pytest
import six import six
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
BIN_VALUE = six.b( 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" "\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"

View File

@ -1,9 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from mongoengine import *
from tests.utils import MongoDBTestCase, get_as_pymongo
import pytest import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase, get_as_pymongo
class TestBooleanField(MongoDBTestCase): class TestBooleanField(MongoDBTestCase):
def test_storage(self): def test_storage(self):

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from decimal import Decimal from decimal import Decimal
from mongoengine import *
from tests.utils import MongoDBTestCase
import pytest import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
class TestCachedReferenceField(MongoDBTestCase): class TestCachedReferenceField(MongoDBTestCase):
def test_get_and_save(self): def test_get_and_save(self):

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import datetime import datetime
import pytest
import six import six
try: try:
@ -8,9 +10,7 @@ except ImportError:
dateutil = None dateutil = None
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestDateField(MongoDBTestCase): class TestDateField(MongoDBTestCase):

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import datetime as dt import datetime as dt
import pytest
import six import six
try: try:
@ -11,7 +13,6 @@ from mongoengine import *
from mongoengine import connection from mongoengine import connection
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestDateTimeField(MongoDBTestCase): class TestDateTimeField(MongoDBTestCase):

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from decimal import Decimal from decimal import Decimal
from mongoengine import *
from tests.utils import MongoDBTestCase
import pytest import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
class TestDecimalField(MongoDBTestCase): class TestDecimalField(MongoDBTestCase):
def test_validation(self): def test_validation(self):

View File

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest
from mongoengine import * from mongoengine import *
from mongoengine.base import BaseDict from mongoengine.base import BaseDict
from tests.utils import MongoDBTestCase, get_as_pymongo from tests.utils import MongoDBTestCase, get_as_pymongo
import pytest
class TestDictField(MongoDBTestCase): class TestDictField(MongoDBTestCase):
@ -290,7 +291,7 @@ class TestDictField(MongoDBTestCase):
e.save() e.save()
e.update(set__mapping={"ints": [3, 4]}) e.update(set__mapping={"ints": [3, 4]})
e.reload() e.reload()
assert BaseDict == type(e.mapping) assert isinstance(e.mapping, BaseDict)
assert {"ints": [3, 4]} == e.mapping assert {"ints": [3, 4]} == e.mapping
# try creating an invalid mapping # try creating an invalid mapping

View File

@ -2,11 +2,11 @@
import sys import sys
from unittest import SkipTest from unittest import SkipTest
from mongoengine import *
from tests.utils import MongoDBTestCase
import pytest import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
class TestEmailField(MongoDBTestCase): class TestEmailField(MongoDBTestCase):
def test_generic_behavior(self): def test_generic_behavior(self):

View File

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest
from mongoengine import ( from mongoengine import (
Document, Document,
EmbeddedDocument, EmbeddedDocument,
@ -13,7 +15,6 @@ from mongoengine import (
) )
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestEmbeddedDocumentField(MongoDBTestCase): class TestEmbeddedDocumentField(MongoDBTestCase):

View File

@ -4,6 +4,7 @@ import unittest
from bson import DBRef, ObjectId, SON from bson import DBRef, ObjectId, SON
from nose.plugins.skip import SkipTest from nose.plugins.skip import SkipTest
import pytest
from mongoengine import ( from mongoengine import (
BooleanField, BooleanField,
@ -39,7 +40,6 @@ from mongoengine.base import BaseField, EmbeddedDocumentList, _document_registry
from mongoengine.errors import DeprecatedError from mongoengine.errors import DeprecatedError
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestField(MongoDBTestCase): class TestField(MongoDBTestCase):
@ -1838,7 +1838,7 @@ class TestField(MongoDBTestCase):
user = User.objects(bookmarks__all=[post_1]).first() user = User.objects(bookmarks__all=[post_1]).first()
assert user != None assert user is not None
assert user.bookmarks[0] == post_1 assert user.bookmarks[0] == post_1
def test_generic_reference_filter_by_dbref(self): def test_generic_reference_filter_by_dbref(self):

View File

@ -137,7 +137,6 @@ class TestFileField(MongoDBTestCase):
text = six.b("Hello, World!") text = six.b("Hello, World!")
more_text = six.b("Foo Bar") more_text = six.b("Foo Bar")
content_type = "text/plain"
streamfile = StreamFile() streamfile = StreamFile()
streamfile.save() streamfile.save()
@ -205,7 +204,7 @@ class TestFileField(MongoDBTestCase):
doc_b = GridDocument.objects.with_id(doc_a.id) doc_b = GridDocument.objects.with_id(doc_a.id)
doc_b.the_file.replace(f, filename="doc_b") doc_b.the_file.replace(f, filename="doc_b")
doc_b.save() doc_b.save()
assert doc_b.the_file.grid_id != None assert doc_b.the_file.grid_id is not None
# Test it matches # Test it matches
doc_c = GridDocument.objects.with_id(doc_b.id) doc_c = GridDocument.objects.with_id(doc_b.id)

View File

@ -1,10 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest
import six import six
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestFloatField(MongoDBTestCase): class TestFloatField(MongoDBTestCase):

View File

@ -1,8 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestIntField(MongoDBTestCase): class TestIntField(MongoDBTestCase):

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from bson import DBRef, ObjectId from bson import DBRef, ObjectId
import pytest
from mongoengine import * from mongoengine import *
from mongoengine.base import LazyReference from mongoengine.base import LazyReference
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestLazyReferenceField(MongoDBTestCase): class TestLazyReferenceField(MongoDBTestCase):

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest
import six import six
try: try:
@ -10,7 +11,6 @@ from mongoengine import *
from mongoengine.connection import get_db from mongoengine.connection import get_db
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestLongField(MongoDBTestCase): class TestLongField(MongoDBTestCase):

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import datetime import datetime
from mongoengine import *
from tests.utils import MongoDBTestCase
import pytest import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
class TestMapField(MongoDBTestCase): class TestMapField(MongoDBTestCase):
def test_mapfield(self): def test_mapfield(self):

View File

@ -1,10 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from bson import DBRef, SON from bson import DBRef, SON
import pytest
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestReferenceField(MongoDBTestCase): class TestReferenceField(MongoDBTestCase):
@ -59,21 +58,6 @@ class TestReferenceField(MongoDBTestCase):
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
post1.validate() post1.validate()
def test_objectid_reference_fields(self):
"""Make sure storing Object ID references works."""
class Person(Document):
name = StringField()
parent = ReferenceField("self")
Person.drop_collection()
p1 = Person(name="John").save()
Person(name="Ross", parent=p1.pk).save()
p = Person.objects.get(name="Ross")
assert p.parent == p1
def test_dbref_reference_fields(self): def test_dbref_reference_fields(self):
"""Make sure storing references as bson.dbref.DBRef works.""" """Make sure storing references as bson.dbref.DBRef works."""

View File

@ -1,8 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytest
from mongoengine import * from mongoengine import *
from tests.utils import MongoDBTestCase from tests.utils import MongoDBTestCase
import pytest
class TestURLField(MongoDBTestCase): class TestURLField(MongoDBTestCase):

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import uuid import uuid
from mongoengine import *
from tests.utils import MongoDBTestCase, get_as_pymongo
import pytest import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase, get_as_pymongo
class Person(Document): class Person(Document):
api_key = UUIDField(binary=False) api_key = UUIDField(binary=False)

View File

@ -42,11 +42,11 @@ class PickleSignalsTest(Document):
@classmethod @classmethod
def post_save(self, sender, document, created, **kwargs): def post_save(self, sender, document, created, **kwargs):
pickled = pickle.dumps(document) pickle.dumps(document)
@classmethod @classmethod
def post_delete(self, sender, document, **kwargs): def post_delete(self, sender, document, **kwargs):
pickled = pickle.dumps(document) pickle.dumps(document)
signals.post_save.connect(PickleSignalsTest.post_save, sender=PickleSignalsTest) signals.post_save.connect(PickleSignalsTest.post_save, sender=PickleSignalsTest)

View File

@ -1,8 +1,9 @@
import unittest import unittest
import pytest
from mongoengine import * from mongoengine import *
from mongoengine.queryset import QueryFieldList from mongoengine.queryset import QueryFieldList
import pytest
class TestQueryFieldList(unittest.TestCase): class TestQueryFieldList(unittest.TestCase):
@ -221,7 +222,7 @@ class TestOnlyExcludeAll(unittest.TestCase):
assert obj.comments == [] assert obj.comments == []
obj = BlogPost.objects.only("various.test_dynamic.some").get() obj = BlogPost.objects.only("various.test_dynamic.some").get()
assert obj.various["test_dynamic"].some == True assert obj.various["test_dynamic"].some is True
obj = BlogPost.objects.only("content", "comments.title").get() obj = BlogPost.objects.only("content", "comments.title").get()
assert obj.content == "Had a good coffee today..." assert obj.content == "Had a good coffee today..."

View File

@ -9,6 +9,7 @@ from bson import DBRef, ObjectId
import pymongo import pymongo
from pymongo.read_preferences import ReadPreference from pymongo.read_preferences import ReadPreference
from pymongo.results import UpdateResult from pymongo.results import UpdateResult
import pytest
import six import six
from six import iteritems from six import iteritems
@ -24,7 +25,6 @@ from mongoengine.queryset import (
QuerySetManager, QuerySetManager,
queryset_manager, queryset_manager,
) )
import pytest
class db_ops_tracker(query_counter): class db_ops_tracker(query_counter):
@ -1712,11 +1712,11 @@ class TestQueryset(unittest.TestCase):
post = BlogPost(content="Watching TV", category=lameness) post = BlogPost(content="Watching TV", category=lameness)
post.save() post.save()
assert 1 == BlogPost.objects.count() assert BlogPost.objects.count() == 1
assert "Lameness" == BlogPost.objects.first().category.name assert BlogPost.objects.first().category.name == "Lameness"
Category.objects.delete() Category.objects.delete()
assert 1 == BlogPost.objects.count() assert BlogPost.objects.count() == 1
assert None == BlogPost.objects.first().category assert BlogPost.objects.first().category is None
def test_reverse_delete_rule_nullify_on_abstract_document(self): def test_reverse_delete_rule_nullify_on_abstract_document(self):
"""Ensure nullification of references to deleted documents when """Ensure nullification of references to deleted documents when
@ -1739,11 +1739,11 @@ class TestQueryset(unittest.TestCase):
BlogPost(content="Watching TV", author=me).save() BlogPost(content="Watching TV", author=me).save()
assert 1 == BlogPost.objects.count() assert BlogPost.objects.count() == 1
assert me == BlogPost.objects.first().author assert BlogPost.objects.first().author == me
self.Person.objects(name="Test User").delete() self.Person.objects(name="Test User").delete()
assert 1 == BlogPost.objects.count() assert BlogPost.objects.count() == 1
assert None == BlogPost.objects.first().author assert BlogPost.objects.first().author is None
def test_reverse_delete_rule_deny(self): def test_reverse_delete_rule_deny(self):
"""Ensure deletion gets denied on documents that still have references """Ensure deletion gets denied on documents that still have references
@ -1896,7 +1896,7 @@ class TestQueryset(unittest.TestCase):
""" """
p1 = self.Person(name="User Z", age=20).save() p1 = self.Person(name="User Z", age=20).save()
del_result = p1.delete(w=0) del_result = p1.delete(w=0)
assert None == del_result assert del_result is None
def test_reference_field_find(self): def test_reference_field_find(self):
"""Ensure cascading deletion of referring documents from the database. """Ensure cascading deletion of referring documents from the database.
@ -2047,7 +2047,7 @@ class TestQueryset(unittest.TestCase):
post = BlogPost(title="garbage").save() post = BlogPost(title="garbage").save()
assert post.title != None assert post.title is not None
BlogPost.objects.update_one(unset__title=1) BlogPost.objects.update_one(unset__title=1)
post.reload() post.reload()
assert post.title is None assert post.title is None
@ -5006,7 +5006,7 @@ class TestQueryset(unittest.TestCase):
# PyPy evaluates __len__ when iterating with list comprehensions while CPython does not. # PyPy evaluates __len__ when iterating with list comprehensions while CPython does not.
# This may be a bug in PyPy (PyPy/#1802) but it does not affect # This may be a bug in PyPy (PyPy/#1802) but it does not affect
# the behavior of MongoEngine. # the behavior of MongoEngine.
assert None == people._len assert people._len is None
assert q == 1 assert q == 1
list(people) list(people)
@ -5053,7 +5053,7 @@ class TestQueryset(unittest.TestCase):
Person(name="a").save() Person(name="a").save()
qs = Person.objects() qs = Person.objects()
_ = list(qs) _ = list(qs)
with pytest.raises(OperationError, match="QuerySet already cached") as ctx_err: with pytest.raises(OperationError, match="QuerySet already cached"):
qs.no_cache() qs.no_cache()
def test_no_cached_queryset_no_cache_back_to_cache(self): def test_no_cached_queryset_no_cache_back_to_cache(self):

View File

@ -1,10 +1,10 @@
import unittest import unittest
from bson.son import SON from bson.son import SON
import pytest
from mongoengine import * from mongoengine import *
from mongoengine.queryset import Q, transform from mongoengine.queryset import Q, transform
import pytest
class TestTransform(unittest.TestCase): class TestTransform(unittest.TestCase):

View File

@ -3,11 +3,11 @@ import re
import unittest import unittest
from bson import ObjectId from bson import ObjectId
import pytest
from mongoengine import * from mongoengine import *
from mongoengine.errors import InvalidQueryError from mongoengine.errors import InvalidQueryError
from mongoengine.queryset import Q from mongoengine.queryset import Q
import pytest
class TestQ(unittest.TestCase): class TestQ(unittest.TestCase):

View File

@ -3,10 +3,10 @@ import datetime
from bson.tz_util import utc from bson.tz_util import utc
from nose.plugins.skip import SkipTest from nose.plugins.skip import SkipTest
import pymongo import pymongo
from pymongo import MongoClient
from pymongo import ReadPreference
from pymongo.errors import InvalidName, OperationFailure
from pymongo import MongoClient, ReadPreference
from pymongo.errors import InvalidName, OperationFailure
import pytest
try: try:
import unittest2 as unittest import unittest2 as unittest
@ -29,7 +29,6 @@ from mongoengine.connection import (
get_connection, get_connection,
get_db, get_db,
) )
import pytest
def get_tz_awareness(connection): def get_tz_awareness(connection):

View File

@ -1,5 +1,7 @@
import unittest import unittest
import pytest
from mongoengine import * from mongoengine import *
from mongoengine.connection import get_db from mongoengine.connection import get_db
from mongoengine.context_managers import ( from mongoengine.context_managers import (
@ -10,7 +12,6 @@ from mongoengine.context_managers import (
switch_db, switch_db,
) )
from mongoengine.pymongo_support import count_documents from mongoengine.pymongo_support import count_documents
import pytest
class ContextManagersTest(unittest.TestCase): class ContextManagersTest(unittest.TestCase):
@ -214,7 +215,6 @@ class ContextManagersTest(unittest.TestCase):
raise TypeError() raise TypeError()
def test_query_counter_does_not_swallow_exception(self): def test_query_counter_does_not_swallow_exception(self):
with pytest.raises(TypeError): with pytest.raises(TypeError):
with query_counter() as q: with query_counter() as q:
raise TypeError() raise TypeError()

View File

@ -1,7 +1,7 @@
import unittest import unittest
from six import iterkeys
import pytest import pytest
from six import iterkeys
from mongoengine import Document from mongoengine import Document
from mongoengine.base.datastructures import BaseDict, BaseList, StrictDict from mongoengine.base.datastructures import BaseDict, BaseList, StrictDict

View File

@ -1,7 +1,6 @@
import unittest import unittest
from pymongo import MongoClient from pymongo import MongoClient, ReadPreference
from pymongo import ReadPreference
import mongoengine import mongoengine
from mongoengine.connection import ConnectionFailure from mongoengine.connection import ConnectionFailure
@ -25,14 +24,13 @@ class ConnectionTest(unittest.TestCase):
def test_replicaset_uri_passes_read_preference(self): def test_replicaset_uri_passes_read_preference(self):
"""Requires a replica set called "rs" on port 27017 """Requires a replica set called "rs" on port 27017
""" """
try: try:
conn = mongoengine.connect( conn = mongoengine.connect(
db="mongoenginetest", db="mongoenginetest",
host="mongodb://localhost/mongoenginetest?replicaSet=rs", host="mongodb://localhost/mongoenginetest?replicaSet=rs",
read_preference=READ_PREF, read_preference=READ_PREF,
) )
except ConnectionFailure as e: except ConnectionFailure:
return return
if not isinstance(conn, CONN_CLASS): if not isinstance(conn, CONN_CLASS):

View File

@ -1,9 +1,10 @@
import re import re
import unittest import unittest
from mongoengine.base.utils import LazyRegexCompiler
import pytest import pytest
from mongoengine.base.utils import LazyRegexCompiler
signal_output = [] signal_output = []