fix remaining assertRaises

This commit is contained in:
Bastien Gérard 2019-08-31 22:40:54 +03:00
parent ac25f4b98b
commit 3e764d068c
10 changed files with 76 additions and 80 deletions

View File

@ -595,12 +595,12 @@ class TestIndexes(unittest.TestCase):
Blog.drop_collection() Blog.drop_collection()
with pytest.raises(OperationFailure) as ctx_err: with pytest.raises(OperationFailure) as exc_info:
Blog(id="garbage").save() Blog(id="garbage").save()
# One of the errors below should happen. Which one depends on the # One of the errors below should happen. Which one depends on the
# PyMongo version and dict order. # PyMongo version and dict order.
err_msg = str(ctx_err.exception) err_msg = str(exc_info.value)
assert any( assert any(
[ [
"The field 'unique' is not valid for an _id index specification" "The field 'unique' is not valid for an _id index specification"

View File

@ -335,13 +335,13 @@ 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(ValueError) as cm: with pytest.raises(
ValueError, match="Document Animal may not be subclassed"
) as exc_info:
class Dog(Animal): class Dog(Animal):
pass pass
assert "Document Animal may not be subclassed" in str(cm.exception)
# Check that _cls etc aren't present on simple documents # Check that _cls etc aren't present on simple documents
dog = Animal(name="dog").save() dog = Animal(name="dog").save()
assert dog.to_mongo().keys() == ["_id", "name"] assert dog.to_mongo().keys() == ["_id", "name"]
@ -358,13 +358,13 @@ class TestInheritance(MongoDBTestCase):
name = StringField() name = StringField()
meta = {"allow_inheritance": True} meta = {"allow_inheritance": True}
with pytest.raises(ValueError) as cm: with pytest.raises(ValueError) as exc_info:
class Mammal(Animal): class Mammal(Animal):
meta = {"allow_inheritance": False} meta = {"allow_inheritance": False}
assert ( assert (
str(cm.exception) str(exc_info.value)
== 'Only direct subclasses of Document may set "allow_inheritance" to False' == 'Only direct subclasses of Document may set "allow_inheritance" to False'
) )

View File

@ -350,14 +350,11 @@ class TestInstance(MongoDBTestCase):
name = StringField() name = StringField()
meta = {"allow_inheritance": True} meta = {"allow_inheritance": True}
with pytest.raises(ValueError) as e: with pytest.raises(ValueError, match="Cannot override primary key field") as e:
class EmailUser(User): class EmailUser(User):
email = StringField(primary_key=True) email = StringField(primary_key=True)
exc = e.exception
assert str(exc) == "Cannot override primary key field"
def test_custom_id_field_is_required(self): def test_custom_id_field_is_required(self):
"""Ensure the custom primary key field is required.""" """Ensure the custom primary key field is required."""
@ -365,10 +362,9 @@ class TestInstance(MongoDBTestCase):
username = StringField(primary_key=True) username = StringField(primary_key=True)
name = StringField() name = StringField()
with pytest.raises(ValidationError) as e: with pytest.raises(ValidationError) as exc_info:
User(name="test").save() User(name="test").save()
exc = e.exception assert "Field is required: ['username']" in str(exc_info.value)
assert "Field is required: ['username']" in str(exc)
def test_document_not_registered(self): def test_document_not_registered(self):
class Place(Document): class Place(Document):
@ -870,12 +866,12 @@ class TestInstance(MongoDBTestCase):
t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25, z=15)) t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25, z=15))
with pytest.raises(ValidationError) as cm: with pytest.raises(ValidationError) as exc_info:
t.save() t.save()
expected_msg = "Value of z != x + y" expected_msg = "Value of z != x + y"
assert expected_msg in cm.exception.message assert expected_msg in str(exc_info.value)
assert cm.exception.to_dict() == {"doc": {"__all__": expected_msg}} assert exc_info.value.to_dict() == {"doc": {"__all__": expected_msg}}
t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25)).save() t = TestDocument(doc=TestEmbeddedDocument(x=10, y=25)).save()
assert t.doc.z == 35 assert t.doc.z == 35
@ -3208,43 +3204,47 @@ class TestInstance(MongoDBTestCase):
def test_positional_creation(self): def test_positional_creation(self):
"""Document cannot be instantiated using positional arguments.""" """Document cannot be instantiated using positional arguments."""
with pytest.raises(TypeError) as e: with pytest.raises(TypeError) as exc_info:
person = self.Person("Test User", 42) person = self.Person("Test User", 42)
expected_msg = ( expected_msg = (
"Instantiating a document with positional arguments is not " "Instantiating a document with positional arguments is not "
"supported. Please use `field_name=value` keyword arguments." "supported. Please use `field_name=value` keyword arguments."
) )
assert str(e.exception) == expected_msg assert str(exc_info.value) == expected_msg
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 e: with pytest.raises(TypeError) as exc_info:
person = self.Person("Test User", age=42) person = 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 "
"supported. Please use `field_name=value` keyword arguments." "supported. Please use `field_name=value` keyword arguments."
) )
assert str(e.exception) == expected_msg assert str(exc_info.value) == expected_msg
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 e: with pytest.raises(TypeError) as exc_info:
job = self.Job("Test Job", 4) job = 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 "
"supported. Please use `field_name=value` keyword arguments." "supported. Please use `field_name=value` keyword arguments."
) )
assert str(e.exception) == expected_msg assert str(exc_info.value) == expected_msg
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 e: with pytest.raises(TypeError) as exc_info:
job = self.Job("Test Job", years=4) job = 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 "
"supported. Please use `field_name=value` keyword arguments." "supported. Please use `field_name=value` keyword arguments."
) )
assert str(e.exception) == expected_msg assert str(exc_info.value) == expected_msg
def test_data_contains_id_field(self): def test_data_contains_id_field(self):
"""Ensure that asking for _data returns 'id'.""" """Ensure that asking for _data returns 'id'."""

