Django test.py model object instance is limited to one test 测试

Django test.py model object instance is limited to one test

好吧,这很奇怪。这是我的有效代码:

test.py

from django.test import TestCase
from django.urls import reverse, resolve
from django.utils import timezone
import datetime

from ..models import Realtor, Listing, Contact
from ..views import listing

from django.test import override_settings
from PIL import Image
from io import BytesIO
from django.core.files import File
import tempfile

def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
    file_obj = BytesIO()
    image = Image.new("RGB", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)

class RealestateListingViewTest(TestCase):
    @override_settings(MEDIA_ROOT=tempfile.TemporaryDirectory(prefix='mediatest').name)
    def setUp(self):
        image_file = get_image_file
        Realtor.objects.create(name='sample_realtor', photo=get_image_file())
        Listing.objects.create(title='listing_sample', address='sample', realtor=Realtor.objects.get(pk=1), city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', photo_main=get_image_file(), photo_1=get_image_file(), photo_2=get_image_file(), photo_3=get_image_file(), photo_4=get_image_file(), photo_5=get_image_file(), photo_6=get_image_file())
        url = reverse('btre:listing', kwargs={'listing_id': 1})
        self.response = self.client.get(url)

    def test_listing_status_code(self):
        self.assertEquals(self.response.status_code, 200)

上面的代码有效,但每当我添加另一个测试时,比如:

    def test_listing_url_resolves_listing_view(self):
        view = resolve('/realestate/listing/1')
        self.assertEqual(view.func, listing)

我收到这个错误:

======================================================================
ERROR: test_listing_url_resolves_listing_view (realestate.tests.test_view_listing.RealestateListingViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\Storm\Dev\btre_project\realestate\tests\test_view_listing.py", line 35, in setUp
    Listing.objects.create(title='listing_sample', address='sample', realtor=Realtor.objects.get(pk=1), city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', photo_main=get_image_file(), photo_1=get_image_file(), photo_2=get_image_file(), photo_3=get_image_file(), photo_4=get_image_file(), photo_5=get_image_file(), photo_6=get_image_file())
  File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Storm\Envs\btre\lib\site-packages\django\db\models\query.py", line 408, in get
    self.model._meta.object_name
realestate.models.Realtor.DoesNotExist: Realtor matching query does not exist.

有人知道这是怎么发生的或为什么会发生吗?

另请注意,只要 TestCase 中只存在一个测试,它就可以工作 class 这就是为什么它对我来说很奇怪。

我也尝试过这种创建图像文件的方法:

class RealestateListingViewTest(TestCase):
    @staticmethod
    def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
        file_obj = BytesIO()
        image = Image.new("RGB", size=size, color=color)
        image.save(file_obj, ext)
        file_obj.seek(0)
        return File(file_obj, name=name)

你没有显示你正在测试的视图,但大概 1 中的 URL 是对象的 PK。

问题是虽然数据库在每次测试后都会被清除,但序列不会被重置。所以第二次在setUp方法中创建一个item,它的PK就不会是1.

您不应依赖特定的 ID。将创建的项目分配给一个变量并使用它:

    listing = Listing.objects.create(title='listing_sample', address='sample', realtor=Realtor.objects.get(pk=1), city='sample', state='sample', zipcode='1234', price='555555', bedrooms='1', bathrooms='1', garage='1', sqft='123', lot_size='123', photo_main=get_image_file(), photo_1=get_image_file(), photo_2=get_image_file(), photo_3=get_image_file(), photo_4=get_image_file(), photo_5=get_image_file(), photo_6=get_image_file())
    url = reverse('btre:listing', kwargs={'listing_id': listing.id})