2013-10-21 45 views
0

我有我想測試的功能,允許用戶在主頁上添加記錄,然後查看保存頁面中的記錄 - 哪些工作時運行應用程序。self.client.login不保持登錄測試的持續時間

當最初運行下面的測試時,用戶已經登錄,但是當瀏覽器URL被指向/保存 時,用戶已經變成AnonymousUser。

這是有原因嗎?以下是我的代碼如下。

測試:

def test_viewing_logged_in_users_saved_records(self): 

    # A user logs in 
    self.client.login(username = 'testuser1', email='[email protected]', password = 'testuser1password') 
    self.browser.get(self.live_server_url) 

    # set up our POST data - keys and values are strings 
    # and post to home URL 
    response = self.client.post('/', 
           {'title': TestCase3.title 
           }) 

    # The user is redirected to the new unit test display page 
    self.assertRedirects(response, 'unittestcase/hLdQg28/') 

    # Proceeds to the page where they can see their saved records 
    self.browser.get(self.live_server_url + '/saved') 

    # The user can view the tests that they have saved 
    body = self.browser.find_element_by_tag_name('body') 
    self.assertIn(TestCase3.title, body.text) 

查看:

def home_post(request): 
    logging.warning('In home_post') 
    logging.warning(request.user) 
    if request.method == 'POST': 
     if request.user.is_authenticated(): 
    .... 

def saved(request): 
    logging.warning('In saved') 
    logging.warning(request.user) 
    if request.user.is_authenticated(): 
    .... 

記錄:

WARNING:root:In home_post 
WARNING:root:testuser1 

WARNING:root:In saved 
WARNING:root:AnonymousUser 

回答

4

你的第一個POST請求到家庭URL使用虛擬客戶端,您可以在已登錄。

您的請求/saved URL使用self.browser,這是沒有登錄。

它爲什麼要在同一個測試同時使用self.clientself.browser尚不清楚。如果您不需要在此測試中使用實時服務器,那麼我會在整個過程中使用self.client。對於你的例子中,你可以做:

response = self.client.get('/saved') 
self.assertContains(response, TestCase3.title) 

如果確實需要使用活的服務器,請參閱live server test case docs伐木的例子中使用的硒客戶端。

+0

謝謝,這是一個Django noobie有關登錄導致在同一測試中使用兩個混淆,現在它的工作! –