如何在Django模型上测试外键对象

时间:2018-10-16 04:34:53

标签: django testing django-rest-framework

我想在测试时在模型(Article)上传递外键对象(Category)。目前,我创建了category对象,然后将其变量传递给我的商品测试数据。我正在获取此错误{{1 }}我的目标是能够创建类别,然后在测试创建新文章时将其传递到文章测试数据中。关于如何正确实现这一点的任何想法?

base_test.py

TypeError: Object of type 'Category' is not JSON serializable.

test_article.py

class BaseTest:
    """
    Class contains data to be used for testing
    """

    def __init__(self):

        self.title = "How to tnnrain your flywwwwwwwwwwf"
        self.description = "Ever wondner how toddddd ddddwwwwd?"
        self.body = "You have to benlieve becausedddddddddcf"

        self.category = Category.objects.create(
            title='test category',
        )
        self.category.save()




       """ sample article data """
       self.create_article = {
            "article": {
                "title": self.title,
                "description": self.description,
                "body": self.body,
                "tags": ["reactjs"],
                "category": self.category


            }
        }

Models.py

from rest_framework.test import APIClient, APITestCase
from rest_framework import status
from ..test_authentication.test_base import BaseTest
from authors.apps.articles.models import Article, Category
from authors.apps.authentication.models import User

class ArticlesTest(APITestCase,BaseTest):
    def setUp(self):
        BaseTest.__init__(self)
        self.client = APIClient()

    """ method for testing creation of a new article """
    def test_create_article(self):
        self.create_login_user()
        response = self.client.post('/api/articles/',self.create_article, 
        format="json")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

2 个答案:

答案 0 :(得分:3)

由于您要使用JSON数据模拟HTTP POST,因此应传递类别ID:

,而不是传递python Category对象
class BaseTest:
"""
Class contains data to be used for testing
"""

    def __init__(self):

       self.title = "How to tnnrain your flywwwwwwwwwwf"
       self.description = "Ever wondner how toddddd ddddwwwwd?"
       self.body = "You have to benlieve becausedddddddddcf"

      self.category = Category.objects.create(
          title='test category',
         )
      # don't need to call save

    self.create_article = {
            "title": self.title,
            "description": self.description,
            "body": self.body,
            "tags": ["reactjs"],
            "category": self.category.id
      }

答案 1 :(得分:-1)

您应该将self.category转换为json。 它不是json变量