From 14f94933804c6c6f9fbaf956cce5ac12beae459a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Honza=20Kr=C3=A1l?= Date: Wed, 3 Jun 2009 02:35:59 +0000 Subject: [PATCH] [soc2009/model-validation] Added first validator with tests No usefull error message yet, validator isn't used anywhere, just a mockup basically git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@10898 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/validators.py | 7 ++++++ tests/modeltests/validators/__init__.py | 0 tests/modeltests/validators/models.py | 0 tests/modeltests/validators/tests.py | 33 +++++++++++++++++++++++++ 4 files changed, 40 insertions(+) create mode 100644 django/core/validators.py create mode 100644 tests/modeltests/validators/__init__.py create mode 100644 tests/modeltests/validators/models.py create mode 100644 tests/modeltests/validators/tests.py diff --git a/django/core/validators.py b/django/core/validators.py new file mode 100644 index 0000000000..319c3c4c62 --- /dev/null +++ b/django/core/validators.py @@ -0,0 +1,7 @@ +from django.core.exceptions import ValidationError + +def validate_integer(value, all_values={}, model_instance=None): + try: + int(value) + except (ValueError, TypeError), e: + raise ValidationError('') diff --git a/tests/modeltests/validators/__init__.py b/tests/modeltests/validators/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/modeltests/validators/models.py b/tests/modeltests/validators/models.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/modeltests/validators/tests.py b/tests/modeltests/validators/tests.py new file mode 100644 index 0000000000..ffeaeb979a --- /dev/null +++ b/tests/modeltests/validators/tests.py @@ -0,0 +1,33 @@ +from unittest import TestCase + +from django.core.exceptions import ValidationError +from django.core.validators import validate_integer + +class TestSimpleValidators(TestCase): + pass + +SIMPLE_VALIDATORS_VALUES = ( + (validate_integer, '42', None), + (validate_integer, '-42', None), + (validate_integer, -42, None), + (validate_integer, -42.5, None), + (validate_integer, None, ValidationError), + (validate_integer, 'a', ValidationError), +) + +def get_simple_test_func(expected, value, num): + if isinstance(expected, type) and issubclass(expected, ValidationError): + test_mask = 'test_%s_raises_error_%d' + def test_func(self): + self.assertRaises(expected, validator, value) + else: + test_mask = 'test_%s_%d' + def test_func(self): + self.assertEqual(expected, validator(value)) + test_name = test_mask % (validator.__name__, num) + return test_name, test_func + +test_counter = {} +for validator, value, expected in SIMPLE_VALIDATORS_VALUES: + num = test_counter[validator] = test_counter.setdefault(validator, 0) + 1 + setattr(TestSimpleValidators, *get_simple_test_func(expected, value, num))