单元测试中的AssertionError

时间:2019-07-29 10:22:37

标签: python-3.x django-models django-rest-framework

我在编写测试时遇到了错误

 assert response.status_code == status.HTTP_201_CREATED
     

E AssertionError:断言415 == 201   E -415   E +201

models.py

class Product(TimeStamp):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
color = models.ManyToManyField(ColorOfProduct)
available = models.BooleanField(default=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', null=True, blank=True)
slug = models.SlugField(max_length=100, unique=True, blank=True)

def __str__(self):
    return f'{self.category} - {self.name}'

tests.py 看起来像这样

class ProductTest(APITestCase):
def post_product(self, category, name, brand_name, color, available):
    url = reverse(ProductView.name)
    print(url)
    data = {
        'category': category,
        'name': name,
        'brand_name': brand_name,
        'color': color,
        'available': available,
    }

    response = self.client.post(url, data, format='json')
    return response

def test_post_and_get_product(self):
    new_category_name = 'Hewlet Packard'
    new_product_name = 'HP Zenbook'
    new_brand_name = 'HP'
    new_color = 'black'
    new_available = True
    response = self.post_product(
        new_category_name,
        new_product_name,
        new_brand_name,
        new_color,
        new_available,
    )
    assert response.status_code == status.HTTP_201_CREATED
    assert Product.objects.count() == 1
    assert Product.objects.get().name == new_product_name

我指示的是媒体类型,但是当我检查时会抛出错误“不支持的媒体类型”

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

原因可能是django的默认测试格式为application/octet-stream。在调用测试方法之前,您需要使用json.dumps()。在您的post_product方法中,只需更改:

response = self.client.post(url, data, format='json')

import json 

response = self.client.post(url, json.dumps(data), content_type='application/json')