summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorDaniyal <abbasi.daniyal98@gmail.com>2021-03-24 11:15:08 +0530
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2021-07-15 11:43:33 +0200
commitf479df7f8d03ab767bb5e5d655243191087d6432 (patch)
treebf6f248ad7938a0d9f77ea616a59fba2d5a8befb /tests
parent08f077888548a951f01b454d0db08d9407f7f0aa (diff)
Refs #32508 -- Raised Type/ValueError instead of using "assert" in django.db.models.
Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
Diffstat (limited to 'tests')
-rw-r--r--tests/bulk_create/tests.py5
-rw-r--r--tests/dates/tests.py5
-rw-r--r--tests/datetimes/tests.py13
-rw-r--r--tests/db_functions/datetime/test_extract_trunc.py3
-rw-r--r--tests/delete/tests.py6
-rw-r--r--tests/distinct_on_fields/tests.py9
-rw-r--r--tests/invalid_models_tests/test_models.py12
-rw-r--r--tests/model_fields/test_foreignkey.py9
-rw-r--r--tests/model_fields/test_manytomanyfield.py28
-rw-r--r--tests/model_indexes/tests.py7
-rw-r--r--tests/queries/tests.py18
-rw-r--r--tests/schema/fields.py6
-rw-r--r--tests/validation/models.py15
13 files changed, 106 insertions, 30 deletions
diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py
index df764f945f..2ee54c382f 100644
--- a/tests/bulk_create/tests.py
+++ b/tests/bulk_create/tests.py
@@ -347,3 +347,8 @@ class BulkCreateTests(TestCase):
)
with self.assertRaisesMessage(ValueError, msg):
NullableFields.objects.bulk_create([NullableFields(auto_field=parent)])
+
+ def test_invalid_batch_size_exception(self):
+ msg = 'Batch size must be a positive integer.'
+ with self.assertRaisesMessage(ValueError, msg):
+ Country.objects.bulk_create([], batch_size=-1)
diff --git a/tests/dates/tests.py b/tests/dates/tests.py
index 82f21a2634..9f12d997e0 100644
--- a/tests/dates/tests.py
+++ b/tests/dates/tests.py
@@ -98,11 +98,12 @@ class DatesTests(TestCase):
def test_dates_fails_when_given_invalid_kind_argument(self):
msg = "'kind' must be one of 'year', 'month', 'week', or 'day'."
- with self.assertRaisesMessage(AssertionError, msg):
+ with self.assertRaisesMessage(ValueError, msg):
Article.objects.dates("pub_date", "bad_kind")
def test_dates_fails_when_given_invalid_order_argument(self):
- with self.assertRaisesMessage(AssertionError, "'order' must be either 'ASC' or 'DESC'."):
+ msg = "'order' must be either 'ASC' or 'DESC'."
+ with self.assertRaisesMessage(ValueError, msg):
Article.objects.dates("pub_date", "year", order="bad order")
@override_settings(USE_TZ=False)
diff --git a/tests/datetimes/tests.py b/tests/datetimes/tests.py
index f42936b557..7f98032e0a 100644
--- a/tests/datetimes/tests.py
+++ b/tests/datetimes/tests.py
@@ -199,3 +199,16 @@ class DateTimesTests(TestCase):
Article.objects.create(pub_date=dt, published_on=dt.date(), title="Don't put dates into datetime functions!")
with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'published_on' to DateTimeField"):
list(Article.objects.datetimes('published_on', 'second'))
+
+ def test_datetimes_fails_when_given_invalid_kind_argument(self):
+ msg = (
+ "'kind' must be one of 'year', 'month', 'week', 'day', 'hour', "
+ "'minute', or 'second'."
+ )
+ with self.assertRaisesMessage(ValueError, msg):
+ Article.objects.datetimes('pub_date', 'bad_kind')
+
+ def test_datetimes_fails_when_given_invalid_order_argument(self):
+ msg = "'order' must be either 'ASC' or 'DESC'."
+ with self.assertRaisesMessage(ValueError, msg):
+ Article.objects.datetimes('pub_date', 'year', order='bad order')
diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py
index e9e069c1cf..ced9da0c78 100644
--- a/tests/db_functions/datetime/test_extract_trunc.py
+++ b/tests/db_functions/datetime/test_extract_trunc.py
@@ -655,7 +655,8 @@ class DateFunctionTests(TestCase):
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(truncated=Trunc('start_datetime', 'year', output_field=IntegerField())))
- with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."):
+ msg = "'name' isn't a DateField, TimeField, or DateTimeField."
+ with self.assertRaisesMessage(TypeError, msg):
list(DTModel.objects.annotate(truncated=Trunc('name', 'year', output_field=DateTimeField())))
with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"):
diff --git a/tests/delete/tests.py b/tests/delete/tests.py
index bf6543d735..d269a08b9d 100644
--- a/tests/delete/tests.py
+++ b/tests/delete/tests.py
@@ -280,6 +280,12 @@ class DeletionTests(TestCase):
with self.assertRaisesMessage(TypeError, msg):
M.objects.all()[0:5].delete()
+ def test_pk_none(self):
+ m = M()
+ msg = "M object can't be deleted because its id attribute is set to None."
+ with self.assertRaisesMessage(ValueError, msg):
+ m.delete()
+
def test_m2m(self):
m = M.objects.create()
r = R.objects.create()
diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py
index f87a3affb3..5404c3eb41 100644
--- a/tests/distinct_on_fields/tests.py
+++ b/tests/distinct_on_fields/tests.py
@@ -87,9 +87,14 @@ class DistinctOnTests(TestCase):
self.assertSequenceEqual(qset, expected)
self.assertEqual(qset.count(), len(expected))
- # Combining queries with different distinct_fields is not allowed.
+ # Combining queries with non-unique query is not allowed.
base_qs = Celebrity.objects.all()
- with self.assertRaisesMessage(AssertionError, "Cannot combine queries with different distinct fields."):
+ msg = 'Cannot combine a unique query with a non-unique query.'
+ with self.assertRaisesMessage(TypeError, msg):
+ base_qs.distinct('id') & base_qs
+ # Combining queries with different distinct_fields is not allowed.
+ msg = 'Cannot combine queries with different distinct fields.'
+ with self.assertRaisesMessage(TypeError, msg):
base_qs.distinct('id') & base_qs.distinct('name')
# Test join unreffing
diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py
index 66657211b2..f0984fa759 100644
--- a/tests/invalid_models_tests/test_models.py
+++ b/tests/invalid_models_tests/test_models.py
@@ -1591,6 +1591,18 @@ class OtherModelTests(SimpleTestCase):
])
+class MultipleAutoFieldsTests(TestCase):
+ def test_multiple_autofields(self):
+ msg = (
+ "Model invalid_models_tests.MultipleAutoFields can't have more "
+ "than one auto-generated field."
+ )
+ with self.assertRaisesMessage(ValueError, msg):
+ class MultipleAutoFields(models.Model):
+ auto1 = models.AutoField(primary_key=True)
+ auto2 = models.AutoField(primary_key=True)
+
+
@isolate_apps('invalid_models_tests')
class JSONFieldTests(TestCase):
@skipUnlessDBFeature('supports_json_field')
diff --git a/tests/model_fields/test_foreignkey.py b/tests/model_fields/test_foreignkey.py
index d30cca9b5c..0cd6d62a55 100644
--- a/tests/model_fields/test_foreignkey.py
+++ b/tests/model_fields/test_foreignkey.py
@@ -147,3 +147,12 @@ class ForeignKeyTests(TestCase):
)
with self.assertRaisesMessage(FieldError, msg):
Related._meta.get_field('child').related_fields
+
+ def test_invalid_to_parameter(self):
+ msg = (
+ "ForeignKey(1) is invalid. First parameter to ForeignKey must be "
+ "either a model, a model name, or the string 'self'"
+ )
+ with self.assertRaisesMessage(TypeError, msg):
+ class MyModel(models.Model):
+ child = models.ForeignKey(1, models.CASCADE)
diff --git a/tests/model_fields/test_manytomanyfield.py b/tests/model_fields/test_manytomanyfield.py
index 5724fe9384..0ddf57ceaf 100644
--- a/tests/model_fields/test_manytomanyfield.py
+++ b/tests/model_fields/test_manytomanyfield.py
@@ -59,6 +59,34 @@ class ManyToManyFieldTests(SimpleTestCase):
assert_app_model_resolved('model_fields')
assert_app_model_resolved('tests')
+ def test_invalid_to_parameter(self):
+ msg = (
+ "ManyToManyField(1) is invalid. First parameter to "
+ "ManyToManyField must be either a model, a model name, or the "
+ "string 'self'"
+ )
+ with self.assertRaisesMessage(TypeError, msg):
+ class MyModel(models.Model):
+ m2m = models.ManyToManyField(1)
+
+ @isolate_apps('model_fields')
+ def test_through_db_table_mutually_exclusive(self):
+ class Child(models.Model):
+ pass
+
+ class Through(models.Model):
+ referred = models.ForeignKey(Child, on_delete=models.CASCADE)
+ referent = models.ForeignKey(Child, on_delete=models.CASCADE)
+
+ msg = 'Cannot specify a db_table if an intermediary model is used.'
+ with self.assertRaisesMessage(ValueError, msg):
+ class MyModel(models.Model):
+ m2m = models.ManyToManyField(
+ Child,
+ through='Through',
+ db_table='custom_name',
+ )
+
class ManyToManyFieldDBTests(TestCase):
diff --git a/tests/model_indexes/tests.py b/tests/model_indexes/tests.py
index 46f769cddc..95dec7ef48 100644
--- a/tests/model_indexes/tests.py
+++ b/tests/model_indexes/tests.py
@@ -173,8 +173,11 @@ class SimpleIndexesTests(SimpleTestCase):
# suffix can't be longer than 3 characters.
long_field_index.suffix = 'suff'
- msg = 'Index too long for multiple database support. Is self.suffix longer than 3 characters?'
- with self.assertRaisesMessage(AssertionError, msg):
+ msg = (
+ 'Index too long for multiple database support. Is self.suffix '
+ 'longer than 3 characters?'
+ )
+ with self.assertRaisesMessage(ValueError, msg):
long_field_index.set_name_with_model(Book)
@isolate_apps('model_indexes')
diff --git a/tests/queries/tests.py b/tests/queries/tests.py
index ac4e8849c4..fa87e7859c 100644
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -417,9 +417,10 @@ class Queries1Tests(TestCase):
def test_heterogeneous_qs_combination(self):
# Combining querysets built on different models should behave in a well-defined
# fashion. We raise an error.
- with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'):
+ msg = 'Cannot combine queries on two different base models.'
+ with self.assertRaisesMessage(TypeError, msg):
Author.objects.all() & Tag.objects.all()
- with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'):
+ with self.assertRaisesMessage(TypeError, msg):
Author.objects.all() | Tag.objects.all()
def test_ticket3141(self):
@@ -1226,10 +1227,11 @@ class Queries3Tests(TestCase):
# This shouldn't create an infinite loop.
self.assertQuerysetEqual(Valid.objects.all(), [])
- def test_ticket8683(self):
+ def test_datetimes_invalid_field(self):
# An error should be raised when QuerySet.datetimes() is passed the
# wrong type of field.
- with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."):
+ msg = "'name' isn't a DateField, TimeField, or DateTimeField."
+ with self.assertRaisesMessage(TypeError, msg):
Item.objects.datetimes('name', 'month')
def test_ticket22023(self):
@@ -2405,13 +2407,17 @@ class QuerySetSupportsPythonIdioms(TestCase):
def test_slicing_negative_indexing_not_supported_for_single_element(self):
"""hint: inverting your ordering might do what you need"""
- with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."):
+ msg = 'Negative indexing is not supported.'
+ with self.assertRaisesMessage(ValueError, msg):
Article.objects.all()[-1]
def test_slicing_negative_indexing_not_supported_for_range(self):
"""hint: inverting your ordering might do what you need"""
- with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."):
+ msg = 'Negative indexing is not supported.'
+ with self.assertRaisesMessage(ValueError, msg):
Article.objects.all()[0:-5]
+ with self.assertRaisesMessage(ValueError, msg):
+ Article.objects.all()[-1:]
def test_invalid_index(self):
msg = 'QuerySet indices must be integers or slices, not str.'
diff --git a/tests/schema/fields.py b/tests/schema/fields.py
index aaba202364..0e567e2d19 100644
--- a/tests/schema/fields.py
+++ b/tests/schema/fields.py
@@ -32,8 +32,10 @@ class CustomManyToManyField(RelatedField):
)
self.swappable = swappable
self.db_table = db_table
- if kwargs['rel'].through is not None:
- assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used."
+ if kwargs['rel'].through is not None and self.db_table is not None:
+ raise ValueError(
+ 'Cannot specify a db_table if an intermediary model is used.'
+ )
super().__init__(
related_name=related_name,
related_query_name=related_query_name,
diff --git a/tests/validation/models.py b/tests/validation/models.py
index ff9aad11f0..3a5a9cd354 100644
--- a/tests/validation/models.py
+++ b/tests/validation/models.py
@@ -125,18 +125,3 @@ class GenericIPAddressTestModel(models.Model):
class GenericIPAddrUnpackUniqueTest(models.Model):
generic_v4unpack_ip = models.GenericIPAddressField(null=True, blank=True, unique=True, unpack_ipv4=True)
-
-
-# A model can't have multiple AutoFields
-# Refs #12467.
-assertion_error = None
-try:
- class MultipleAutoFields(models.Model):
- auto1 = models.AutoField(primary_key=True)
- auto2 = models.AutoField(primary_key=True)
-except AssertionError as exc:
- assertion_error = exc
-assert str(assertion_error) == (
- "Model validation.MultipleAutoFields can't have more than one "
- "auto-generated field."
-)