Django:创建模型的测试有效,但渲染模板的测试无效

时间:2019-06-22 02:43:43

标签: python django code-coverage

我正在学习测试,并且正在使用coverage软件包。

我在测试唯一视图时遇到问题,它向数据库查询今天的社论(如果不存在),它将返回昨天的社论。

def today_editorial(request):
    '''it does not handle the case when an editorial has not been created
    before more than 2 days '''

    editorials = Editorial.objects.all().order_by('-id') 
    tz = pytz.timezone('America/Bogota')
    today_date = datetime.now(tz).date()
    yesterday_date = today_date - timedelta(days=1)

    try:
        today_editorial = Editorial.objects.get(date = today_date)
        if today_editorial:
            return render(request, 'editorial/index.html', {'editorials': editorials, 'today_editorial': today_editorial})
    except:
        yesterday_editorial = Editorial.objects.get(date = yesterday_date)
        if yesterday_editorial:
            return render(request, 'editorial/index.html', {'editorials': editorials, 'yesterday_editorial': yesterday_editorial}) 

test_views.py

很好奇此测试不起作用,因为创建“社论”对象的测试有效。

对于此测试,我只是复制从test_models.py文件创建编辑对象的函数:

from django.test import TestCase
from django.test import TestCase
from editorial.models import Editorial
from editorial.views import *
from django.utils import timezone
from django.urls import reverse


# Create your tests here.

# views test
class EditorialTestViews(TestCase):

    def create_editorial(self, title="only a test", body="yes, this is only a test"):
        return Editorial.objects.create(title=title, body=body,
               url="https://www.google.com", image = "https://img.elcomercio.pe/files/article_content_ec_fotos/uploads/2019/06/19/5d0ae893b3287.jpeg",
               date=timezone.now())

    def test_today_editorial_view(self):
        e = self.create_editorial() #you've to have create todays editorial for the view to work
        url = "http://127.0.0.1:8000/editorial-del-dia"
        resp = self.client.get(url)
        self.assertEqual(resp.status_code, 200) 

错误消息:

$ coverage run manage.py test editorial/tests -v 2
Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
Operations to perform:
  Synchronize unmigrated apps: coverage, messages, staticfiles
  Apply all migrations: admin, auth, contenttypes, editorial, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying editorial.0001_initial... OK
  Applying sessions.0001_initial... OK
System check identified no issues (0 silenced).
test_editorial_creation (editorial.tests.test_models.EditorialTestModels) ... ok
test_today_editorial_view (editorial.tests.test_views.EditorialTestViews) ... ERROR

======================================================================
ERROR: test_today_editorial_view (editorial.tests.test_views.EditorialTestViews)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "D:\web_proyects\el_comecio_app\editorial\views.py", line 25, in today_editorial
    today_editorial = Editorial.objects.get(date = today_date)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\db\models\query.py", line 408, in get
    self.model._meta.object_name
editorial.models.Editorial.DoesNotExist: Editorial matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\web_proyects\el_comecio_app\editorial\tests\test_views.py", line 22, in test_today_editorial_view
    resp = self.client.get(url)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\test\client.py", line 535, in get
    response = super().get(path, data=data, secure=secure, **extra)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\test\client.py", line 347, in get
    **extra,
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\test\client.py", line 422, in generic
    return self.request(**r)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\test\client.py", line 503, in request
    raise exc_value
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\core\handlers\exception.py", line 34, in
inner
    response = get_response(request)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\web_proyects\el_comecio_app\editorial\views.py", line 29, in today_editorial
    yesterday_editorial = Editorial.objects.get(date = yesterday_date)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "d:\virtual_envs\el_comercio_app\lib\site-packages\django\db\models\query.py", line 408, in get
    self.model._meta.object_name
editorial.models.Editorial.DoesNotExist: Editorial matching query does not exist.

----------------------------------------------------------------------
Ran 2 tests in 0.074s

FAILED (errors=1)
Destroying test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
(el_comercio_app)

models.py

from django.db import models

# Create your models here.

class Editorial(models.Model):
    title = models.CharField(max_length=100)
    body = models.CharField(max_length=400)
    url = models.CharField(max_length=600)
    image = models.CharField(max_length=600)
    date = models.DateField()

    def __str__(self):
        return f"Editorial con id:  #{self.id}"

    def __repr__(self):
        return f"Editorial con id:  #{self.id}"

我的应用程序的结构是:

editorial
    |_managment
    |_migrations
    |_templates
    |_tests
      |___init__.py
      |_test_models.py
      |_test_views.py
    |_admin.py
    |_models.py
    |_views.py
    |_urls.py
el_comercio_app
static
staticfiles
manage.py

奖金:

我该怎么做才能不对测试的URL进行硬编码?

editorial / urls.py

from django.urls import path
from editorial import views
from django.contrib import admin

app_name = 'editorial'

urlpatterns = [
    path('admin', admin.site.urls),
    path("editorial-del-dia", views.today_editorial, name="today_editorial")
]

el_comercio_app / urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
     path("", include("editorial.urls", namespace='editorial')),
]

0 个答案:

没有答案