You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django点赞功能Post接口测试异常:点赞记录未写入数据库

Django点赞接口测试异常:数据库提前销毁导致断言失败

我基于Django开发的点赞功能在实际使用中运行正常,但测试Post接口时出现异常:发送Post请求后,本该向Likes模型插入记录,但测试数据库在验证点赞记录前就被销毁,导致Likes模型记录数始终为0,断言失败。

测试文件代码

from django.test import TestCase
from django.urls import reverse

from register.models import User
from vietnam_research.models import Articles, Likes
class TestView(TestCase):
    @classmethod
    def setUpTestData(cls):
        User.objects.create_user(email='tester@b.c').set_password('12345')
        user = User.objects.get(email='tester@b.c')
        Articles.objects.create(title='Hello', note='How are you', user=user)

    def test_click_good_button(self):
        user = User.objects.get(email='tester@b.c')
        response = self.client.post(reverse('vnm:likes', kwargs={'user_id': 1, 'article_id': 1}), follow=True)
        self.assertEqual(200, response.status_code)

        print('Articles.objects.all().count(): ', Articles.objects.all().count())
        print('Likes.objects.all().count(): ', Likes.objects.all().count())
        self.assertTrue(Likes.objects.filter(user=user).exists())

模型代码

class Articles(models.Model):
    title = models.CharField(max_length=200)
    note = models.TextField()
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)


class Likes(models.Model):
    articles = models.ForeignKey(on_delete=models.CASCADE)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

Views代码

class LikesUpdateView(LoginRequiredMixin, UpdateView):
    def post(self, request, *args, **kwargs):
        print(json.loads(request.body), json.loads(request.body).get('status'))
        try:
            user = User.objects.get(pk=kwargs['user_id'])
            article = Articles.objects.get(pk=kwargs['article_id'])
            like = Likes.objects.filter(user=user, articles=article)
            if not like.exists():
                Likes.objects.create(user=user, articles=article)
            else:
                like.delete()
            return JsonResponse({"status": "responded by views.py"})
        except User.DoesNotExist:
            logging.critical('invalid user')
        except Articles.DoesNotExist:
            logging.critical('invalid article')

URLs配置

urlpatterns = [
    path('', index, name='index'),
    path('likes/<int:user_id>/<int:article_id>/', LikesUpdateView.as_view(), name='likes'),
      :
]

控制台测试日志

D:\venv\Scripts\python.exe "C:\pycharm\django_test_manage.py" test tests.test_views.TestView.test_click_good_button D:\mysite
Testing started at 22:28 ...
Creating test database for alias 'default'...
Found 1 test(s).
System check identified no issues (0 silenced).


Articles.objects.all().count():  1
Destroying test database for alias 'default'...  <<<< 这里!!!
Likes.objects.all().count():  0

Failure
Traceback (most recent call last):
  File "D:\OneDrive\dev\portfolio\mysite\vietnam_research\tests\test_views.py", line 36, in test_click_good_button
    self.assertTrue(Likes.objects.filter(user=user).exists())
AssertionError: False is not true

另一次测试日志:

Articles.objects.all().count():  1
Likes.objects.all().count():  0
Destroying test database for alias 'default'...

发送Post请求后本该向Likes模型执行插入操作,但实际在生成点赞记录前,测试数据库就被销毁了。测试Post方法时是否遗漏了什么配置?

经过多轮测试,Likes模型记录数始终为0,怀疑数据库存在异常,但始终无法生成点赞记录。

内容的提问来源于stack exchange,提问作者yoshitaka okada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:21:35