Skip to main content
 首页 » 编程设计

python之如何使用 requests_mock 对文件上传进行单元测试

2024年12月31日9jirigala

我正在为一个 API 编写一个 Python (3) 包装器,我正在尝试对其中需要上传文件的部分进行单元测试。我想验证文件名和内容是否由我的客户正确发送。

我正在使用 Python 的 unittest图书馆,以及requests和 requests_mock用于测试。

我计划解决这个问题的方法是使用一个回调函数来验证文件是否已发送以及所有 header 是否已正确设置。这是我到目前为止所拥有的:

import unittest 
import requests 
import requests_mock 
 
from my_class import my_class 
 
from my_class.API import API 
 
class  TestAPI(unittest.TestCase): 
 
    def setUp(self): 
        self.hostname = 'https://www.example.com' 
 
    def validate_file_upload(self, request, context, filename, content): 
        # self.assertEqual(something, something_else) 
        # better solution goes here 
 
    def test_submit_file(self): 
        API_ENDPOINT = self.hostname + '/api/tasks/create/file/' 
        DUMMY_FILE = 'file' 
        DUMMY_CONTENT = 'here is the\ncontent of our\nfile' 
 
        s = API(self.hostname) 
 
        with open(DUMMY_FILE, 'w+') as f: 
            f.write(DUMMY_CONTENT) 
 
        with requests_mock.Mocker() as m: 
            def json_callback(request, context): 
                self.validate_file_upload(request, context, DUMMY_FILE, 
                    DUMMY_CONTENT) 
                return {} 
 
            m.post(API_ENDPOINT, json=json_callback) 
            s.upload_file(DUMMY_FILE) 

我已经确定,在文件上传成功后,validate_file_upload 的request 参数有一些相关的数据,即 request.headers 和 request.text。以下是 validate_file_upload 函数调用后两者的内容:

request.headers

{'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '171', 'Content-Type': 'multipart/form-data; boundary=e1a0aa05f83735e85ddca089c450a21b'} 

request.text

'--e1a0aa05f83735e85ddca089c450a21b\r\nContent-Disposition: form-data; name="file"; filename="file"\r\n\r\nhere is the\ncontent of our\nfile\r\n--e1a0aa05f83735e85ddca089c450a21b--\r\n' 

现在,事情是这样的。我知道我可以解析 request.text 字符串并获取我想要的数据;验证起来很容易。

但是,这种逻辑似乎真的不属于我的单元测试。我无法想象没有更好的解决方案;有人已经在不同的模块中实现了此功能,或者我忽略了一些明显的东西。

我不应该实现 HTTP spec用于文件上传 单元测试像文件上传一样简单的东西,对吗?有更好的方法吗?


这是 dir(request) 的输出:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_allow_redirects', '_case_sensitive', '_cert', '_create', '_matcher', '_proxies', '_qs', '_request', '_stream', '_timeout', '_url_parts', '_url_parts_', '_verify', 'allow_redirects', 'cert', 'hostname', 'json', 'matcher', 'netloc', 'path', 'port', 'proxies', 'qs', 'query', 'scheme', 'stream', 'text', 'timeout', 'verify'] 

我已经检查了文件上传数据的任何其他表示形式的所有非下划线属性,但无济于事。我也试过搜索 StackOverflow和 Google ,而且我离找到更好的方法也很近。这是唯一出现在任一搜索中的帖子。

请您参考如下方法:

我没有 my_class.API 来测试你的确切代码,但我相信你可以使用 cgi。

import cgi 
 
body_file = io.BytesIO(request.body) 
_, pdict = cgi.parse_header(request.headers['Content-Type']) 
parsed = cgi.parse_multipart(fp=body_file, pdict=pdict) 
# Now inspect `parsed`