简体   繁体   English

Django测试用户模型失败,但可在浏览器中使用

[英]Django testing user model fails but it works in the browser

I am new to testing and am trying to run the following tests but I get a 404 assertion error because the method that tries to reverse the url cannot find the category that had been created in the setUp method. 我是测试的新手,正在尝试运行以下测试,但收到404断言错误,因为尝试反向url的方法找不到在setUp方法中创建的类别 I can create categories in the browser using the superuser with no problem and the url responds with 200 status. 我可以毫无问题地使用超级用户在浏览器中创建类别 ,并且该URL响应为200状态。 Could you help me understand what I am doing wrong? 您能帮我了解我做错了什么吗?

Test: 测试:

from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth.models import User
from cataloger.models import Category

class CatalogerCategoriesTests(TestCase):

    def setUp(self):
       tom = User.objects.create_user(username="tom", password="1234567")
       Category.objects.create(name="cell phone", 
                            description="current cell phone types in the market.",
                            created_by=tom)

    def test_category_page_success_status_code(self):
       url = reverse('category_items', kwargs={'pk': 1})
       response = self.client.get(url)
       self.assertEquals(response.status_code, 200)

Fail: 失败:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/cataloger/tests_categories.py", line 48, in test_category_page_success_status_code
    self.assertEquals(response.status_code, 200)
AssertionError: 404 != 200

Models: 楷模:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User


class Category(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=300)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(null=True)
    created_by = models.ForeignKey(User, related_name="categories")

Views: 浏览次数:

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from cataloger.models import Category

def category_items(request, pk):
    category = get_object_or_404(Category, pk=pk)
    return render(request, 'category_items.html', {'category': category})

urls: 网址:

from django.conf.urls import url
from . import views

urlpatterns = [
        url(r'^cataloger/$', views.cataloger, name='cataloger'),
        url(r'^cataloger/categories/(?P<pk>\d+)/$', views.category_items, name='category_items')
    ]

The pk of the object might not always be 1 depending upon the test structure and DB. 根据测试结构和数据库,对象的pk可能并不总是1 The pk of the Category instance should be used explicitly. Category实例的pk应该明确使用。

from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth.models import User
from cataloger.models import Category

class CatalogerCategoriesTests(TestCase):
    def setUp(self):
        tom = User.objects.create_user(username="tom", password="1234567")
        self.category = Category.objects.create(
            name="cell phone", 
            description="current cell phone types in the market.",
            created_by=tom
        )

    def test_category_page_success_status_code(self):
        url = reverse('category_items', kwargs={'pk': self.category.pk})
        response = self.client.get(url)
        self.assertEquals(response.status_code, 200)

@Stuart Dines explains very well. @Stuart Dines解释得很好。 You should match pk for urls. 您应该将pk匹配为网址。

Or if you just want to know that model instance created well, just try self.assertIsInstance(...) 或者,如果您只是想知道模型实例创建得很好,只需尝试self.assertIsInstance(...)

def setUp(self):
   tom = User.objects.create_user(username="tom", password="1234567")
   category = Category.objects.create(name="cell phone", 
                        description="current cell phone types in the market.",
                        created_by=tom)

def test_if_category_instance_made(self):
    self.assertIsInstance(self.category, Category)

Also I recommend model mommy for easy testing django models. 我也推荐妈妈模型,以便于测试Django模型。 It automatically generate random model (also put test data possible) and make really easy to testing your model! 它会自动生成随机模型(还可以提供测试数据),并且非常容易测试模型!

This is example using model_mommy for your test code 这是使用model_mommy作为测试代码的示例

from model_mommy import mommy

class CatalogerCategoriesTests(TestCase):

    def setUp(self):
        self.tom = mommy.make("User")
        self.category = mommy.make("Category", user=self.user)

    def test_if_category_instance_made(self):
        self.assertIsInstance(self.category, Category)

    def test_category_page_success_status_code(self):
        url = reverse('category_items', kwargs={'pk': self.category.pk})
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM