使用瓶子在请求中使用请求中的嵌套对象进行单元测试

问题描述:

一个单元如何测试烧瓶中写入的REST API端点,该端点接受请求主体的嵌套字典对象?使用瓶子在请求中使用请求中的嵌套对象进行单元测试

下面是使用烧瓶中,并输入验证webargs

from flask import Flask 
from webargs import fields 
from webargs.flaskparser import use_args 

app = Flask(__name__) 

hello_args = { 
    'a': fields.Nested({'name' : fields.Str()}) 
} 

@app.route('/', methods=['POST']) 
@use_args(hello_args) 
def index(args): 
    return 'Hello ' + str(args) 


def test_app(): 
    app.config['TESTING'] = True 
    test_app = app.test_client(use_cookies=False) 
    test_app.post(data={"a": {"name": "Alice"}}) 


if __name__ == '__main__': 
    app.run() 

直接使用该enpoint时正常工作,

% curl -H "Content-Type: application/json" -X POST \ 
     -d '{"a":{"name": "Alice"}}' http://localhost:5000 

Hello {'a': {'name': 'Alice'}}% 

然而引发在werkzeug.test.EnvironBuilder一个异常时,它在内部被调用的例子,单元测试,

nosetests /tmp/test.py              
E 
====================================================================== 
ERROR: test.test_app 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/usr/lib64/python3.4/site-packages/nose/case.py", line 198, in runTest 
    self.test(*self.arg) 
    File "/tmp/test.py", line 26, in test_app 
    test_app.post(data={"a": {"name": "Alice"}}) 
    File "/home/rth/.local/lib64/python3.4/site-packages/werkzeug/test.py", line 788, in post 
    return self.open(*args, **kw) 
    File "/home/rth/.local/lib64/python3.4/site-packages/flask/testing.py", line 103, in open 
    builder = make_test_environ_builder(self.application, *args, **kwargs) 
    File "/home/rth/.local/lib64/python3.4/site-packages/flask/testing.py", line 34, in make_test_environ_builder 
    return EnvironBuilder(path, base_url, *args, **kwargs) 
    File "/home/rth/.local/lib64/python3.4/site-packages/werkzeug/test.py", line 338, in __init__ 
    self._add_file_from_data(key, value) 
    File "/home/rth/.local/lib64/python3.4/site-packages/werkzeug/test.py", line 355, in _add_file_from_data 
    self.files.add_file(key, **value) 
TypeError: add_file() got multiple values for argument 'name' 

---------------------------------------------------------------------- 
Ran 1 test in 0.011s 

FAILED (errors=1) 

这使用Pytho 3.5,烧瓶0.12和网状物1.5.2。

此外,在https://github.com/pallets/flask/issues/2176

看来,尽管使用webargs,输入数据仍然必须被序列化和CONTENT_TYPE对于这项工作明确指定提交的问题。特别是,

test_app.post(data=json.dumps({"a": {"name": "Alice"}}), 
      content_type='application/json') 

更换

test_app.post(data={"a": {"name": "Alice"}}) 

固定这个问题(另见相关的SO答案here)。