Django测试有问题吗?

t1qtbnec  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(121)

我正在开发一个Django应用程序,目前正在测试它,这是我的观点:

from django.http import JsonResponse, HttpResponseBadRequest
from store.models import Product
from .basket import Basket

# Create your views here.
def basket_summary(request):
    basket = Basket(request)
    return render(request, "store/basket/summary.html", {"basket": basket})

def basket_add(request):
    basket = Basket(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)
        basket.add(product=product, product_qty=product_qty)

        basket_qty = basket.__len__()
        response = JsonResponse({"qty": basket_qty})
        return response

def basket_delete(request):
    basket = Basket(request)
    if request.POST.get("action") == "post":
        product_id = int(request.POST.get("productid"))
        basket.delete(product_id=product_id)

        basket_qty = basket.__len__()
        basket_total = basket.get_total_price()
        response = JsonResponse({"qty": basket_qty, "subtotal": basket_total})
        return response

def basket_update(request):
    basket = Basket(request)
    if request.POST.get("action") == "post":
        product_id = int(request.POST.get("productid"))
        product_qty = int(request.POST.get("productqty"))
        basket.update(product_id=product_id, product_qty=product_qty)

        basket_qty = basket.__len__()
        basket_total = basket.get_total_price()
        response = JsonResponse({"qty": basket_qty, "subtotal": basket_total})
        return response

我的urls.py文件也在下面:

from .views import basket_summary, basket_add, basket_delete, basket_update

app_name = "store_basket"
urlpatterns = [
    path("", basket_summary, name="basket_summary"),
    path("add/", basket_add, name="basket_add"),
    path("delete/", basket_delete, name="basket_delete"),
    path("update/", basket_update, name="basket_update"),
]

最后是我的测试文件:

from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from store.models import Category, Product
from json import loads

class TestBasketView(TestCase):
    def setUp(self):
        category = Category.objects.create(name="django", slug="django")
        user = User.objects.create(username="admin")
        Product.objects.create(
            title="django beginners",
            category=category,
            created_by=user,
            slug="django-beginners",
            price="20.00",
            image="django",
        )
        Product.objects.create(
            title="django intermediate",
            category=category,
            created_by=user,
            slug="django-beginners",
            price="20.00",
            image="django",
        )
        Product.objects.create(
            title="django advanced",
            category=category,
            created_by=user,
            slug="django-beginners",
            price="20.00",
            image="django",
        )
        self.client.post(
            reverse("store_basket:basket_add"),
            {"productid": 1, "productqty": 1, "action": "post"},
            xhr=True,
        )
        self.client.post(
            reverse("store_basket:basket_add"),
            {"productid": 2, "productqty": 2, "action": "post"},
            xhr=True,
        )

    def test_basket_url(self):
        """
        Test homepage response status
        """
        response = self.client.get(reverse("store_basket:basket_summary"))
        self.assertEqual(response.status_code, 200)

    def test_basket_add(self):
        """
        Test adding items to the basket
        """
        response = self.client.post(
            reverse("store_basket:basket_add"),
            {"productid": 3, "productqty": 1, "action": "post"},
            xhr=True,
        )
        self.assertEqual(response.json(), {"qty": 4})
        response = self.client.post(
            reverse("store_basket:basket_add"),
            {"productid": 2, "productqty": 1, "action": "post"},
            xhr=True,
        )
        self.assertEqual(response.json(), {"qty": 3})

    def test_basket_delete(self):
        """
        Test deleting items from the basket
        """
        response = self.client.post(
            reverse("store_basket:basket_delete"),
            {"productid": 2, "action": "post"},
            xhr=True,
        )
        self.assertEqual(response.json(), {"qty": 1, "subtotal": "20.00"})

    def test_basket_update(self):
        """
        Test updating items from the basket
        """
        response = self.client.post(
            reverse("store_basket:basket_update"),
            {"productid": 2, "productqty": 1, "action": "post"},
            xhr=True,
        )
        self.assertEqual(response.json(), {"qty": 2, "subtotal": "40.00"})

