【问题标题】:ValueError: Content-Type header is "text/html", not "application/json" django pythonValueError: Content-Type 标头是 \"text/html\",而不是 \"application/json\" django python
【发布时间】:2022-10-14 11:17:51
【问题描述】:

我正在尝试对我的一个观点进行测试,但我不断收到此错误raise ValueError( ValueError: Content-Type header is "text/html", not "application/json"

这是视图功能


def add_to_cart(request):
    cart = Cart(request)
    if request.POST.get("action") == "post":
        product_id = int(request.POST.get("productid"))
        product_qty = int(request.POST.get("productqty"))
        product = get_object_or_404(Product, id=product_id)
        cart.add(product=product, qty=product_qty)
        product_qty = cart.__len__()
        response = JsonResponse({"qty": product_qty})
        return response

这是网址路径

from django.urls import path
from . import views
app_name = "cart"

urlpatterns = [
    path("add/", views.add_to_cart, name="add_to_cart"),
]

最后是测试

def test_add_to_cart(self):
        response = self.client.post(reverse('cart:add_to_cart'), {
            "productid": 3,
            "productqty": 1,
            "action":'post',
        }, xhr=True)
        print(response.status_code)
        self.assertTrue(response.json(), {'qty':4})
        response = self.client.post(reverse('cart:add_to_cart'), {
            "productid": 2,
            "productqty": 1,
            "action":'post',
        }, xhr=True)
        self.assertTrue(response.json(), {'qty':3})

【问题讨论】:

  • 而不是打印 response.status_code 您应该断言。检查值是否符合您的预期第一的.
  • 那是最初用于调试的,我应该删除它,我将测试状态代码并更新问题

标签: python json django unit-testing testing


【解决方案1】:

实际上一切正常,错误来自我使用的self.assertTrue

我实际上是打算使用self.assertEqual

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 2020-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多