Django单元测试之Client

首先上一个简单的测试用例(添加用户,然后利用此用户登陆测试并添加一个Q到系统中)

...
from myapp.models import Question,User
from django.test import TestCase
...

class QATest(TestCase):
    def setUp(self):
        User.objects.create(username="goood", password=hashlib.md5("Lockey23").hexdigest(), first_name="Young",
                            last_name="Cheng", department="SRS", email="[email protected]", member_of="SRS-BI",
                            team="SRS-BI", role="admin")
        self.client.post('/account/login/', {'username': 'goood', 'password': 'Lockey23'})
        user = User.objects.get(nt_id="goood")
        Question.objects.create(create_nt_id=user, question_text="test question")

The test client is a Python class that acts as a dummy Web browser, allowing you to test your views and interact with your Django-powered application programmatically.

上面的例子中已经使用了两个最常用的方法GET和POST(PUT和DELETE与POST基本格式相同),请记住请求方式以及数据格式!

然后下面介绍一个clent的特性:

The test client is stateful. If a response returns a cookie, then that cookie will be stored in the test client and sent with all subsequent get() and post() requests.
意思client是状态保持的,所以如果我们需要测试登陆系统中的多个API的话只需要登陆一次然后就可以顺畅的去测试其他的接口了;所以一般对于需要登陆之后才能操作的接口我们会将登陆操作放到setUp函数中去执行,这样后面的所有测试方法都可以使用这一次的登录状态来进行接口测试了
>>> res = c.get('/account/uprofile/')
>>> res.status_code
200
>>> dir(res)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_charset', '_closable_objects', '_container', '_content_type_for_repr', '_convert_to_charset', '_handler_class', '_headers', '_reason_phrase', 'charset', 'client', 'close', 'closed', 'content', 'context', 'cookies', 'csrf_cookie_set', 'delete_cookie', 'flush', 'get', 'getvalue', 'has_header', 'items', 'json', 'make_bytes', 'next', 'readable', 'reason_phrase', 'request', 'resolver_match', 'seekable', 'serialize', 'serialize_headers', 'set_cookie', 'set_signed_cookie', 'setdefault', 'status_code', 'streaming', 'tell', 'templates', 'writable', 'write', 'writelines', 'wsgi_request']
>>> res.cookies
'esgRwIIJG22pcryrZf7aGaEBIl9iCf5h6kId3lK90Gej9B71OpAO7Al2iS9abYzn' sessionid='yuvc0flduilh0tsd4hcpwymq750kn496'>
>>> res.session
从上面的例子我们可以看到client的一些方法属性,以及对于状态保持有力的证明res.cookies

下面看一些常用的测试方法以及:

    def test_get_q_a_list(self):
        res = self.client.post('/get_q_a_list', json.dumps(test_json_data['search']),content_type="application/json")
        self.assertEqual(res.status_code, 200)#测试返回值是否登录200,注意这里有个属性调用res.status_code
>>> from django.test import TestCase
>>> dir(TestCase)
['assertAlmostEqual', 'assertAlmostEquals', 'assertContains', 'assertCountEqual', 'assertDictContainsSubset', 'assertDictEqual', 'assertEqual', 'assertEquals', 'assertFalse', 'assertFieldOutput', 'assertFormError', 'assertFormsetError', 'assertGreater', 'assertGreaterEqual', 'assertHTMLEqual', 'assertHTMLNotEqual', 'assertIn', 'assertInHTML', 'assertIs', 'assertIsInstance', 'assertIsNone', 'assertIsNot', 'assertIsNotNone', 'assertItemsEqual', 'assertJSONEqual', 'assertJSONNotEqual', 'assertLess', 'assertLessEqual', 'assertListEqual', 'assertMultiLineEqual', 'assertNotAlmostEqual', 'assertNotAlmostEquals', 'assertNotContains', 'assertNotEqual', 'assertNotEquals', 'assertNotIn', 'assertNotIsInstance', 'assertNotRegex', 'assertNotRegexpMatches', 'assertNumQueries', 'assertQuerysetEqual', 'assertRaises', 'assertRaisesMessage', 'assertRaisesRegex', 'assertRaisesRegexp', 'assertRedirects', 'assertRegex', 'assertRegexpMatches', 'assertSequenceEqual', 'assertSetEqual', 'assertTemplateNotUsed', 'assertTemplateUsed', 'assertTrue', 'assertTupleEqual', 'assertXMLEqual', 'assertXMLNotEqual','setUp', 'skipTest', 'tearDown', 'tearDownClass']

所有以assert开头并且测试比较结果、是否为真的都是常用的方法

一个很实用的属性方法json()

假如说你的post请求返回了一个json数据,那么我们就需要这样来接受并做数据解析了:

    def test_login_success(self):
        res = cli.post('/account/login/', {'username': 'goood', 'password': 'Lockey23'})
        self.assertEqual(res.json()['result'], 'Success')

你可能感兴趣的:(python,django)