def test_get_prep_value_empty_list(self): """No choice stored as empty string""" item = SelectMultipleField() self.assertIsInstance( item.get_prep_value([]), six.string_types) self.assertEquals( item.get_prep_value([]), '')
def test_validate_blank(self): item = SelectMultipleField(choices=self.choices) item.editable = True item.blank = True value = [''] instance = "Fake Unused Instance" self.assertIs(item.validate(value, instance), None)
def test_max_choices_single(self): item = SelectMultipleField(choices=self.choices, max_length=254, max_choices=1) self.assertEqual(item.max_choices, 1) self.assertIsInstance(item.validators[2], MaxChoicesValidator) self.assertIs(item.run_validators(self.choices_list[0:1]), None)
def test_max_length_single(self): item = SelectMultipleField(choices=self.choices, max_length=1) self.assertEqual(item.max_length, 1) self.assertIsInstance(item.validators[0], validators.MaxLengthValidator) self.assertIsInstance(item.validators[1], MaxLengthValidator) choice = self.choices_list[0:1] self.assertIs(item.run_validators(value=choice), None)
def test_get_choices_w_blank_choice(self): """Overridden get_choices suppresses blank choice tuple""" item = SelectMultipleField(choices=self.choices) choices = item.get_choices(include_blank=True) self.assertIsInstance(choices, list) self.assertIsInstance(choices[0], tuple) self.assertIn(BLANK_CHOICE_DASH[0], choices)
def test_formfield_default_is_callable(self): item = SelectMultipleField(default=FakeCallableDefault) form = item.formfield() self.assertIsInstance(form, SelectMultipleFormField) self.assertTrue(item.has_default()) self.assertTrue(callable(form.initial)) self.assertIs(form.initial, FakeCallableDefault)
def test_to_python_single_string(self): item = SelectMultipleField() single = self.choices_list[3] self.assertIsInstance( item.to_python(single), list) self.assertEquals( item.to_python(single), [single])
def test_to_python_string(self): item = SelectMultipleField() for i, v in enumerate(self.choices_list): subset = self.choices_list[0: i] encoded = encode_list_to_csv(subset) self.assertIsInstance(item.to_python(encoded), list) self.assertEqual(item.to_python(encoded), sorted(subset))
def test_validate_valid_choices(self): for choices in self.test_choices: item = SelectMultipleField(choices=choices[0]) item.editable = True instance = "Fake Unused Instance" for i, v in enumerate(choices[1]): subset = self.choices_list[0: i + 1] self.assertIs(item.validate(subset, instance), None)
def test_formfield_default_string(self): string_default = "String As Default" item = SelectMultipleField(default=string_default) form = item.formfield() self.assertIsInstance(form, SelectMultipleFormField) self.assertTrue(item.has_default()) self.assertEqual(item.get_default(), string_default) self.assertEqual(form.initial, string_default)
def test_validate_options_list_raises_validationerror(self): item = SelectMultipleField(choices=self.choices) value = ['InvalidChoice'] with self.assertRaises(ValidationError) as cm: self.assertTrue(item.validate_options_list(value)) self.assertEqual( cm.exception.messages[0], SelectMultipleField. default_error_messages['invalid_choice'].format(value[0]))
def test_max_length_many(self): for n in range(2, len(self.choices_list)): many_choices = self.choices_list[0:n] encoded_choices_len = len(encode_list_to_csv(many_choices)) item = SelectMultipleField(choices=self.choices, max_length=encoded_choices_len) self.assertEqual(item.max_length, encoded_choices_len) self.assertIsInstance(item.validators[0], MaxLengthValidator) self.assertIs(item.run_validators(value=many_choices), None)
def test_max_length_many(self): for n in range(2, len(self.choices_list)): many_choices = self.choices_list[0:n] encoded_choices_len = len(encode_list_to_csv(many_choices)) item = SelectMultipleField( choices=self.choices, max_length=encoded_choices_len) self.assertEqual(item.max_length, encoded_choices_len) self.assertIsInstance(item.validators[0], MaxLengthValidator) self.assertIs(item.run_validators(value=many_choices), None)
def test_to_python_invalid_type(self): item = SelectMultipleField() invalid_type = True with self.assertRaises(ValidationError) as cm: item.to_python(invalid_type) self.assertEqual( cm.exception.messages[0], (SelectMultipleField.default_error_messages['invalid_type'] % {'value': type(invalid_type)}))
def test_to_python_list_w_invalid_value(self): item = SelectMultipleField(choices=self.choices) self.assertTrue(item.choices) invalid_list = ['InvalidChoice'] with self.assertRaises(ValidationError) as cm: item.to_python(invalid_list) self.assertEqual( cm.exception.messages[0], SelectMultipleField. default_error_messages['invalid_choice'].format(invalid_list[0]))
def test_max_choices_many(self): for n in range(2, len(self.choices_list)): many_choices = self.choices_list[0:n] many_choices_len = len(many_choices) item = SelectMultipleField(choices=self.choices, max_length=254, max_choices=many_choices_len) self.assertEqual(item.max_choices, many_choices_len) self.assertIsInstance(item.validators[2], MaxChoicesValidator) self.assertIs(item.run_validators(many_choices), None)
def test_validate_not_blank(self): item = SelectMultipleField(choices=self.choices) item.editable = True item.blank = False value = [] instance = "Fake Unused Instance" with self.assertRaises(ValidationError) as cm: self.assertTrue(item.validate(value, instance)) self.assertEqual(cm.exception.messages[0], SelectMultipleField.default_error_messages['blank'])
def test_max_choices_many(self): for n in range(2, len(self.choices_list)): many_choices = self.choices_list[0:n] many_choices_len = len(many_choices) item = SelectMultipleField( choices=self.choices, max_length=254, max_choices=many_choices_len) self.assertEqual(item.max_choices, many_choices_len) self.assertIsInstance(item.validators[1], MaxChoicesValidator) self.assertIs(item.run_validators(many_choices), None)
def test_validate_invalid_string(self): item = SelectMultipleField(choices=self.choices) item.editable = True value = "Invalid Choice" instance = "Fake Unused Instance" with self.assertRaises(ValidationError) as cm: self.assertTrue(item.validate(value, instance)) self.assertEqual( cm.exception.messages[0], SelectMultipleField. default_error_messages['invalid_choice'].format(value))
def test_validate_options_list_raises_validationerror(self): item = SelectMultipleField(choices=self.choices) value = ['InvalidChoice'] with self.assertRaises(ValidationError) as cm: self.assertTrue(item.validate_options_list(value)) self.assertEqual( cm.exception.messages[0], (SelectMultipleField.default_error_messages['invalid_choice'] % {'value': value[0]}) )
def test_max_length_validationerror_single(self): item = SelectMultipleField(choices=self.choices, max_length=1) self.assertEqual(item.max_length, 1) self.assertIsInstance(item.validators[0], MaxLengthValidator) two_choices = self.choices_list[0:2] with self.assertRaises(ValidationError) as cm: item.run_validators(value=two_choices) self.assertEqual( cm.exception.messages[0], MaxLengthValidator.message % {'limit_value': 1, 'show_value': 3} )
def test_to_python_list_w_invalid_value(self): item = SelectMultipleField(choices=self.choices) self.assertTrue(item.choices) invalid_list = ['InvalidChoice'] with self.assertRaises(ValidationError) as cm: item.to_python(invalid_list) self.assertEqual( cm.exception.messages[0], (SelectMultipleField.default_error_messages['invalid_choice'] % {'value': invalid_list[0]}) )
def test_formfield_empty_value_w_blank(self): """ Formfield can return empty value, set ModelField.blank to True """ item = SelectMultipleField(choices=self.choices, blank=True) form = item.formfield() self.assertIsInstance(form, SelectMultipleFormField) self.assertEqual(form.coerce, item.to_python) self.assertTrue(item.blank) self.assertFalse(form.required) self.assertFalse(item.null) self.assertEqual(form.empty_value, []) self.assertIn(BLANK_CHOICE_DASH[0], form.choices)
def test_validate_invalid_string(self): item = SelectMultipleField(choices=self.choices) item.editable = True value = "Invalid Choice" instance = "Fake Unused Instance" with self.assertRaises(ValidationError) as cm: self.assertTrue(item.validate(value, instance)) self.assertEqual( cm.exception.messages[0], (SelectMultipleField.default_error_messages['invalid_choice'] % {'value': value}) )
def test_validate_not_blank(self): item = SelectMultipleField(choices=self.choices) item.editable = True item.blank = False value = [] instance = "Fake Unused Instance" with self.assertRaises(ValidationError) as cm: self.assertTrue(item.validate(value, instance)) self.assertEqual( cm.exception.messages[0], SelectMultipleField.default_error_messages['blank'] )
def test_formfield_no_empty_value_by_default(self): """ Formfield returns no empty value by default """ item = SelectMultipleField(choices=self.choices) form = item.formfield() self.assertIsInstance(form, SelectMultipleFormField) self.assertFalse(item.has_default()) self.assertEqual(form.coerce, item.to_python) self.assertFalse(item.blank) self.assertTrue(form.required) self.assertFalse(item.null) self.assertEqual(form.empty_value, []) self.assertNotIn(BLANK_CHOICE_DASH[0], form.choices)
class ChickenBalls(models.Model): """ChickenBalls is used for South migration testing""" SUICIDE = 's' HOT = 'h' HOME_STYLE = 'H' CAJUN = 'c' JERK = 'j' GATOR = 'g' FLAVOUR_CHOICES = ( (_('Hot & Spicy'), ( (SUICIDE, _('Suicide hot')), (HOT, _('Hot hot sauce')), (CAJUN, _('Cajun sauce')), (JERK, _('Jerk sauce')))), (_('Traditional'), ( (HOME_STYLE, _('Homestyle')), (GATOR, _('Gator flavour')))), ) flavour = SelectMultipleField( blank=True, include_blank=False, max_length=5, max_choices=2, choices=FLAVOUR_CHOICES ) RANCH = 'r' HONEY_MUSTARD = 'h' BBQ = 'b' DIP_CHOICES = ( (RANCH, _('Ranch')), (HONEY_MUSTARD, _('Honey mustard')), (BBQ, _('BBQ')), ) dips = SelectMultipleField( blank=True, default='', include_blank=False, max_length=6, max_choices=3, choices=DIP_CHOICES ) def __str__(self): return "pk=%s" % force_text(self.pk) def get_absolute_url(self): return reverse('ftw:detail', args=[self.pk])
class Career(TranslatableModel, PublishingModel, SpaceaweModel, SearchModel): cover = ImageField(null=True, blank=True, upload_to='careers') _languages = SelectMultipleField(max_length=9999, choices=global_settings.LANGUAGES, db_column='languages') objects = CareerManager() @property def main_visual(self): return self.cover.file if self.cover else None def links_list(self): return [link for link in self.links.all()] def __str__(self): return self.title def get_absolute_url(self): return reverse('careers:career-detail', kwargs={ 'slug': self.slug, }) def zip_url(self): return self.download_url('zip') def pdf_url(self): return self.download_url('pdf') def epub_url(self): return self.download_url('epub') def rtf_url(self): return self.download_url('rtf') def download_url(self, resource): return os.path.join(settings.MEDIA_URL, self.media_key(), 'download', self.download_key() + '.' + resource) def download_path(self, resource): return os.path.join(settings.MEDIA_ROOT, self.media_key(), 'download', self.download_key() + '.' + resource) def attachment_url(self, filename): if filename.startswith('http') or filename.startswith('/'): result = filename else: result = os.path.join(settings.MEDIA_URL, 'activities/attach', self.uuid, filename) return result def download_key(self): return self.slug + '-careers-' + str(self.pk) @classmethod def media_key(cls): return str(cls._meta.verbose_name_plural) class Meta: ordering = ['release_date']
class Booklet(TranslatableModel, PublishingModel): _languages = SelectMultipleField(max_length=9999, choices=global_settings.LANGUAGES, db_column='languages') objects = BookletManager() @property def main_visual(self): return self.cover.file if self.cover else None def __str__(self): return self.title def pdf_url(self): return self.download_url('pdf') def download_url(self, resource): return os.path.join(settings.MEDIA_URL, self.media_key(), 'download', self.download_key() + '.' + resource) def download_path(self, resource): return os.path.join(settings.MEDIA_ROOT, self.media_key(), 'download', self.download_key() + '.' + resource) def download_key(self): return self.slug + '-booklet-' + str(self.pk) @classmethod def media_key(cls): return str(cls._meta.verbose_name_plural) class Meta: ordering = ['release_date']
class ProjectPlatformSettings(BasePlatformSettings): PROJECT_CREATE_OPTIONS = ( ('sourcing', _('Sourcing')), ('funding', _('Funding')), ) PROJECT_CONTACT_TYPE_OPTIONS = ( ('organization', _('Organization')), ('personal', _('Personal')), ) PROJECT_CREATE_FLOW_OPTIONS = ( ('combined', _('Combined')), ('choice', _('Choice')), ) PROJECT_CONTACT_OPTIONS = ( ('mail', _('E-mail')), ('phone', _('Phone')), ) PROJECT_SHARE_OPTIONS = ( ('twitter', _('Twitter')), ('facebook', _('Facebook')), ('facebookAtWork', _('Facebook at Work')), ('linkedin', _('LinkedIn')), ('whatsapp', _('Whatsapp')), ('email', _('Email')), ) create_types = SelectMultipleField(max_length=100, choices=PROJECT_CREATE_OPTIONS) contact_types = SelectMultipleField(max_length=100, choices=PROJECT_CONTACT_TYPE_OPTIONS) share_options = SelectMultipleField( max_length=100, choices=PROJECT_SHARE_OPTIONS, blank=True, include_blank=False ) facebook_at_work_url = models.URLField(max_length=100, null=True, blank=True) allow_anonymous_rewards = models.BooleanField( _('Allow guests to donate rewards'), default=True ) create_flow = models.CharField(max_length=100, choices=PROJECT_CREATE_FLOW_OPTIONS) contact_method = models.CharField(max_length=100, choices=PROJECT_CONTACT_OPTIONS) class Meta: verbose_name_plural = _('project platform settings') verbose_name = _('project platform settings')
def test_max_length_validationerror_many(self): for n in range(2, len(self.choices_list)): test_max_length = 2 * n - 2 # One less than encoded list len item = SelectMultipleField(choices=self.choices, max_length=test_max_length) self.assertEqual(item.max_length, test_max_length) self.assertIsInstance(item.validators[0], MaxLengthValidator) many_choices = self.choices_list[0:n] many_choices_len = len(encode_list_to_csv(many_choices)) self.assertTrue(many_choices_len > test_max_length) with self.assertRaises(ValidationError) as cm: item.run_validators(value=many_choices) self.assertEqual( cm.exception.messages[0], MaxLengthValidator.message % { 'limit_value': item.max_length, 'show_value': many_choices_len })
class TeachingMaterial(TranslatableModel, PublishingModel, SpaceaweModel): activity_type_choises = (('g', 'Game'), ('l', 'Lesson plan')) cover = ImageField(null=True, blank=True, upload_to='careers/teaching-materials/covers') age = models.ManyToManyField( MetadataOption, limit_choices_to={'group': 'age'}, related_name='age+', ) learning = models.CharField( max_length=2, choices=activity_type_choises, blank=False, null=False, verbose_name='type of learning activity', ) _languages = SelectMultipleField(max_length=9999, choices=global_settings.LANGUAGES, db_column='languages') objects = TeachingMaterialManager() def age_range(self): # return ' '.join(obj.title for obj in self.age.all()) age_ranges = [obj.title for obj in self.age.all()] return utils.beautify_age_range(age_ranges) @property def main_visual(self): return self.cover.file if self.cover else None def __str__(self): return self.title def get_absolute_url(self): return reverse('careers:teaching-material-detail', kwargs={ 'slug': self.slug, }) def attachment_url(self, filename): if filename.startswith('http') or filename.startswith('/'): result = filename else: result = os.path.join(settings.MEDIA_URL, 'careers/teaching-materials/attachments', self.id, filename) return result @classmethod def media_key(cls): return str(cls._meta.verbose_name_plural) class Meta: ordering = ['release_date']
def test_max_length_validationerror_many(self): for n in range(2, len(self.choices_list)): test_max_length = 2 * n - 2 # One less than encoded list len item = SelectMultipleField( choices=self.choices, max_length=test_max_length) self.assertEqual(item.max_length, test_max_length) self.assertIsInstance(item.validators[0], MaxLengthValidator) many_choices = self.choices_list[0:n] many_choices_len = len(encode_list_to_csv(many_choices)) self.assertTrue(many_choices_len > test_max_length) with self.assertRaises(ValidationError) as cm: item.run_validators(value=many_choices) self.assertEqual( cm.exception.messages[0], MaxLengthValidator.message % { 'limit_value': item.max_length, 'show_value': many_choices_len} )
class Post(models.Model): ICEHOUSE = 'icehouse' JUNO = 'juno' KILO = 'kilo' LIBERTY = 'liberty' MITAKA = 'mitaka' NEWTON = 'newton' OCATA = 'ocata' RELEASE_CHOICES = ( (ICEHOUSE, 'Icehouse'), (JUNO, 'Juno'), (KILO, 'Kilo'), (LIBERTY, 'Liberty'), (MITAKA, 'Mitaka'), (OCATA, 'Ocata'), ) releases = SelectMultipleField( max_length=50, choices=RELEASE_CHOICES, default='ocata' ) author = models.ForeignKey('auth.User') ossn = models.CharField(max_length=10) title = models.CharField(max_length=200) discussion = models.TextField() summary = models.TextField() actions = models.TextField() contact = models.CharField(max_length=50) references = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title return "pk=%s" % force_text(self.pk) def get_releases(self): if self.releases: keys_choices = self.toppings return '%s' % (', '.join(filter(bool, keys_choices))) get_releases.short_description = _('Releases') def get_absolute_url(self): return reverse('Post:detail', args=[self.pk])
class ChickenWings(models.Model): """ChickenWings demonstrates optgroup usage and max_choices""" SUICIDE = 's' HOT = 'h' MEDIUM = 'm' MILD = 'M' CAJUN = 'c' JERK = 'j' HONEY_GARLIC = 'g' HONEY_BBQ = 'H' THAI = 't' BACON = 'b' BOURBON = 'B' FLAVOUR_CHOICES = ( (_('Hot & Spicy'), ( (SUICIDE, _('Suicide hot')), (HOT, _('Hot hot sauce')), (MEDIUM, _('Medium hot sauce')), (MILD, _('Mild hot sauce')), (CAJUN, _('Cajun sauce')), (JERK, _('Jerk sauce')))), (_('Sweets'), ( (HONEY_GARLIC, _('Honey garlic')), (HONEY_BBQ, _('Honey barbeque')), (THAI, _('Thai sweet sauce')), (BACON, _('Messy bacon sauce')), (BOURBON, _('Bourbon whiskey barbeque')))), ) flavour = SelectMultipleField( blank=True, include_blank=False, max_length=5, max_choices=2, choices=FLAVOUR_CHOICES ) def __str__(self): return "pk=%s" % force_text(self.pk) def get_absolute_url(self): return reverse('ftw:detail', args=[self.pk])
class Pizza(models.Model): """Pizza demonstrates minimal use-case""" ANCHOVIES = 'a' BLACK_OLIVES = 'b' CHEDDAR_CHEESE = 'c' EGG = 'e' PANCETTA = 'pk' PEPPERONI = 'p' PROSCIUTTO_CRUDO = 'P' MOZZARELLA = 'm' MUSHROOMS = 'M' TOMATO = 't' TOPPING_CHOICES = ( (ANCHOVIES, _('Anchovies')), (BLACK_OLIVES, _('Black olives')), (CHEDDAR_CHEESE, _('Cheddar cheese')), (EGG, _('Eggs')), (PANCETTA, _('Pancetta')), (PEPPERONI, _('Pepperoni')), (PROSCIUTTO_CRUDO, _('Prosciutto crudo')), (MOZZARELLA, _('Mozzarella')), (MUSHROOMS, _('Mushrooms')), (TOMATO, _('Tomato')), ) toppings = SelectMultipleField( max_length=10, choices=TOPPING_CHOICES ) def get_toppings(self): if self.toppings: keys_choices = self.toppings return '%s' % (', '.join(filter(bool, keys_choices))) get_toppings.short_description = _('Toppings') def __str__(self): return "pk=%s" % force_text(self.pk) def get_absolute_url(self): return reverse('pizza:detail', args=[self.pk])
def test_get_choices_include_blank(self): """ Explicit include_blank value is honored, ignoring passed parameters """ item = SelectMultipleField(choices=self.choices, include_blank=True) choices = item.get_choices() self.assertIsInstance(choices, list) self.assertIsInstance(choices[0], tuple) self.assertIn(BLANK_CHOICE_DASH[0], choices) choices = item.get_choices(include_blank=False) self.assertIsInstance(choices, list) self.assertIsInstance(choices[0], tuple) self.assertIn(BLANK_CHOICE_DASH[0], choices) item = SelectMultipleField(choices=self.choices, include_blank=False) choices = item.get_choices() self.assertIsInstance(choices, list) self.assertIsInstance(choices[0], tuple) self.assertNotIn(BLANK_CHOICE_DASH[0], choices) choices = item.get_choices(include_blank=True) self.assertIsInstance(choices, list) self.assertIsInstance(choices[0], tuple) self.assertNotIn(BLANK_CHOICE_DASH[0], choices)
def test_get_choices_keys_optgroup(self): item = SelectMultipleField(choices=self.optgroup_choices) choices = item.get_choices_keys() self.assertEqual(len(choices), len(self.optgroup_choices_list)) for n in choices: self.assertIn(n, self.optgroup_choices_list)
def test_get_prep_value_none(self): """None stored as NULL in db""" item = SelectMultipleField() self.assertIs(item.get_prep_value(None), None)
def test_get_internal_type(self): item = SelectMultipleField() charfield = CharField() self.assertEquals(item.get_internal_type(), charfield.get_internal_type())
def test_formfield(self): item = SelectMultipleField() form = item.formfield() self.assertIsInstance(form, SelectMultipleFormField)
def test_to_python_list(self): for choices, choices_list in self.test_choices: item = SelectMultipleField(choices=choices) self.assertTrue(item.choices) self.assertIsInstance(item.to_python(choices_list), list) self.assertEquals(item.to_python(choices_list), choices_list)
def test_to_python_empty_list(self): item = SelectMultipleField() self.assertIsInstance(item.to_python([]), list) self.assertEquals(item.to_python([]), [])
def test_to_python_none(self): item = SelectMultipleField() self.assertIs(item.to_python(None), None)
def test_get_prep_value_list(self): item = SelectMultipleField() self.assertIsInstance( item.get_prep_value(self.choices_list), six.string_types)
def test_get_choices_keys(self): item = SelectMultipleField(choices=self.choices) self.assertEqual(item.get_choices_keys(), self.choices_list)