How to copy Multidict for Flask Post Unit Test Python

So, in my flash application, I have a form on the interface that is populated by several users. Each user is associated with a flag with the name "selected_user". When submitted, the form is published via standard HTML controls (without javascript or manual ajax of any type).

In the backend, I can analyze this using

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

and it returns a list of users as I expect (the user here is himself a dictionary of unique keys and associated values).

The listing of flask.request.form looks like this:

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 that I cannot reproduce this format in my unit tests for life. Obviously, I could use some javascript in order to associate verified users on the interface with an array or whatever, and then duplicate this area is much easier on the backend, and this may be very good, which I end up doing, but it seems like an unnecessary hassle just to test this feature when it already works great in my application.

Here is what I tried in my test right now, it looks like this 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 results in an error:

add_file() got an unexpected keyword argument 'primaryEmail'

I also tried sending them as query strings, sending data as json.dumps (data), encoding each mock_user as a tuple as follows:

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

. ? ! , , , SO .

+4
1

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

:

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

EDIT:

data.add... , , data.add('selected_user', json.dumps(mock_user)), , , JSON.

+3

Source: https://habr.com/ru/post/1624476/


All Articles