用Python写一个上传接口,并给出测试用例
时间: 2023-03-20 15:01:23 浏览: 242
好的,下面是一个使用Python编写的简单的文件上传接口的示例代码,以及测试用例:
```python
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
if file:
filename = file.filename
file.save(filename)
return 'File uploaded successfully'
else:
return 'No file was uploaded'
if __name__ == '__main__':
app.run(debug=True)
```
这个接口会监听POST请求,并尝试从请求中获取一个名为“file”的文件对象。如果成功获取到了文件对象,就将其保存在当前工作目录下,文件名与上传时的文件名相同,并返回“File uploaded successfully”;如果没有获取到文件对象,则返回“No file was uploaded”。
接下来是测试用例:
```python
import requests
def test_upload_file():
url = 'http://localhost:5000/upload'
files = {'file': ('test.txt', b'This is a test file.')}
response = requests.post(url, files=files)
assert response.status_code == 200
assert response.text == 'File uploaded successfully'
files = {'file': ('', b'This is another test file.')}
response = requests.post(url, files=files)
assert response.status_code == 200
assert response.text == 'No file was uploaded'
```
这个测试用例会首先向接口上传一个名为“test.txt”的文件,文件内容为“This is a test file.”。然后它会检查接口的响应状态码是否为200,并检查响应内容是否为“File uploaded successfully”。接着,它会再次向接口上传一个空文件,然后检查接口的响应状态码是否为200,并检查响应内容是否为“No file was uploaded”。如果所有的断言都通过了,那么就说明接口工作正常。
阅读全文