繁体   English   中英

Django单元测试用例

[英]Django Unit test cases

编写包含数据库更改(例如更改实体状态)的Django单元测试用例的最佳方法是什么? 例如:-我有不同的测试用例,其中实体的状态根据导致数据库级别更改的用户不同操作而改变。

什么是处理此类操作的测试用例的最佳方法?

def post(self, request, *args, **kwargs):
    if action==1:
        Entity.last_status= Entity.status
        Entity.status = 1
        Entity.save()
    elif action == 2:
        Entity.last_status = Entity.status
        Entity.status = 2
        Entity.save() 

等等...!!! -

嗨,Django有很多用于测试此目的的TestCase对象:

一个小类的例子:

import unittest
from django.test import Client

class SimpleTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_action_1(self):
        # Issue a POST request.
        response = self.client.post('/YOUR_POST_URL/', {'action': 1})
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)
        # Check the last entry
        last_entry = Entry.objects.last()
        self.assertEqual(last_entry.status, 1)

        response = self.client.post('/YOUR_POST_URL/', {'action': 2})
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)        
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)
        # Check the last entry
        last_entry = Entry.objects.last()
        self.assertEqual(last_entry.status, 2)   
        self.assertEqual(last_entry.last_status, 1)   

这个测试做什么?

他将创建一个空数据库来进行迁移,发出带有action=1参数的POST请求,我们检查状态为200(已执行且无错误),并检查数据库中现在是否有status=1Entry 现在,我们对参数action=2进行相同action=2并检查now statuslast_status

您可以按照MaximeK的答案中所述使用Django的测试Client ,或者另一种方法是直接调用视图。 您可以创建HttpRequest对象,并在调用它时将其传递到视图中。

from django.http import HttpRequest

def test_set_entity_status(self):
    # Set up the request
    request = HttpRequest()
    request.method = 'POST'
    request.POST['action'] = 1

    # Call the view function directly
    post(request)

    # Perform the assertions
    last_entity = Entity.objects.last()
    self.assertEqual(last_entity.status, 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM