如何创建映像以对API进行单元测试

时间:2015-12-18 02:09:30

标签: python django rest unit-testing

我有一个代表女性的简单模型,用户可以查看,编辑和创建:

class Female(models.Model):

    firstName = models.CharField(max_length=255)
    lastName = models.CharField(max_length=255)
    profileImage = models.ImageField()
    bio = models.TextField()
    fantasticBio = models.TextField()

我使用多部分表单通过Angular服务发送创建数据。这很好用。处理创建的django视图是:

@api_view(['POST'])
def createFemale(request):

    serializedFemale = FemaleSerializer(data=request.data)

    if serializedFemale.is_valid():
        serializedFemale.save()
        return Response(serializedFemale.data)
    else:
        return Response(serializedFemale.errors, status=status.HTTP_400_BAD_REQUEST)

我的问题是我无法对此视图进行完全单元测试。我无法创建可用于通过测试客户端测试视图的图像。我对图像生成的了解是有限的,因此我可能会生成错误的图像,但是当我在设置中将其直接写入数据库时​​,它似乎被接受为Django ImageField。相关测试代码如下:

def createImageFile():

    """
        Convinience function to create a test image
    """

    image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
    image_file = BytesIO()
    image.save(image_file, 'PNG')
    img_str = base64.b64encode(image_file.getvalue())
    img_str = str.encode("data:image/png;base64,") + img_str

    return ImageFile(img_str)


def test_createFemale(self):

    """
        A valid Female created with the API should be in the database
    """

    profileImage = SimpleUploadedFile("test.png", createImageFile().file, content_type="image/png")

    femaleToCreate = {}
    femaleToCreate['firstName'] = "Test"
    femaleToCreate['lastName'] = "Female"
    femaleToCreate['profileImage'] = profileImage
    femaleToCreate['bio'] = "Test bio"
    femaleToCreate['fantasticBio'] = "Fantastic test bio"

    response = self.client.post(url, femaleToCreate)

    self.assertEquals(response.status_code, 200)  # Make sure valid request returns success response

我从服务器收到的回复是:

{'profileImage': ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.']}

如何在单元测试中创建我的API接受的图像?

请不要建议读取现有图像的文件,我已经考虑过这个选项而选择不追求它,因为我认为这是一个不好的做法。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

好的,所以我按照以下方式解决了这个问题:

def test_images_by_component_id_update(self):
    image = PIL.Image.new('RGB', size=(1, 1))
    file = tempfile.NamedTemporaryFile(suffix='.jpg')
    image.save(file)

    with open(file.name, 'rb') as f:
        data = {'image': f}
        response = self.client.patch(reverse('foo', args=(1, 1)), data=data, format='multipart')

    self.assertEqual(200, response.status_code)

注意我必须重新打开文件,这需要一段时间来调试。无论出于何种原因,它不喜欢NamedTemporaryFile.file属性,所以我不得不重新打开。