2014-03-29 63 views
0

我正在測試我正在使用Python 3.2編寫的WSGI應用程序 我一直在尋找一種方法將會話cookie從一個請求傳遞到下一個請求。單元測試http會話cookie python3

的self.cli是http.client.HTTPConnection

的cookie是http.cookies.SimpleCookie

def testLogonCookie(self): 
    self.cli.connect() 
    self.cli.request("POST", '/login', b'user=GUI&pass=Junkie') 
    res = self.cli.getresponse() 
    heads = res.getheader('Set-Cookie') 
    print(heads) 
    txt = str(res.readall()) 
    self.assertGreater(txt.find('Lorum ipsum'), -1, 'testLogin') 
    head = {"HTTP_COOKIE": heads} 
    print(head) 

    ####Exception here 
    self.cli.request('GET', '/loggedon', head) 

    res = self.cli.getresponse() 
    txt = str(res.readall()) 
    print(txt) 
    self.assertGreater(txt.find('user=GUI_Junkie'), -1, 'testLogonCookie') 

第一打印軌跡是SID = 0422f293-58e4-45a9-ab07- a4881c7b98d0; expires = 2014-03-29 17:39:55.868140

第二個是{'HTTP_COOKIE':'SID = 0422f293-58e4-45a9-ab07-a4881c7b98d0;到期= 2014年3月29日17:39:55.868140' }

的例外,我得到的是TypeError: 'str' does not support the buffer interface

我懷疑我有解析getheader,並把它放在一個字典,但我不知道是否有一個更簡單的方法去實現它。最後,我只想將cookie從一個請求推送到另一個請求。

回答

0

請求調用是錯誤的。第三個參數是請求的主體。 request('GET', '/loggedon', headers=head)

def testLogonCookie(self): 
    self.cli.connect() 
    self.cli.request("POST", '/login', b'user=GUI&pass=Junkie') 
    res = self.cli.getresponse() 
    heads = res.getheader('Set-Cookie') 
    txt = str(res.readall()) 
    self.assertGreater(txt.find('Lorum ipsum'), -1, 'testLogin') 
    head = {'Cookie': heads} 
    self.cli.request('GET', '/loggedon', headers=head) 
    res = self.cli.getresponse() 
    txt = str(res.readall()) 
    self.assertGreater(txt.find('user=GUI_Junkie'), -1, 'testLogonCookie')