The test client
test client是一個python類,來模擬一個簡單的“啞”瀏覽器,允許你來測試你的view函數.你可以使用test client完成下列事情:
1.模擬"Get"和"Post"請求,觀察響應結果--從HTTP(headers,status codes)到頁面內容.
2.檢查重定向鏈(如果有的話),在每一步檢查URL和status code。
3.用一個包括特定值的模板context來測試一個request被Django模板渲染。
>>> from django.test.client import Client >>> c = Client() >>> response = c.post('/login/', {'username': 'john', 'password': 'smith'}) >>> response.status_code 200 >>> response = c.get('/customer/details/') >>> response.content '<!DOCTYPE html...'
使用django.test.client.Client的實例來使用test client。
注意:請求網頁時,使用path而不是整個domain。
>>> c.get('/login/')
是正確的。
>>> c.get('http://www.example.com/login/')
是錯誤的。
test client不適合操作不是由Django建立的網站.所以,請求其它網頁時,請使用python的標准庫--urllib或者urllib2.
為了解析URl,test client使用由ROOT_URLCONF(settings.py)指定的URLconf。
默認情況下,test client會忽略CSRF檢查,如果要強制進行CSRF檢查,可以
csrf_client = Client(enforce_csrf_checks=True)
Making Requests
使用django.test.client.Client()來執行請求。
class Client(enforce_csrf_checks=False, **defaults)
可以使用關鍵字參數來指定默認的請求報頭:
c = Client(HTTP_USER_AGENT='Mozilla/5.0')
記得在USER_AGENT前加HTTP_。
Client實例具有以下方法:
get(path, data={}, follow=False, **extra)
執行一個GET請求並返回Response對象。
>>> c = Client() >>> c.get('/customers/details/', {'name': 'fred', 'age': 7})
相當於向以下url執行GET:
/customers/details/?name=fred&age=7
extra關鍵字參數可用作請求報頭:
>>> c = Client() >>> c.get('/customers/details/', {'name': 'fred', 'age': 7}, ... HTTP_X_REQUESTED_WITH='XMLHttpRequest')
當然也可以將查詢字符對編碼后加入url:
>>> c = Client() >>> c.get('/customers/details/?name=fred&age=7')
data參數的優先級在編碼后的url之上。
如果將follow設置為True,client會追蹤任何重定向,返回的response有redirect_chain屬性,包括所有重定向過程中的url和狀態碼組成的元祖列表。
如果有個URL /redirect_me/ 重定向向 /next/, 再重定向向 /final/:
>>> response = c.get('/redirect_me/', follow=True) >>> response.redirect_chain [(u'http://testserver/next/', 302), (u'http://testserver/final/', 302)]
post(path, data={}, content_type=MULTIPART_CONTENT, follow=False, **extra)
執行一個POST請求並返回response對象,data參數為POST數據。
如果提供content_type參數(例如 text/xml),數據會被作為報頭中Content-Type的類型進行POST上傳。
如果不提供content_type參數,數據會被作為multipart/form-data類型上傳。
為一個參數提交多個多個值時--比如選住<select multiple>域的多個值--這些值可以是列表或者元組.舉例來說,提交choice域的三個被選中的值:
{'choices': ('a', 'b', 'd')}
上傳文件:
>>> c = Client() >>> with open('wishlist.doc') as fp: ... c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})
文件的名字'attachment'是不相關的,取決於你處理文件的代碼。
如果同一個文件要post多次,注意每次post都要恢復文件的指針,最簡單的方法就是將文件關閉再重新打開。
注意文件要以正確的方式被打開以便於讀取,如果文件是binary data,例如讀取img時,要將打開模式設為rb。
post的路徑中也可以包含查詢字符對:
>>> c.post('/login/?visitor=true', {'name': 'fred', 'passwd': 'secret'})
這樣既會通過post上傳data數據,也向GET確定visitor=True。
options(path, data='', content_type='application/octet-stream', follow=False, **extra)
做OPTIONS請求,對測試REST接口很有用。data被用作請求的主體。
put(path, data='', content_type='application/octet-stream', follow=False, **extra)
做PUT請求,測試RESTful接口。
patch(path, data='', content_type='application/octet-stream', follow=False, **extra)
做PATCH請求,測試RESTful接口。
delete(path, data='', content_type='application/octet-stream', follow=False, **extra)
做DELETE請求,測試RESTful接口。
login(**credentials)
如果使用django的用戶驗證系統,可用login方法進行測試。
>>> c = Client() >>> c.login(username='fred', password='secret')
登陸成功的話,返回True。
使用之前,當然要創建一個用戶。由於測試數據庫使用的是單獨的數據庫,原先數據庫中的用戶是不能用於測試的。
設置密碼時,不能用user的密碼屬性進行設置,而是用set_password()方法設置正確的哈希密碼,或者使用create_user()方法創建一個帶哈希密碼的用戶。
logout()
登出。
Testing Responses
client的get和post方法都返回response對象,和HttpResponse對象是不同的。
class Response具有以下屬性:
client:the test client
content:response的主體,string類型,是view render后的頁面的最終內容,或者是錯誤信息。
context:用來渲染模板的context實例。如果頁面使用了多個模板,那context就會是Context Object列表.它們的排序方式就是它們被渲染的順序。
>>> response = client.get('/foo/') >>> response.context['name'] 'Arthur'
request:用於請求的數據。
status_code:狀態碼。
templates:被用來渲染最終的content的Template實例列表.template.name可以得到template的文件名,如果template是由文件載入的話(如 'admin/index.html')。那template就會是Template列表,它們的排序方式就是它們被渲染的順序.
response也可以當做字典來查詢Http header:
response['Content-Type']
Exceptions
如果你將TestClient指向了由view函數raise的異常,那這個異常在test case里是可見的.你可以使用標准的try...except塊或者assertRaises()來測試它們.對test client唯一不可見的異常是Http404,PermissionDenied和SystemExit。django會在內部捕捉這些異常並返回合適的response.這種情況下,你可以查看下你的response.status_code.
Persistent state
如果一個response返回了一個cookie,那么這個cookie就會被存儲在test client里,並被其后的所有get()和post()傳送.如果你想要終止這個cookie,你可以新建一個Client實例,或者手動刪除它。
一個test client具有兩個存儲持久化狀態信息的屬性:
Client.cookies
一個python SimpleCookie對象,存儲cilent的所有cookie。
Client.sessions
包含session信息的類字典對象。
如果要修改一個session並且存儲,首先將session存儲在變量中:
def test_something(self): session = self.client.session session['somekey'] = 'test' session.save()
一個使用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)
Test cases的一些功能
默認的test client
每個django.test.*TestCase的test case實例都會訪問django test client,所以Client可以不用實例化,而直接用self.client訪問:
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)
Fixture loading
如果數據庫里沒有數據,那么對於一個基於數據庫的網站來說,test case並無多大的用處.為了給測試數據庫加入測試數據更方便,django提供了載入fixtures的方法.
fixture是一系列的數據集合,django知道如何將它導入數據庫。
創建fixture最直接的方法就是使用manage.py dumpdata.當然,這假設你的實際數據庫里已經有數據了.
注意:
如果你運行過manage.py syncdb命令,那么你已經使用過fixture了--只是你不知道而已。當你使用syncdb去創建數據庫時,會創建一個叫initial_data的fixture。
其他名字的Fixture可以通過manage.py loaddata命令手動安裝.
一旦建立了一個fixture,並將它放在了某個django app的fixtures目錄中,你就可以在你的測試類里使用它了:
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()
這是具體發生的過程:
1. 在setup()運行前,django會清空數據庫,相當於你執行了syncdb。
2.然后,所有的fixture會被安裝.在例子中,django會安裝任何一個名字為mammals的JSON格式的fixture和名為birds的fixture數據。
Assertions
除了python中的assertEqual()和assertTrue()外,django的TestCase還提供了幾個額外的assert方法。
assertContains(response, text, count=None, status_code=200, msg_prefix='', html=False)
斷言response是否與status_code和text內容相應。將html設為True會將text作為html處理。
assertJSONEqual(raw, expected_data, msg=None)
斷言Json片段raw和expected_data是否相當。