【问题标题】:Understanding model in djangorestframwork unit tests了解 djangorestframwork 单元测试中的模型
【发布时间】:2018-11-24 19:23:23
【问题描述】:

我正在阅读django-rest-framework 中过滤器的单元测试。我尝试通过添加上述模型在另一个项目中本地模拟单元测试,但我的测试失败:django.db.utils.ProgrammingError: relation "blog_post" does not exist

tests.py

from django.test import TestCase
from django.db import models
from rest_framework import filters, serializers


class Post(models.Model):
    title = models.CharField(max_length=20)
    content  = models.TextField(max_length=255)

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

class TestPostFilter(TestCase):
    def setUp(self):
        Post.objects.create(title="A post title",content="some post content")

    def test_search(self):
        assert True

我知道要为模型创建相应的数据库表,我们必须运行 ./manage.py makemigrations blog./manage.py migrate blog,但上面的 example 添加一个虚拟模型仅用于测试目的。我看不到该模型迁移是如何执行的。可能在后台发生了很多事情。我的问题是这个模型是如何在测试数据库中创建的?

【问题讨论】:

    标签: django unit-testing django-rest-framework


    【解决方案1】:

    如果您查看 tests 包,它正在被设置为 Django 应用程序。注意tests 中的models.py,最重要的是conftest.py 文件中的def pytest_configure(configure) 函数。您需要执行相同的操作才能为测试环境定义模型。

    https://github.com/encode/django-rest-framework/blob/0e10d32fb122619a7977909536b642d09603192a/tests/models.py https://github.com/encode/django-rest-framework/blob/0e10d32fb122619a7977909536b642d09603192a/tests/conftest.py

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2015-06-24
      • 2017-12-19
      • 2010-12-26
      相关资源
      最近更新 更多