django test

django的单元测试

官方文档:https://docs.djangoproject.com/en/dev/topics/testing/

相对于自己封装urllib/urllib2/request做测试类有以下特点:

1. 独立的测试数据库(与生产库分离,因此更利于测试人员做测试而不影响正式数据)

  代价就是,测试数据要自己再通过代码造一遍。

    运行完了清理数据。删掉测试库(默认行为, 不要删除数据库添加 --keepdb选项)。

2. 通过python manage.py test module.tests  来运行时,自动集成了相关的django测试web, 运行完了关闭。 如此可通过django.test.Client 模拟一些用户页面操作。

tests.py (demo)

from django.test import TestCase, Client
from django.contrib.auth import get_user_model

class MyTest(TestCase):
    def setUp(self):
        USER_MODEL = get_user_model()
        user = USER_MODEL.objects.create(email='yuwentao@xxx.com')
        user.set_password('123456')
        user.save()
        if not hasattr(self, 'client'):
            self.client = Client()

        setattr(self.client, 'user', user)
        self.client.login(email='yuwentao@xxx.com', password='123456')

    def test_click_xxx(self):
        self.client.get("/xxx/1")

django.test.Client更多文档看这里:https://docs.djangoproject.com/en/dev/topics/testing/tools/

3. 运行: python manage.py test myapp.tests

原文地址:https://www.cnblogs.com/Tommy-Yu/p/6170274.html