View File

@ -270,10 +270,12 @@ class TestDictField(MongoDBTestCase):
embed = Embedded(name="garbage") embed = Embedded(name="garbage")
doc = DictFieldTest(dictionary=embed) doc = DictFieldTest(dictionary=embed)
with pytest.raises(ValidationError) as ctx_err: with pytest.raises(ValidationError) as exc_info:
doc.validate() doc.validate()
assert "'dictionary'" in str(ctx_err.exception)
assert "Only dictionaries may be used in a DictField" in str(ctx_err.exception) error_msg = str(exc_info.value)
assert "'dictionary'" in error_msg
assert "Only dictionaries may be used in a DictField" in error_msg
def test_atomic_update_dict_field(self): def test_atomic_update_dict_field(self):
"""Ensure that the entire DictField can be atomically updated.""" """Ensure that the entire DictField can be atomically updated."""

View File

@ -88,9 +88,10 @@ class TestEmailField(MongoDBTestCase):
invalid_idn = ".google.com" invalid_idn = ".google.com"
user = User(email="me@%s" % invalid_idn) user = User(email="me@%s" % invalid_idn)
with pytest.raises(ValidationError) as ctx_err:
with pytest.raises(ValidationError) as exc_info:
user.validate() user.validate()
assert "domain failed IDN encoding" in str(ctx_err.exception) assert "domain failed IDN encoding" in str(exc_info.value)
def test_email_field_ip_domain(self): def test_email_field_ip_domain(self):
class User(Document): class User(Document):

View File

