简体   繁体   English

Django test.py model object 实例仅限一次测试

[英]Django test.py model object instance is limited to one test

Okay this is pretty strange.好吧,这很奇怪。 This is my code that works:这是我的有效代码:

test.py测试.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)

The above code works but whenever I add another test to the mix, like:上面的代码有效,但每当我添加另一个测试时,比如:

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

I get this error:我收到此错误:

======================================================================
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.

Anyone have an idea how or why this is happening?任何人都知道如何或为什么会发生这种情况?

Also note that it works as long as there is only one test existing in the TestCase class which is why it is very strange to me.另请注意,只要 TestCase class 中只存在一个测试,它就可以工作,这就是为什么它对我来说很奇怪。

Also I have tried this method for the image file creation:我也尝试过这种方法来创建图像文件:

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)

You haven't shown the view that you're testing, but presumably the 1 in that URL is the PK of the object.您还没有显示您正在测试的视图,但推测 URL 中的1是 object 的 PK。

The issue is that although the database is cleared after every test, sequences are not reset.问题是虽然每次测试后数据库都会被清除,但序列并没有被重置。 So the second time you create an item in the setUp method, its PK will not be 1.所以第二次在setUp方法中创建一个item,它的PK就不会是1了。

You shouldn't rely on specific IDs.您不应该依赖特定的 ID。 Assign the created item to a variable and use it:将创建的项目分配给变量并使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM