如何在类内部测试方法

时间:2015-10-05 21:43:03

标签: python django unit-testing tdd

在想要为以下代码创建测试时需要帮助:

这里验证密码的长度,如果你尝试更改,并希望创建两个测试,其中传递new_password1 whith len> = 5和len< 5.

#forms.py
     class ValidatingPasswordChangeForm(auth.forms.PasswordChangeForm):
            def clean_new_password1(self):
                    password1 = self.cleaned_data.get('new_password1')
                    if len(password1) < 5:
                        raise forms.ValidationError("La contraseña debe tener 5 caracteres o más.")
                    return password1


#url.py
url(r'^password_change/$', 'django.contrib.auth.views.password_change',
        {'template_name': 'interface/change_password.html',
         'password_change_form': forms.ValidatingPasswordChangeForm,
         'post_change_redirect': views.success_password}, name="password_change")

这是我的测试但不知道如何模拟password1并为后来分配一个cumstom单词做一个断言。

#test
    def test_len_password_true(self):
            mock_password = mock.MagicMock()
            mock_self = mock.MagicMock({'cleaned_data':'changos'})
            with mock.patch.multiple('interface.forms.ValidatingPasswordChangeForm.clean_new_password1', password1="cosa" ):
                from interface.forms import ValidatingPasswordChangeForm
                ValidatingPasswordChangeForm().clean_new_password1(mock_self)
                #context = mock_self.call_args[0][3]
                #print context

1 个答案:

答案 0 :(得分:0)

这是我的测试和工作,如果有人可以贡献输入我会很感激

class test_password(unittest.TestCase):
    """ Contiene los test para la funcionalidad de contraseña.
    """
    def test_success_password(self):
        mock_render = mock.MagicMock()
        mock_request = mock.MagicMock()
        with mock.patch.multiple('interface.views', render=mock_render):
            from interface.views import success_password
            success_password(mock_request)
            context = mock_render.call_args[0][2]
            self.assertEqual(context['message']['data'],
                             'Cambio exitoso de contrase\xc3\xb1a')

    def test_len_password_true(self):
        """llamado al método de validación debe devolver la misma
        contraseña.
        """
        mock_auth_form = mock.MagicMock()
        from interface.forms import ValidatingPasswordChangeForm
        form = ValidatingPasswordChangeForm(mock_auth_form)
        form.cleaned_data = {'new_password1': 'hola5'}
        self.assertEquals(form.clean_new_password1(), 'hola5')

    def test_len_password_error(self):
        """llamado al método de validación con una contraseña, de menos de 5
        caracteres, debe levantar un error de validación.
        """
        mock_auth_form = mock.MagicMock()
        from interface.forms import ValidatingPasswordChangeForm
        form = ValidatingPasswordChangeForm(mock_auth_form)
        form.cleaned_data = {'new_password1': 'hol4'}
        with self.assertRaises(forms.ValidationError):
            form.clean_new_password1()