@ -36,11 +36,11 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
name = StringField() name = StringField()
emb = EmbeddedDocumentField("MyDoc") emb = EmbeddedDocumentField("MyDoc")
with pytest.raises(ValidationError) as ctx: with pytest.raises(ValidationError) as exc_info:
emb.document_type emb.document_type
assert ( assert (
"Invalid embedded document class provided to an EmbeddedDocumentField" "Invalid embedded document class provided to an EmbeddedDocumentField"
in str(ctx.exception) in str(exc_info.value)
) )
def test_embedded_document_field_only_allow_subclasses_of_embedded_document(self): def test_embedded_document_field_only_allow_subclasses_of_embedded_document(self):
@ -72,9 +72,9 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
p = Person(settings=AdminSettings(foo1="bar1", foo2="bar2"), name="John").save() p = Person(settings=AdminSettings(foo1="bar1", foo2="bar2"), name="John").save()
# Test non exiting attribute # Test non exiting attribute
with pytest.raises(InvalidQueryError) as ctx_err: with pytest.raises(InvalidQueryError) as exc_info:
Person.objects(settings__notexist="bar").first() Person.objects(settings__notexist="bar").first()
assert unicode(ctx_err.exception) == u'Cannot resolve field "notexist"' assert unicode(exc_info.value) == u'Cannot resolve field "notexist"'
with pytest.raises(LookUpError): with pytest.raises(LookUpError):
Person.objects.only("settings.notexist") Person.objects.only("settings.notexist")
@ -108,9 +108,9 @@ class TestEmbeddedDocumentField(MongoDBTestCase):
p.save() p.save()
# Test non exiting attribute # Test non exiting attribute
with pytest.raises(InvalidQueryError) as ctx_err: with pytest.raises(InvalidQueryError) as exc_info:
assert Person.objects(settings__notexist="bar").first().id == p.id assert Person.objects(settings__notexist="bar").first().id == p.id
assert unicode(ctx_err.exception) == u'Cannot resolve field "notexist"' assert unicode(exc_info.value) == u'Cannot resolve field "notexist"'
# Test existing attribute # Test existing attribute
assert Person.objects(settings__base_foo="basefoo").first().id == p.id assert Person.objects(settings__base_foo="basefoo").first().id == p.id
@ -316,9 +316,9 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
p2 = Person(settings=NonAdminSettings(foo2="bar2")).save() p2 = Person(settings=NonAdminSettings(foo2="bar2")).save()
# Test non exiting attribute # Test non exiting attribute
with pytest.raises(InvalidQueryError) as ctx_err: with pytest.raises(InvalidQueryError) as exc_info:
Person.objects(settings__notexist="bar").first() Person.objects(settings__notexist="bar").first()
assert unicode(ctx_err.exception) == u'Cannot resolve field "notexist"' assert unicode(exc_info.value) == u'Cannot resolve field "notexist"'
with pytest.raises(LookUpError): with pytest.raises(LookUpError):
Person.objects.only("settings.notexist") Person.objects.only("settings.notexist")
@ -344,9 +344,9 @@ class TestGenericEmbeddedDocumentField(MongoDBTestCase):
p.save() p.save()
# Test non exiting attribute # Test non exiting attribute
with pytest.raises(InvalidQueryError) as ctx_err: with pytest.raises(InvalidQueryError) as exc_info:
assert Person.objects(settings__notexist="bar").first().id == p.id assert Person.objects(settings__notexist="bar").first().id == p.id
assert unicode(ctx_err.exception) == u'Cannot resolve field "notexist"' assert unicode(exc_info.value) == u'Cannot resolve field "notexist"'
# Test existing attribute # Test existing attribute
assert Person.objects(settings__base_foo="basefoo").first().id == p.id assert Person.objects(settings__base_foo="basefoo").first().id == p.id

View File