但是我运行了测试,得到了这个错误:

======================================================================
ERROR: test_basket_add (store_basket.test.test_views.TestBasketView.test_basket_add)
Test adding items to the basket
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/bottgabriel/Desktop/Practices/py/ecommerce/store_basket/test/test_views.py", line 63, in test_basket_add
    self.assertEqual(response.json(), {"qty": 4})
                     ^^^^^^^^^^^^^^^
  File "/Users/bottgabriel/Desktop/Practices/py/ecommerce/venv/lib/python3.11/site-packages/django/test/client.py", line 823, in _parse_json
    raise ValueError(
ValueError: Content-Type header is "text/html; charset=utf-8", not "application/json"

======================================================================
FAIL: test_basket_delete (store_basket.test.test_views.TestBasketView.test_basket_delete)
Test deleting items from the basket
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/bottgabriel/Desktop/Practices/py/ecommerce/store_basket/test/test_views.py", line 80, in test_basket_delete
    self.assertEqual(response.json(), {"qty": 1, "subtotal": "20.00"})
AssertionError: {'qty': 0, 'subtotal': 0} != {'qty': 1, 'subtotal': '20.00'}
- {'qty': 0, 'subtotal': 0}
?         ^

+ {'qty': 1, 'subtotal': '20.00'}
?         ^              ++ ++++

======================================================================
FAIL: test_basket_update (store_basket.test.test_views.TestBasketView.test_basket_update)
Test updating items from the basket
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/bottgabriel/Desktop/Practices/py/ecommerce/store_basket/test/test_views.py", line 91, in test_basket_update
    self.assertEqual(response.json(), {"qty": 2, "subtotal": "40.00"})
AssertionError: {'qty': 0, 'subtotal': 0} != {'qty': 2, 'subtotal': '40.00'}
- {'qty': 0, 'subtotal': 0}
?         ^

+ {'qty': 2, 'subtotal': '40.00'}
?         ^              ++ ++++

----------------------------------------------------------------------
Ran 13 tests in 0.267s

FAILED (failures=2, errors=1, skipped=1)
Destroying test database for alias 'default'...

任何帮助将不胜感激!
P.S:我已经调试并确保视图返回JSON,但由于某种原因,测试不起作用。

3phpmpom

3phpmpom1#

最有可能的情况是视图引发了一个错误,例如,因为产品不存在,中间件将其转换为HTML页面。
一个常见的误解是主键是固定的。他们不是。你应该把它们存储在测试用例中,所以:

class TestBasketView(TestCase):
    def setUp(self):
        category = Category.objects.create(name='django', slug='django')
        user = User.objects.create(username='admin')
        self.product1 = Product.objects.create(
            title='django beginners',
            category=category,
            created_by=user,
            slug='django-beginners',
            price='20.00',
            image='django',
        )
        self.product2 = Product.objects.create(
            title='django intermediate',
            category=category,
            created_by=user,
            slug='django-beginners',
            price='20.00',
            image='django',
        )
        self.product3 = Product.objects.create(
            title='django advanced',
            category=category,
            created_by=user,
            slug='django-beginners',
            price='20.00',
            image='django',
        )
        self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product1.pk, 'productqty': 1, 'action': 'post'},
            xhr=True,
        )
        self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product1.pk, 'productqty': 2, 'action': 'post'},
            xhr=True,
        )

    def test_basket_add(self):
        """
        Test adding items to the basket
        """
        response = self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product3.pk, 'productqty': 1, 'action': 'post'},
            xhr=True,
        )
        self.assertEqual(response.json(), {'qty': 4})
        response = self.client.post(
            reverse('store_basket:basket_add'),
            {'productid': self.product2.pk, 'productqty': 1, 'action': 'post'},
            xhr=True,
        )
        self.assertEqual(response.json(), {'qty': 3})

注意:通常情况下,我们 * 不 * 应该调用像__len__这样的魔法属性,通常情况下,这应该只在某些情况下进行,例如在使用super调用时。

相关问题