def test_policy_math(self, mock_points_earned_trials_count,
                         mock_points_earned_get_points_earned_trials_count,
                         GradingPolicyCls, params, trials_count, points_earned,
                         sequence, er):
        mock_points_earned_get_points_earned_trials_count.return_value = trials_count, points_earned
        mock_points_earned_trials_count.return_value = trials_count, points_earned

        POLICY_CLS_TO_NAME = {
            v: k
            for k, v in GRADING_POLICY_NAME_TO_CLS.items()
        }

        policy = GradingPolicy.objects.filter(
            name=POLICY_CLS_TO_NAME[GradingPolicyCls]).first()
        self.assertIsNotNone(policy)
        policy.params = params
        # pass sequence = None - this is a stub to not create a lot of objects in DB and test only math here
        if er and type(er) == type and issubclass(er, Exception):
            with pytest.raises(er):
                GradingPolicyCls(sequence=sequence, policy=policy)._calculate()
        else:
            grade = GradingPolicyCls(sequence=sequence,
                                     policy=policy)._calculate()
            self.assertEqual(grade, er)
            self.assertIsInstance(grade, (float, int))
Beispiel #2
0
class CollectionOrderForm(ModelForm):
    """
    Add collection in group form.
    """

    grading_policy_name = forms.ChoiceField(
        choices=((k, v) for k, v in GRADING_POLICY_NAME_TO_CLS.items()),
        required=True,
        widget=PolicyChoiceWidget)

    class Meta:
        """
        Inner class with metadata options for CollectionOrderForm.
        """

        model = CollectionOrder
        fields = ('collection', 'slug', 'engine', 'grading_policy_name',
                  'strict_forward', 'ui_option', 'ui_next')
        labels = {
            'ui_option': _('UI Option'),
            'ui_next': _('Additional NEXT Button')
        }
        help_texts = {
            'collection':
            _("You can choose the available collection or create a new Collection above."
              )
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        self.group = kwargs.pop('group')
        read_only = kwargs.pop('read_only') if 'read_only' in kwargs else False
        super().__init__(*args, **kwargs)
        self.fields['collection'].queryset = self.fields[
            'collection'].queryset.filter(owner_id=self.user.id)
        if read_only:
            self.fields['collection'].widget = HiddenInput()
            self.fields['collection'].widget.attrs['readonly'] = read_only

    def clean(self):
        super().clean()
        engine, policy = self.cleaned_data.get(
            'engine'), self.cleaned_data.get('grading_policy_name')

        engine_cls = engine.engine_driver
        policy_cls = GRADING_POLICY_NAME_TO_CLS.get(policy)

        if policy_cls is None:
            raise forms.ValidationError(
                {'grading_policy_name': ['Not correct policy']})

        required_engine = policy_cls.require.get('engine')

        if required_engine and not isinstance(engine_cls, required_engine):
            engine_err_msg = 'This Engine doesn\'t support chosen Policy. Please choose another policy or engine.'
            policy_err_msg = 'This policy can be used only with {} engine(s). Choose another policy or engine.'.format(
                ", ".join([
                    engine.__name__.strip('Engine')
                    for engine in required_engine
                ]))
            raise forms.ValidationError({
                'engine': [engine_err_msg],
                'grading_policy_name': [policy_err_msg]
            })
        return self.cleaned_data

    def save(self, **kwargs):
        self.instance.group = self.group
        self.instance.collection = self.cleaned_data['collection']
        self.instance.engine = self.cleaned_data['engine']
        self.instance.grading_policy = self.cleaned_data['grading_policy']
        self.instance.save()