Django单元测试

2018-10-15  本文已影响0人  null_fca6

为什么需要自动化测试

测试覆盖率

Doctest

下面是一个样例

def factorial(n): 
"""Return the factorial of n, an exact integer >= 0.

>>> [factorial(n) for n in range(6)] 
[1, 1, 2, 6, 24, 120] 
>>> factorial(30) 265252859812191058636308480000000 
>>> factorial(-1) 
Traceback (most recent call last): 
    ...
 ValueError: n must be >= 0 
"""

import math 
if not n >= 0: 
    raise ValueError("n must be >= 0") 
result = 1 
factor = 2 
while factor <= n: 
    result *= factor 
    factor += 1 
return result
if __name__ == "__main__": 
    import doctest 
    doctest.testmod()

Unittest

如何使用Unittest

下面是一个样例

class ProductTestCase(unittest.TestCase): 
    def testIntegers(self): 
        x = 3 
        y = 4 
        p = my_math.product(x, y) 
        self.failUnless(p == x*y, 'Integer␣multiplication␣failed') 
if __name__ == '__main__': unittest.main()
*************************Wrong************************* 
F 
======================================================== 
FAIL: testIntegers (__main__.ProductTestCase) 
-------------------------------------------------------
Traceback (most recent call last): 
                File "test_my_math.py", line 17, in testIntegers self.failUnless(p == x*y, 'Integer␣multiplication␣ failed') 
AssertionError: Integer multiplication failed 
-------------------------------------------------------
Ran 1 tests in 0.001s 
FAILED (failures=1)

*************************Correct************************* 
. 
-------------------------------------------------------
Ran 1 tests in 0.001s 
OK

源码检查

Django单元测试

讲了这么多python的单元测试,那如何进行Django的单元测试呢?

class TestDefault(TestCase):

    def setUp(self):
        # 设置配置
        settings.IGNORE_WECHAT_SIGNATURE = True

        # user1 => not bind
        # user2 => bind
        User.objects.create(open_id='abc')
        User.objects.create(open_id='a', student_id='2016013265')

        # textMsgs => 用户一般可能输入(成功)
        self.textMsgs = ['balabala', 'gg', '抢火车票']

    # 是否返回帮助
    def is_default(self, content):
        pattern = '对不起,没有找到您需要的信息:('
        return content.find(pattern) != -1

    def test_text(self):
        users = User.objects.all()

        for user in users:
            for textMsg in self.textMsgs:
                fromUser = user.open_id
                curTime = str(getTimeStamp(datetime.datetime.now()))
                msgId = str(random.randint(0, 99999)) + curTime
                data = getTextXml(fromUser, curTime, textMsg, msgId)

                response = self.client.post(
                    path='/wechat/',
                    content_type='application/xml',
                    data=data
                )

                content = str(response.content.decode('utf-8'))
                self.assertEqual(self.is_default(content), True)

python manage.py test

运行测试的时候,测试程序会在所有以test开头的文件中查找所有的test cases(inittest.TestCase的子类),自动建立测试集然后运行测试。(注意是所有app的test文件,包括子目录中的)

python manage.py test

运行结果:


image.png

python manage.py xxx.tests

python manage.py xxx.TestDefault

python manage.py xxx.TestDefault.testxxx/py

python manage.py test–pattern=”tests_*.py”

python -Wall manage.py test

数据库

测试是需要数据库的,django会为测试单独生成数据库。不管你的测试是否通过,当你所有的测试都执行过后,这个测试数据库就会被销毁。

为了保证所有的测试都从干净的数据库开始,执行顺序如下:

加速测试

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.MD5PasswordHasher',
)

travis CI与django的单元测试

script: 
    - python manage.py test

参考

上一篇 下一篇

猜你喜欢

热点阅读