def my_func(a_list, idx): return a_list[idx] import unittest class MyFuncTestCase(unittest.TestCase): def testBasic(self): a = ['larry', 'curly', 'moe'] self.assertEqual(my_func(a, 0), 'larry') self.assertEqual(my_func(a, 1), 'curly')二、django的测试--django.utils.unittest库、django.test.client库。
from django.utils import unittest from myapp.models import Animal class AnimalTestCase(unittest.TestCase): def setUp(self): self.lion = Animal.objects.create(name="lion", sound="roar") self.cat = Animal.objects.create(name="cat", sound="meow") def test_animals_can_speak(self): """Animals that can speak are correctly identified""" self.assertEqual(self.lion.speak(), 'The lion says "roar"') self.assertEqual(self.cat.speak(), 'The cat says "meow"')(2)django.test.client库
from django.utils import unittest from django.test.client import Client class SimpleTest(unittest.TestCase): def setUp(self): # Every test needs a client. self.client = Client() def test_details(self): # Issue a GET request. response = self.client.get('/customer/details/') # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # Check that the rendered context contains 5 customers. self.assertEqual(len(response.context['customers']), 5)或者更高级的,直接用from django.test.TestCase
from django.test import TestCase class SimpleTest(TestCase): def test_details(self): response = self.client.get('/customer/details/') self.assertEqual(response.status_code, 200) def test_index(self): response = self.client.get('/customer/index/') self.assertEqual(response.status_code, 200)三、数据库使用
如果你测试时候还需要初始化数据库,那TestCase.fixtures帮你了。
而且,django在测试的时候,会帮你创建一个新的数据库名为:test_原有数据库名。这样可以防止真实数据库被弄脏。
你可以这样初始化你的数据库:from django.test import TestCase from myapp.models import Animal class AnimalTestCase(TestCase): fixtures = ['mammals.json', 'birds'] def setUp(self): # Test definitions as before. call_setup_methods() def testFluffyAnimals(self): # A test that uses the fixtures. call_some_test_code()那有人就问了:mammals.json怎么来的呢?格式是什么呢?其实这个文件是用python manage.py dumpdata命令来的,有关这个命令的文档请google之。文件格式大概如下:
[ { "pk": 1, "model": "apps.animal", "fields": { "status": 1, "gmt_modified": "2015-07-06T14:05:38", "gmt_created": "2015-07-06T14:05:38", "alive": 1, "info": "" } }, { "pk": 2, "model": "apps.animal", "fields": { "status": 0, "gmt_modified": "2015-07-06T14:05:53", "gmt_created": "2015-07-06T14:05:53", "alive": 1, "info": "" } } ]其实,django.test这个包还有很多其他的功能,不能一一列举,详细可以看django官方文档。
版权声明:本文为博主原创文章,未经博主允许不得转载。
python第三方库系列之十八--python/django test库
原文地址:http://blog.csdn.net/wenph2008/article/details/46861569