@ -96,13 +96,13 @@ class TestField(MongoDBTestCase):
"it should raise a ValidationError if validation fails" "it should raise a ValidationError if validation fails"
) )
with pytest.raises(DeprecatedError) as ctx_err: with pytest.raises(DeprecatedError) as exc_info:
Person(name="").validate() Person(name="").validate()
assert str(ctx_err.exception) == error assert str(exc_info.value) == error
with pytest.raises(DeprecatedError) as ctx_err: with pytest.raises(DeprecatedError) as exc_info:
Person(name="").save() Person(name="").save()
assert str(ctx_err.exception) == error assert str(exc_info.value) == error
def test_custom_field_validation_raise_validation_error(self): def test_custom_field_validation_raise_validation_error(self):
def _not_empty(z): def _not_empty(z):
@ -114,16 +114,10 @@ class TestField(MongoDBTestCase):
Person.drop_collection() Person.drop_collection()
with pytest.raises(ValidationError) as ctx_err: with pytest.raises(ValidationError) as exc_info:
Person(name="").validate() Person(name="").validate()
assert "ValidationError (Person:None) (cantbeempty: ['name'])" == str( assert "ValidationError (Person:None) (cantbeempty: ['name'])" == str(
ctx_err.exception exc_info.value
)
with pytest.raises(ValidationError):
Person(name="").save()
assert "ValidationError (Person:None) (cantbeempty: ['name'])" == str(
ctx_err.exception
) )
Person(name="garbage").validate() Person(name="garbage").validate()
@ -1029,9 +1023,9 @@ class TestField(MongoDBTestCase):
if i < 6: if i < 6:
foo.save() foo.save()
else: else:
with pytest.raises(ValidationError) as cm: with pytest.raises(ValidationError) as exc_info:
foo.save() foo.save()
assert "List is too long" in str(cm.exception) assert "List is too long" in str(exc_info.value)
def test_list_field_max_length_set_operator(self): def test_list_field_max_length_set_operator(self):
"""Ensure ListField's max_length is respected for a "set" operator.""" """Ensure ListField's max_length is respected for a "set" operator."""
@ -1040,9 +1034,9 @@ class TestField(MongoDBTestCase):
items = ListField(IntField(), max_length=3) items = ListField(IntField(), max_length=3)
foo = Foo.objects.create(items=[1, 2, 3]) foo = Foo.objects.create(items=[1, 2, 3])
with pytest.raises(ValidationError) as cm: with pytest.raises(ValidationError) as exc_info:
foo.modify(set__items=[1, 2, 3, 4]) foo.modify(set__items=[1, 2, 3, 4])
assert "List is too long" in str(cm.exception) assert "List is too long" in str(exc_info.value)
def test_list_field_rejects_strings(self): def test_list_field_rejects_strings(self):
"""Strings aren't valid list field data types.""" """Strings aren't valid list field data types."""
@ -2325,21 +2319,21 @@ class TestEmbeddedDocumentListField(MongoDBTestCase):
# Test with an embeddedDocument instead of a list(embeddedDocument) # Test with an embeddedDocument instead of a list(embeddedDocument)
# It's an edge case but it used to fail with a vague error, making it difficult to troubleshoot it # It's an edge case but it used to fail with a vague error, making it difficult to troubleshoot it
post = self.BlogPost(comments=comment) post = self.BlogPost(comments=comment)
with pytest.raises(ValidationError) as ctx_err: with pytest.raises(ValidationError) as exc_info:
post.validate() post.validate()
assert "'comments'" in str(ctx_err.exception)
assert "Only lists and tuples may be used in a list field" in str( error_msg = str(exc_info.value)
ctx_err.exception assert "'comments'" in error_msg
) assert "Only lists and tuples may be used in a list field" in error_msg
# Test with a Document # Test with a Document
post = self.BlogPost(comments=Title(content="garbage")) post = self.BlogPost(comments=Title(content="garbage"))
with pytest.raises(ValidationError): with pytest.raises(ValidationError) as exc_info:
post.validate() post.validate()
assert "'comments'" in str(ctx_err.exception)
assert "Only lists and tuples may be used in a list field" in str( error_msg = str(exc_info.value)
ctx_err.exception assert "'comments'" in error_msg
) assert "Only lists and tuples may be used in a list field" in error_msg
def test_no_keyword_filter(self): def test_no_keyword_filter(self):
""" """

View File

@ -31,10 +31,10 @@ class TestURLField(MongoDBTestCase):
# TODO fix URL validation - this *IS* a valid URL # TODO fix URL validation - this *IS* a valid URL
# For now we just want to make sure that the error message is correct # For now we just want to make sure that the error message is correct
with pytest.raises(ValidationError) as ctx_err: with pytest.raises(ValidationError) as exc_info:
link.validate() link.validate()
assert ( assert (
unicode(ctx_err.exception) unicode(exc_info.value)
== u"ValidationError (Link:None) (Invalid URL: http://\u043f\u0440\u0438\u0432\u0435\u0442.com: ['url'])" == u"ValidationError (Link:None) (Invalid URL: http://\u043f\u0440\u0438\u0432\u0435\u0442.com: ['url'])"
) )

