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 pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
import pytest
__all__ = ("TestDynamicDocument",)

View File

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

View File

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

View File

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

View File

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

View File

@ -2,12 +2,11 @@
import uuid
from bson import Binary
from nose.plugins.skip import SkipTest
import pytest
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"

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
from bson import DBRef, SON
import pytest
from mongoengine import *
from tests.utils import MongoDBTestCase
import pytest
class TestReferenceField(MongoDBTestCase):
@ -59,21 +58,6 @@ class TestReferenceField(MongoDBTestCase):
with pytest.raises(ValidationError):
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):
"""Make sure storing references as bson.dbref.DBRef works."""

View File

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

View File

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

View File

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

View File

@ -1,8 +1,9 @@
import unittest
import pytest
from mongoengine import *
from mongoengine.queryset import QueryFieldList
import pytest
class TestQueryFieldList(unittest.TestCase):
@ -221,7 +222,7 @@ class TestOnlyExcludeAll(unittest.TestCase):
assert obj.comments == []
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()
assert obj.content == "Had a good coffee today..."

View File

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

View File

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

View File

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

View File

@ -3,10 +3,10 @@ import datetime
from bson.tz_util import utc
from nose.plugins.skip import SkipTest
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:
import unittest2 as unittest
@ -29,7 +29,6 @@ from mongoengine.connection import (
get_connection,
get_db,
)
import pytest
def get_tz_awareness(connection):

View File

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

View File

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

View File

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

View File

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