jeudi 10 août 2017

Failing to test POST in Django

Using Python3, Django, and Django Rest Frameworks. Previously I had a test case that was making a POST to an endpoint. The payload was a dictionary:

mock_data = {some data here}

In order to send the data over the POST I was doing:

mock_data = base64.b64encode(json.dumps(mock_data).encode('utf-8'))

When doing the POST:

response = self.client.post(
    '/some/path/here/', {
        ...,
        'params': mock_data.decode('utf-8'),
    },
)

And on the receiving end, in validate() method I was doing:

params = data['params']
try:
    params_str = base64.b64decode(params).decode('utf-8')
    app_data = json.loads(params_str)
except (UnicodeDecodeError, ValueError):
    app_data = None

That was all fine, but now I need to use some hmac validation, and the json I am passing can no longer be a dict - its ordering would change each time, so hmac.new(secret, payload, algorithm) would be different. I was trying to use a string:

payload = """{data in json format}"""

But when I am doing:

str_payload = payload.encode('utf-8')
b64_payload = base64.b64encode(str_payload)

I cannot POST it, and getting an error:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'ewog...Cn0=' is not JSON serializable

even if I do b64_payload.decode('utf-8') like before, still getting similar error:

raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'\xa2\x19...\xff' is not JSON serializable

Some python in the terminal:

>>> d = {'email': 'user@mail.com'} # regular dictionary
>>> d
{'email': 'user@mail.com'}
>>> dn = base64.b64encode(json.dumps(d).encode('utf-8'))
>>> dn
b'eyJlbWFpbCI6ICJ1c2VyQG1haWwuY29tIn0='
>>> s = """{"email": "user@mail.com"}""" # string
>>> s
'{"email": "user@mail.com"}'
>>> sn = base64.b64encode(json.dumps(s).encode('utf-8'))
>>> sn
b'IntcImVtYWlsXCI6IFwidXNlckBtYWlsLmNvbVwifSI=' # different!
>>> sn = base64.b64encode(s.encode('utf-8'))
>>> sn
b'eyJlbWFpbCI6ICJ1c2VyQG1haWwuY29tIn0=' # same

Aucun commentaire:

Enregistrer un commentaire