Django测试用户模型失败但它在浏览器中工作

问题描述 投票:0回答:2

我是测试的新手,我正在尝试运行以下测试但是我得到404断言错误,因为尝试反转url的方法无法找到在setUp方法中创建的类别。我可以使用超级用户在浏览器中创建类别而没有问题,并且url以200状态响应。你能帮我理解我做错了什么吗?

测试:

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)

失败:

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

楷模:

# -*- 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")

浏览次数:

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})

网址:

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')
    ]
python django unit-testing
2个回答
2
投票

根据测试结构和DB,对象的pk可能并不总是1。应明确使用pk实例的Category

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)

1
投票

@Stuart Dines解释得非常好。你应该匹配PK的网址。

或者,如果您只是想知道模型实例创建得很好,请尝试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)

另外,我推荐使用model mommy来轻松测试django型号。它可以自动生成随机模型(也可以使测试数据成为可能),并且可以非常轻松地测试模型!

这是使用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)
© www.soinside.com 2019 - 2024. All rights reserved.