简体   繁体   English

如何为Flask Post单元测试Python复制Multidict

[英]How to Replicate Multidict for Flask Post Unit Test Python

So in my flask app, I have a form on the frontend that gets populated with several users. 因此,在我的烧瓶应用程序中,前端有一个表单,其中填充了多个用户。 Each user is associated with a checkbox with the name 'selected_user'. 每个用户都与一个名为“ selected_user”的复选框相关联。 On submit, the form is posted through standard HTML form controls (no javascript or manual ajax of any kind). 提交后,该表单将通过标准HTML表单控件发布(不得使用任何javascript或手动ajax)。

In the backend, I can parse this using 在后端,我可以使用

flask.request.form.getlist('selected_user')

and it returns a list of users as I expect (a user here is itself a dictionary of unique keys and associated values). 并返回我期望的用户列表(这里的用户本身就是唯一键和关联值的字典)。

Printing out flask.request.form looks like so for example: 打印出flask.request.form如下所示:

ImmutableMultiDict([
  ('_xsrf_token', u'an_xsrf_token_would_go_here'),
  ('selected_user', u'{u\'primaryEmail\': u\'some_value\'}'...),
  ('selected_user', u'{u\'primaryEmail\': u\'some_value\'}'...)])

My problem is, I cannot seem to replicate this format in my unit tests for the life of me. 我的问题是,我似乎无法终生在单元测试中复制这种格式。 Obviously, I could use some javascript to bundle the checked users on the frontend into an array or whatever and then duplicate that area much easier on the backend, and that may very well be what I end up doing, but that seems like an unnecessary hassle just to make this function testable when it already behaves perfectly in my application. 显然,我可以使用一些javascript将前端的已检查用户捆绑到一个数组中或类似的东西,然后在后端更容易地复制该区域,这很可能是我最终要做的事情,但这似乎是不必要的麻烦只是为了使该功能在我的应用程序中表现良好时就可以对其进行测试。

Here is what I currently have tried in my test, which seems like it should be the correct answer, but it does not work: 这是我目前在测试中尝试过的内容,似乎应该是正确的答案,但它不起作用:

mock_users = []
for x in range(0, len(FAKE_EMAILS_AND_NAMES)):
  mock_user = {}
  mock_user['primaryEmail'] = FAKE_EMAILS_AND_NAMES[x]['email']
  mock_user['name'] = {}
  mock_user['name']['fullName'] = FAKE_EMAILS_AND_NAMES[x]['name']
  mock_users.append(mock_user)

data = {}
data['selected_user'] = mock_users

response = self.client.post(flask.url_for('add_user'), data=data,
                            follow_redirects=False)

This gives me an error as follows: 这给我一个错误,如下所示:

add_file() got an unexpected keyword argument 'primaryEmail'

I've also attempted sending these as query strings, sending data as json.dumps(data), encoding each mock_user as a tuple like this: 我还尝试将这些作为查询字符串发送,作为json.dumps(data)发送数据,将每个模拟用户编码为元组,如下所示:

data = []
for x in range(0, 3):
  my_tuple = ('selected_user', mock_users[x])
  data.append(my_tuple)

None of these approaches have worked for various other errors. 这些方法都无法解决其他各种错误。 What am I missing here? 我在这里想念什么? Thanks ahead of time for any help! 提前感谢您的帮助! Also, sorry if there are an obvious syntax errors as I rewrote some of this for SO instead of copy pasting. 另外,如果有明显的语法错误,请您谅解,因为我将其中一些重写为SO,而不是复制粘贴。

You can create a MultiDict, then make it Immutable: 您可以创建一个MultiDict,然后将其设置为不可变的:

from werkzeug.datastructures import MultiDict, ImmutableMultiDict

FAKE_EMAILS_AND_NAMES = [
    {'email': 'a@a.com',
     'name': 'a'},
    {'email': 'b@b.com',
     'name': 'b'},
]

data = MultiDict()
for x in range(0, len(FAKE_EMAILS_AND_NAMES)):
  mock_user = {}
  mock_user['primaryEmail'] = FAKE_EMAILS_AND_NAMES[x]['email']
  mock_user['name'] = {}
  mock_user['name']['fullName'] = FAKE_EMAILS_AND_NAMES[x]['name']
  data.add('select_user', mock_user)

data = ImmutableMultiDict(data)

print data

This prints: 打印:

ImmutableMultiDict([
    ('select_user', {'primaryEmail': 'a@a.com', 'name': {'fullName': 'a'}}),
    ('select_user', {'primaryEmail': 'b@b.com', 'name': {'fullName': 'b'}})
])

EDIT: 编辑:

The line data.add... should probably be data.add('selected_user', json.dumps(mock_user)) since it looks like the output you posted is a JSON encoded string. data.add...可能应该是data.add('selected_user', json.dumps(mock_user))因为看起来您发布的输出是JSON编码的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM