Django 模型单元测试

Django model unit test

我开始学习 Django,我在单元测试中遇到了问题,我试图寻找问题所在,但我无法确定我的代码中的问题所在。如果有人可以确定我的代码中存在什么问题,或者您是否可以给我一些建议?

错误:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_create_user (user_api.tests.ModelUseProfileTest)
Users can register
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/vagrant/src/api/user_api/tests.py", line 26, in test_create_user
    user = UserProfile.objects.get(id=1)
  File "/home/ubuntu/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/ubuntu/.virtualenvs/venv/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get
    self.model._meta.object_name
user_api.models.DoesNotExist: UserProfile matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 0.040s
FAILED (errors=1)
Destroying test database for alias 'default'...

我的测试:

from django.test import TestCase
from rest_framework import status
from django.core.urlresolvers import reverse
from .models import UserProfile

# Create your tests here.
class ModelUseProfileTest(TestCase):
 """ Test class define the test suite for the UserProfile model."""

    def test_create_user(self):
    """Users can register"""

    # Create an instance of a GET request.
    response = self.client.post("/api/v1/register/", {
      "name": "Walter",
      "lasT_name": "White",
      "email": "heisenberg@email.com", 
      "password": "secret", })

    user = UserProfile.objects.get(id=1)

    self.assertEqual(user.name, "Walter")
    self.assertEqual(user.last_name, "White")
    self.assertEqual(user.email, "heisenberg@email.com")
    self.assertEqual(response.status_code, 201)

我的模型:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager

class UserProfileManager(BaseUserManager):
      """Helps Django work with our custom user model"""
      def create_user(self, name, last_name, email, password=None):
            """Create a new user profile object."""
            if not email:
                  raise ValueError('Users must have an email address.')

            if not name:
                  raise ValueError('Users must have an name.')

            if not last_name:
                  raise ValueError('Users must have an last name.')

            email = normalize_email(email)
            user = self.model(name=name, last_name=last_name, email=email)
            user.set_password(password)
            user.save(using=self._db)

            return user

      def create_superuser(self, name, last_name, email, password=None):
            """Create and saves a new superuser with given details."""

            user = self.create_user(name, last_name, email, password)
            user.is_superuser = True
            user.is_staff = True
            user.save(using=self._db)

            return user

class UserProfile(AbstractBaseUser, PermissionsMixin):
      """Represents a "user profile" inside our system."""

      name = models.CharField(max_length=500)
      last_name = models.CharField(max_length=500)
      email = models.EmailField(max_length=255, unique=True)
      is_active = models.BooleanField(default=True)
      is_staff = models.BooleanField(default=False)
      objects = UserProfileManager()
      USERNAME_FIELD = 'email'
      REQUIRED_FIELDS = ['name', 'last_name']

      def get_full_name(self):
        """Used to get a users full name."""

          return self.name

      def get_short_name(self):
        """Used to get a users short name."""

          return self.name

      def __str__(self):
        """Django uses this when it needs to convert the object to a string"""

          return self.email

虽然测试客户端每次都从一个空白数据库开始,但没有理由假设主键是1;在每个 运行 之后清空表时,不会重置序列。您应该只查询第一项,而不是显式获取 pk=1:

 user = UserProfile.objects.first()