View File

@ -908,20 +908,20 @@ class TestQueryset(unittest.TestCase):
assert Blog.objects.count() == 2 assert Blog.objects.count() == 2
# test inserting an existing document (shouldn't be allowed) # test inserting an existing document (shouldn't be allowed)
with pytest.raises(OperationError) as cm: with pytest.raises(OperationError) as exc_info:
blog = Blog.objects.first() blog = Blog.objects.first()
Blog.objects.insert(blog) Blog.objects.insert(blog)
assert ( assert (
str(cm.exception) str(exc_info.value)
== "Some documents have ObjectIds, use doc.update() instead" == "Some documents have ObjectIds, use doc.update() instead"
) )
# test inserting a query set # test inserting a query set
with pytest.raises(OperationError) as cm: with pytest.raises(OperationError) as exc_info:
blogs_qs = Blog.objects blogs_qs = Blog.objects
Blog.objects.insert(blogs_qs) Blog.objects.insert(blogs_qs)
assert ( assert (
str(cm.exception) str(exc_info.value)
== "Some documents have ObjectIds, use doc.update() instead" == "Some documents have ObjectIds, use doc.update() instead"
) )
@ -5053,9 +5053,8 @@ 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) as ctx_err: with pytest.raises(OperationError, match="QuerySet already cached") as ctx_err:
qs.no_cache() qs.no_cache()
assert "QuerySet already cached" == str(ctx_err.exception)
def test_no_cached_queryset_no_cache_back_to_cache(self): def test_no_cached_queryset_no_cache_back_to_cache(self):
class Person(Document): class Person(Document):

View File

@ -142,22 +142,22 @@ class ConnectionTest(unittest.TestCase):
def test_connect_fails_if_connect_2_times_with_default_alias(self): def test_connect_fails_if_connect_2_times_with_default_alias(self):
connect("mongoenginetest") connect("mongoenginetest")
with pytest.raises(ConnectionFailure) as ctx_err: with pytest.raises(ConnectionFailure) as exc_info:
connect("mongoenginetest2") connect("mongoenginetest2")
assert ( assert (
"A different connection with alias `default` was already registered. Use disconnect() first" "A different connection with alias `default` was already registered. Use disconnect() first"
== str(ctx_err.exception) == str(exc_info.value)
) )
def test_connect_fails_if_connect_2_times_with_custom_alias(self): def test_connect_fails_if_connect_2_times_with_custom_alias(self):
connect("mongoenginetest", alias="alias1") connect("mongoenginetest", alias="alias1")
with pytest.raises(ConnectionFailure) as ctx_err: with pytest.raises(ConnectionFailure) as exc_info:
connect("mongoenginetest2", alias="alias1") connect("mongoenginetest2", alias="alias1")
assert ( assert (
"A different connection with alias `alias1` was already registered. Use disconnect() first" "A different connection with alias `alias1` was already registered. Use disconnect() first"
== str(ctx_err.exception) == str(exc_info.value)
) )
def test_connect_fails_if_similar_connection_settings_arent_defined_the_same_way( def test_connect_fails_if_similar_connection_settings_arent_defined_the_same_way(
@ -366,9 +366,9 @@ class ConnectionTest(unittest.TestCase):
assert History._collection is None assert History._collection is None
with pytest.raises(ConnectionFailure) as ctx_err: with pytest.raises(ConnectionFailure) as exc_info:
History.objects.first() History.objects.first()
assert "You have not defined a default connection" == str(ctx_err.exception) assert "You have not defined a default connection" == str(exc_info.value)
def test_connect_disconnect_works_on_same_document(self): def test_connect_disconnect_works_on_same_document(self):
"""Ensure that the connect/disconnect works properly with a single Document""" """Ensure that the connect/disconnect works properly with a single Document"""