[英]Django testing not getting connected to the database
我是django的新手。 在我的第一個django應用程序中,我正在測試其中一個視圖以檢查登錄。 這是我的看法:
from testprjct.testapp.forms import LoginForm_form
from django.contrib import auth
def check_login(request):
if request.method == 'POST':
form = LoginForm_form(request.POST)
if request.POST and form.is_valid():
username = request.POST.get('username', '')
password = request.POST.get('password', '')
# I am hard-coding the credentials here just for testing
user = auth.authenticate(username = 'test123', password = 'qwerty')
if user is not None and user.is_active:
auth.login(request, user)
.....
當我運行服務器並嘗試從前端登錄時,此視圖工作正常。 但是在為此視圖執行測試用例時失敗。 這是我針對該視圖的測試代碼:
from testprjct.testapp.models import loginform
class ViewTests(TestCase):
def setUp(self):
loginform.objects.create(username='test123', password='qwerty')
def test_login(self):
response = self.client.get('/login/')
self.assertEqual(response.status_code, 200)
response = self.client.post('/login/', {"username": "test123", "password": "qwerty"})
print response
self.assertEqual(response.status_code, 302)
通過給出登錄詳細信息無效的消息,該操作始終返回200 status_code(不重定向至成功頁面)。
當我在登錄頁面中測試忘記密碼鏈接時,也會出現同樣的問題。 當提供有效的電子郵件ID時,它在前端可以正常工作。 但是從我的測試用例中,即使我提供與前端提供的電子郵件ID相同的電子郵件ID,也始終會給我該錯誤消息:電子郵件ID沒有關聯的用戶帳戶。
有什么建議嗎? 我已經花了很多時間來解決這個問題。
Django建立了一個新的數據庫進行測試,因此它不會訪問您現有的數據。 您需要在測試本身或setUp
方法中創建所需的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.