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))
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): required_engine_names = ", ".join( [e.__name__.strip('Engine') for e in 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( required_engine_names, ) raise forms.ValidationError({ 'engine': [engine_err_msg], 'grading_policy_name': [policy_err_msg] }) return self.cleaned_data
def clean(self): super().clean() policy_name, params = self.cleaned_data.get( 'name'), self.cleaned_data.get('params') required_params = GRADING_POLICY_NAME_TO_CLS.get( policy_name).require.get('params', []) if required_params: for param in required_params: if not params or param not in params: raise forms.ValidationError( "Not all required parameters are set correctly.") return self.cleaned_data
def clean(self): super().clean() policy_name, params = self.cleaned_data.get('name'), self.cleaned_data.get('params') required_params = GRADING_POLICY_NAME_TO_CLS.get(policy_name).require.get('params') if required_params: if params is None: params = self.cleaned_data['params'] = {} for param, default in required_params.items(): if param not in params: params[param] = default continue # TODO(idegtiarov) `threshold` parameter validation is hardcoded. # It should be rewritten when some new parameter appears. if param == 'threshold': try: threshold = int(params[param]) except ValueError: threshold = default threshold = threshold if threshold > 0 else default params[param] = threshold return self.cleaned_data
def get_form_class(self): policy_cls = GRADING_POLICY_NAME_TO_CLS.get( self.request.GET.get('grading_policy'), None) if policy_cls is None: raise Http404("No such grading policy") return policy_cls.get_form_class()
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()