def test_no_evaluate(): def f(x): return x * 2 assert 34 == evaluate(f, x=17) assert 34 == should_not_evaluate(f)(17) assert 38 == evaluate(should_not_evaluate(f), x=42)(19) assert 38 == force_evaluate(should_not_evaluate(f), x=19) assert 19 == should_not_evaluate(19) # should_not_evaluate() on a non-callable is a no-op assert 19 == should_evaluate(19) # should_evaluate() on a non-callable is a no-op assert 46 == evaluate(should_evaluate(should_not_evaluate(f)), x=23)
def multi_choice_queryset(**kwargs): setdefaults(kwargs, dict( attrs={'multiple': ''}, choice_to_option=should_not_evaluate(lambda form, field, choice: (choice, choice.pk, unicode(choice), field.value_list and choice in field.value_list)), is_list=True )) return Field.choice_queryset(**kwargs)
def test_no_evaluate_recursive(): def f(x): return x * 2 subject = Struct(foo=f, bar=should_not_evaluate(f)) assert 34 == evaluate_recursive(subject, x=17).foo assert 38 == evaluate_recursive(subject, x=17).bar(19)
def choice(**kwargs): """ Shortcut for single choice field. If required is false it will automatically add an option first with the value '' and the title '---'. To override that text pass in the parameter empty_label. :param empty_label: default '---' :param choices: list of objects :param choice_to_option: callable with three arguments: form, field, choice. Convert from a choice object to a tuple of (choice, value, label, selected), the last three for the <option> element """ assert 'choices' in kwargs setdefaults(kwargs, dict( required=True, is_list=False, empty_label='---' )) if not kwargs['required'] and not kwargs['is_list']: original_choices = kwargs['choices'] def choices(form, field): return [None] + list(evaluate(original_choices, form=form, field=field)) original_parse = kwargs.get('parse', default_parse) def parse(form, field, string_value): if string_value == '': return None return original_parse(form=form, field=field, string_value=string_value) kwargs.update( choices=choices, parse=parse ) def choice_is_valid(form, field, parsed_data): del form if not field.required and parsed_data is None: return True, '' return parsed_data in field.choices, '%s not in available choices' % parsed_data def choice_post_validation(form, field): field.choice_tuples = [field.choice_to_option(form=form, field=field, choice=choice) if choice is not None else field.empty_choice_tuple for choice in field.choices] setdefaults(kwargs, dict( empty_choice_tuple=(None, '', kwargs['empty_label'], True), choice_to_option=lambda form, field, choice: (choice, unicode(choice), unicode(choice), choice == field.value), input_template='tri_form/choice.html', is_valid=choice_is_valid, post_validation=choice_post_validation )) kwargs['choice_to_option'] = should_not_evaluate(kwargs['choice_to_option']) return Field(**kwargs)