【问题标题】:How to test views in Django?如何在 Django 中测试视图?
【发布时间】:2021-06-21 18:25:10
【问题描述】:

我尝试在 django 应用程序中创建对我的视图的测试,在我的 setUp 方法中我想创建新对象,然后将此对象的 id 传递给 reverse('edit') 以测试传递一个 id,就像我在我的urls,代码如下:

test_views.py

    def setUp(self):
        self.client = Client()
        self.edit = reverse('edit', args=['id'])
        self.id = Employee.objects.create(
            econtact='testContact',
            eemail='test@tset.pl',
            ename='testName'
        ).id

网址

urlpatterns = [
    path('edit/<int:id>', views.edit, name="edit"),
]

型号

class Employee(models.Model):
    ename = models.CharField(max_length=100)
    eemail = models.EmailField()
    econtact = models.CharField(max_length=15)

谁能告诉我为什么,在运行这个测试用例后,我的控制台抛出了我:

django.urls.exceptions.NoReverseMatch: Reverse for 'edit' with arguments '('id',)' not found. 1 pattern(s) tried: ['edit/(?P<id>[0-9]+)$']

感谢您的帮助!

【问题讨论】:

    标签: python django unit-testing testing


    【解决方案1】:

    reverse 中的 args=['id'] 没有多大意义,因为这意味着您有一个 URL,其中字符串 'id' 是主键,而不是存储在名为 @987654325 的变量中的 int @。

    因此,您应该使用以下方法设置测试:

    def setUp(self):
        self.client = Client()
        self.id = Employee.objects.create(
            econtact='testContact',
            eemail='test@tset.pl',
            ename='testName'
        ).id
        self.edit = reverse('edit', args=[self.id])

    【讨论】:

    • 我尝试编译器抛出:location = "django_testid://" + str(test.id()) TypeError: 'int' object is not callable
    • test.id() 没有意义,它是test.id...,因此是location = f'django_testid://{ test.id }'
    • 测试仍然失败,我认为问题出在TypeError: 'int' object is not callable
    • 因为这个str(test.id())来自内部python函数
    • @methodinvocation:请使用 full 回溯编辑问题。
    猜你喜欢
    • 2022-10-13
    • 2021-08-26
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 2021-12-19
    相关资源
    最近更新 更多