def validate_choices(field, value): valid, message = True, None try: to_choice_raise(field, value) except Exception as e: valid = False message = str(e) return valid, message
def test_datum(self): field = Site._meta.get_field('datum') # only the display name is valid, case insensitive for value in [c[1] for c in DATUM_CHOICES]: valid, message = validate_choices(field, value) self.assertTrue(valid, msg="{} should be accepted as a valid choice".format(value)) valid, message = validate_choices(field, value.capitalize().lower()) self.assertTrue(valid, msg="{} should be accepted as a valid choice".format(value)) # the internal name is not valid for value in [c[0] for c in DATUM_CHOICES]: valid, message = validate_choices(field, value) self.assertFalse(valid) self.assertTrue(message) # test that blank return the default choices default_choice = field.default blanks = ['', " ", None] for value in blanks: self.assertEqual(default_choice, to_choice_raise(field, value)) # test that blank, boolean, none, int doesn't break anything for weird in [12, True, "hello world!", {}, []]: valid, message = validate_choices(field, weird) self.assertFalse(valid, msg="{} should not be accepted as a valid choice".format(weird)) self.assertTrue(message)