我试图使用pytest框架将testfile.py写入我的照片服务。
我的照片服务写得很夸张,如下所示。它使用post方法将带有附加信息的图片作为multipart-formdata发布:
swagger: '2.0'
info:
title: Photo service API
version: "0.1"
paths:
/photo:
post:
tags:
- "Photo"
operationId: photo_service.post_photo
summary: Add a new photo
consumes:
- multipart/form-data
- application/x-www-form-urlencoded
parameters:
- name: photo_name
in: formData
description: "file to upload"
required: true
type: string
- name: user_id
in: formData
description: "user who posted"
required: true
type: string
- name: photo_tags
in: formData
description: "tags of the photo"
type: array
items:
type: string
minimum: 1
maximum: 30
required: true
- name: photo_file
in: formData
description: "file to upload"
required: true
type: file
minLength: 1
maxLength: 5000000
responses:
201:
description: New photo added
schema:
properties:
photo_file:
type: object
description: Information about the photo (size, file name, etc.)
headers:
Location:
type: string
description: The URL of the newly-added photo
409:
description: Photo already exists
此后我的照片存储在mongodb数据库中。课堂照片定义为:
class Photo(Document):
photo_name = StringField(max_length=120, required=True)
user_id = StringField(max_length=120, required=True)
photo_file = ImageField()
photo_tags= ListField(StringField(max_length=30))
我的主要问题是如何在testfile.py中编写post方法来测试我的API?我试着像这样写:
headers_content_form_data = {'Content-Type': 'multipart/form-data'}
headers_content_json = {'Content-Type': 'application/json'}
headers_accept = {'Accept': 'application/json'}
with open('/home/user/photoapp/src/ms/photo/img1.jpg', 'rb') as img1:
imgStringIO1 = StringIO(img1.read())
@staticmethod
def test_post_once(client):
print(os.getcwd())
response = client.post('/photo', headers=TestClass.headers_content_form_data,
data={'photo_name': 'thedoors',
'user_id': 'laurea',
'photo_file': (imgStringIO1, 'img1.jpg'),
'photo_tags': ['testTag','45','46']
})
assert response.headers['Location']
assert response.status_code == 201
我似乎在提交photo_file时遇到问题。我尝试提交的照片文件位于我的本地目录中,与测试文件中的相同。
此外,我想尝试在容器内运行。如何将我的图像文件从本地计算机发送到容器以运行测试?