import cgi


def check_response(response, code=200, success=True):
    """
    Make sure an API response is ok:

    - check that status code is in the "ok" range
    - check status code (default: 200)
    - check content-type header (must be application/json)
    - check that response data is valid json
    - check that response data has a 'success' key with True value
    - check that response data has a 'result' key

    :param response: Response object from the requests module
    :type response: requests.models.Response
    :param int code: expected HTTP status code
    :param bool success: wheter we expect success or failure
    :return: the decoded (json) response data
    """
    if type(success) != bool:
        raise TypeError('success must be a boolean')

    assert response.ok is success
    assert response.status_code == code
    content_type = cgi.parse_header(response.headers['content-type'])[0]
    assert content_type == 'application/json'
    data = response.json()
    assert data['success'] is success
    if success:
        assert 'result' in data
    else:
        assert 'error' in data
    return data