如何在django中编写get和post测试方法?

时间:2017-06-21 13:50:05

标签: python django unit-testing django-views django-testing

我是Django测试的新手,并尝试为视图编写测试函数,但我没有得到整个测试视图的东西,我看过很多例子,但似乎很难,我需要一个关于我写的东西的例子,以获得想法。 这是一个我想测试其帖子并得到的函数:

    def ForgetPasswordRegistry(self, request):
    forgetpassword = True
    if request.method == 'GET':
        if 'UserID' in request.session:
            forgetpassword = False
        return request, forgetpassword
    elif request.method == 'POST':
        email = request.POST['email']
        if self.IsUserExist(email):
            forget = models.ForgetPasswordRegistry()
            forget.UserID = self.GetUser(email)
            forget.Access = 1
            session = random.randint(999999999999999, 9999999999999999999999999999999999)
            forget.Session = str(session)
            link = 'http://127.0.0.1:8000/home/resetpassword/' + forget.Session
            self.SendEmail('Reset-Password', link, [forget.UserID.Email])
            forget.save()
            FeedBack = ' Check Your Mail You Got A Recovery Mail'
            AlertType = 'alert-success'
            return request, AlertType, None, FeedBack, None, None
        else:
            AlertType = 'alert-danger'
            ModalFeedBack = 'This Email Dose Not Exist'
            EmailErrors = 'This Email Dose Not Exist'
            return request, AlertType, forgetpassword, None, EmailErrors, ModalFeedBack

2 个答案:

答案 0 :(得分:1)

使用Django的测试客户端:https://docs.djangoproject.com/en/1.11/topics/testing/tools/#the-test-client

示例:

from django.test import Client, TestCase


class ViewTestCase(TestCase):
    def test_post_creation(self):
        c = Client()  # instantiate the Django test client
        response = c.get('/forgetpassword/')
        self.assertEqual(response.status, 200)

答案 1 :(得分:0)

不要让观点的概念混淆你!!基本上有一个python函数,你需要运用某些条件。

看起来有4个主要分支:

  • 不在会议中
  • GET in session
  • POST存在
  • POST不存在

所以应该至少有4种不同的测试。我会发布第一个因为它非常简单:

def ForgetPasswordRegistry(self, request):
forgetpassword = True
if request.method == 'GET':
    if 'UserID' in request.session:
        forgetpassword = False
    return request, forgetpassword

def test_forget_get_user_id_in_session(self):
    request = Mock(session={'UserID': 'here'}, method='GET')
    # instantiate your view class
    yourview = YourView()
    sefl.assertEqual(yourview.ForgetPasswordRegistry(request), (request, False))

后用户存在分支稍微复杂一点,因为测试需要考虑更多内容,并可能为以下内容提供存根实现:

  • SendEmail
  • 的getUser
  • models.ForgetPasswordRegistry()