PUT 单元 TestCase 上的 AssertionError

AssertionError on PUT unit TestCase

提问人:Hunes 提问时间:6/27/2023 最后编辑:Hunes 更新时间:6/27/2023 访问量:21

问:

我正在为 PUT 方法创建一个单元测试,其目的是创建新的数据库条目。问题似乎是我无法以正确的格式检索保存的字段字符串。结果字符串用方括号括起来。 故障部分:tests.py

        def test_create_task(self):
        self.client.login(username='user1', password='password1')
        data: dict[str, str] = {
            'name': 'Nowe zadanie',
            'description': 'Nowy opis',
            'status': 'Nowe',
            'username': 'user1',
        }
        response = self.client.post('/api/tasks/', data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Task.objects.count(), 4)
        self.assertEqual(Task.objects.last().name, 'Nowe zadanie')
        self.assertEqual(Task.objects.last().description, 'Nowy opis')
        self.assertEqual(Task.objects.last().status, 'Nowe')
        self.assertEqual(Task.objects.last().user, self.user1)

create方法从:views.py

    def create(self, request, *args, **kwargs):
        username = request.data.get('username')
        try:
            user = User.objects.get(username=username)
        except ObjectDoesNotExist:
            raise serializers.ValidationError('Invalid username.')

        request_data = request.data.copy()
        request_data.pop('username', None)

        task = Task.objects.create(user=user, **request_data)
        serializer = TaskSerializer(task)
        response_data = serializer.data
        response_data['username'] = user.username

        return Response(response_data, status=status.HTTP_201_CREATED)

Task模型类来自(IM 也使用库):models.pydjango-simple-history

class Task(models.Model):
    objects = models.Manager()
    STATUS_CHOICES = [
        ('Nowe', 'Nowe'),
        ('W toku', 'W toku'),
        ('Rozwiązane', 'Rozwiązane'),
    ]
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=False)
    description = models.TextField(blank=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Nowe')
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
    history = HistoricalRecords()

    def __str__(self):
        return self.name

控制台输出:

======================================================================
FAIL: test_create_task (tasks_app.tests.TaskTestCase.test_create_task)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\hunes\Desktop\Studia\tasks_project\tasks_app\tests.py", line 48, in test_create_task
    self.assertEqual(Task.objects.last().name, 'Nowe zadanie')
AssertionError: "['Nowe zadanie']" != 'Nowe zadanie'
- ['Nowe zadanie']
? --            --
+ Nowe zadanie

我尝试将数据中的单引号字符串转换为双引号字符串,向数据添加类型提示,将 dict lateral 转换为构造函数并在线寻求帮助。当我从 Swagger 的级别测试 API 时,我得到了预期的结果,即保存的对象没有被方括号括起来

对不起,如果我使用了一些糟糕的命名法,我开始学习这门语言了

Python Django 验证测试

评论


答: 暂无答案