示例#1
0
def test(empty_database, create_and_delete_user):
    if is_test():
        # new user, FORCE_CHANGE_PASSWORD required
        force_change_password()

        # new user, fully authenticated use new password
        fullpath = get_lambda_fullpath("LambdaApiUserSignIn")
        event = get_lambda_test_data(fullpath)
        # https://github.com/nficano/python-lambda
        # noinspection PyTypeChecker
        response1 = invoke(fullpath, event)
        assert response1 is not None  # "/user/signin should return Status \"OK\"")
        assert response1["statusCode"] == STATUS_OK
        assert "body" in response1
        body = response1['body']
        response_data = json.loads(body)
        validate_response(response_data)

    elif is_production():
        force_change_password()
        # new user, fully authenticated use new password via API Gateway
        event = get_lambda_test_data(
            get_lambda_fullpath("LambdaApiUserSignIn"))
        # http://docs.python-requests.org/en/master/user/quickstart
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/signin')
        response3 = requests.post(url,
                                  headers=event['headers'],
                                  data=json.dumps(event['body']))
        assert response3.status_code == STATUS_OK
        response_data = response3.json()
        validate_response(response_data)
示例#2
0
def test(empty_database, create_and_delete_user, create_login_session):
    if is_test():
        fullpath = get_lambda_fullpath("LambdaApiAwsBackup")
        event = get_lambda_test_data(fullpath)
        event, fullpath = get_secure_event("LambdaApiAwsBackup")

        # https://github.com/nficano/python-lambda
        response1 = invoke(fullpath, event)
        assert response1["statusCode"] == STATUS_OK
        assert "body" in response1
        body = response1['body']
        response_data = json.loads(body)
        assert 'duration' in response_data
        assert response_data['duration'] > 0.0

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiAwsBackup")
        # http://docs.python-requests.org/en/master/user/quickstart
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/aws/backup')
        response2 = requests.get(url, headers=event['headers'], params=event['queryStringParameters'])
        # "/backup should return Status \"OK\"")
        assert response2.status_code == STATUS_OK
        response_data = response2.json()
        assert 'duration' in response_data
        assert response_data['duration'] > 0.0
def create_user_contact():
    event, fullpath = get_secure_event("LambdaApiUserContact")
    payload = {"httpMethod": "PUT", "body": event['body']}
    response1 = invoke(fullpath, payload)
    assert response1['statusCode'] == STATUS_OK
    body = response1['body']
    assert body
    data = json.loads(response1['body'])
    assert data
    assert 'topic_arn' in data
    assert data['topic_arn'].startswith('arn:aws:sns')

    if is_test():
        payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK
        response_data = json.loads(response2['body'])
        assert 'TopicArn' in response_data
        assert response_data['TopicArn'].startswith("arn:aws:sns:")
    elif is_production():
        # event, fullpath = get_secure_event("LambdaApiUserProfile")
        # url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/user/profile')
        # response = requests.put(url, headers=event['headers'], data=json.dumps(event['body']))
        # assert response.status_code == STATUS_OK
        # event, fullpath = get_secure_event("LambdaApiUserContact")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/user/contact')
        response4 = requests.get(url, headers=event['headers'], params=event['body'])
        assert response4.status_code == STATUS_OK
        response_data = json.loads(response4.text)
示例#4
0
def test(empty_database, create_and_delete_user, create_login_session):
    if is_test():
        event, fullpath = get_secure_event("LambdaApiSamplePython")
        payload = event
        response1 = invoke(fullpath, payload)
        assert response1['statusCode'] == STATUS_OK
        response_data = json.loads(response1['body'])
        assert response_data
        if isinstance(response_data, dict):
            for k in event['body']:
                if k in response_data:
                    assert event['body'][k] == response_data[k]

        payload = {
            "httpMethod": "GET",
            "queryStringParameters": {
                "index_key_example": event['body']['index_key_example']
            }
        }
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK
        response_data = json.loads(response2['body'])

        # noinspection PyShadowingBuiltins
        id = response_data[0]['id']
        payload = {"httpMethod": "DELETE", "queryStringParameters": {"id": id}}
        # noinspection PyTypeChecker
        response3 = invoke(fullpath, payload)
        assert response3['statusCode'] == STATUS_OK

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiSamplePython", aws=True)
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/sample')

        response4 = requests.put(url,
                                 headers=event['headers'],
                                 data=json.dumps(event['body']))
        assert response4.status_code == STATUS_OK
        response_data = json.loads(response4.text)
        assert response_data

        response5 = requests.get(
            url,
            headers=event['headers'],
            params={"index_key_example": event['body']['index_key_example']})
        assert response5.status_code == STATUS_OK
        response_data = json.loads(response5.text)
        assert response_data

        # noinspection PyShadowingBuiltins
        id = response_data[0]["id"]
        response6 = requests.delete(url,
                                    headers=event['headers'],
                                    params={"id": id})
        assert response6.status_code == STATUS_OK
def test(empty_database, create_and_delete_user, create_login_session):
    cognito_idp_client = boto3.client('cognito-idp')
    if is_test():
        event, fullpath = get_secure_event("LambdaApiUserProfile")
        response1 = invoke(fullpath, event)
        assert response1['statusCode'] == STATUS_OK
        response_data = json.loads(response1['body'])
        for k in event['body']:
            if k in response_data:
                assert event['body'][k] == response_data[k]

        payload = {
            "httpMethod": "GET",
            "queryStringParameters": {
                "username": event['body']['username']
            }
        }
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK
        response_data = json.loads(response2['body'])

        # noinspection PyShadowingBuiltins
        id = response_data['id']
        payload = {"httpMethod": "DELETE", "queryStringParameters": {"id": id}}
        # noinspection PyTypeChecker
        response3 = invoke(fullpath, payload)
        assert response3['statusCode'] == STATUS_OK

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiUserProfile")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/profile')
        response4 = requests.post(url,
                                  headers=event['headers'],
                                  data=json.dumps(event['body']))
        assert response4.status_code == STATUS_OK
        response_data = json.loads(response4.text)
        for k in event['body']:
            if k in response_data:
                assert event['body'][k] == response_data[k]

        response5 = requests.get(url,
                                 headers=event['headers'],
                                 params=event['body'])
        assert response5.status_code == STATUS_OK
        response_data = json.loads(response5.text)
        assert response_data

        # noinspection PyShadowingBuiltins
        event['body']['id'] = response_data["id"]
        response6 = requests.delete(url,
                                    headers=event['headers'],
                                    params=event['body'])
        assert response6.status_code == STATUS_OK
def test(empty_database, create_and_delete_user, create_login_session,
         create_user_contact):
    if is_test():
        event, fullpath = get_secure_event("LambdaApiUserMessage")
        event['body']["sns"] = True
        response1 = invoke(fullpath, event)
        assert response1['statusCode'] == STATUS_OK
        response_data = json.loads(response1['body'])
        assert response_data
        assert 'message_id' in response_data
        assert len(response_data['message_id']) >= 32
        assert 'topic_arn' in response_data
        topic_arn = response_data['topic_arn']

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiUserProfile")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/profile')
        response = requests.put(url,
                                headers=event['headers'],
                                data=json.dumps(event['body']))
        assert response.status_code == STATUS_OK

        event, fullpath = get_secure_event("LambdaApiUserMessage")
        event['body']["sns"] = True
        # http://docs.python-requests.org/en/master/user/quickstart
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/message')
        response4 = requests.put(url,
                                 headers=event['headers'],
                                 data=json.dumps(event['body']))
        assert response4.status_code == STATUS_OK
        response_data = json.loads(response4.text)
        assert response_data
        assert "message_id" in response_data
        assert len(response_data['message_id']) > 32

        event, fullpath = get_secure_event("LambdaApiUserContact")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/contact')
        response5 = requests.get(url,
                                 headers=event['headers'],
                                 params=event['body'])
        assert response5.status_code == STATUS_OK
        response_data = json.loads(response5.text)
        # assert any(event['username'] in s['username'] for s in data)

        response6 = requests.delete(
            url,
            headers=event['headers'],
            params={"topic_arn": response_data['TopicArn']})
        assert response6.status_code == STATUS_OK
        response_data = json.loads(response6.text)
def create_users(delete_users):
    # Create testers
    for tester in TESTERS:
        if is_test():
            fullpath = get_lambda_fullpath("LambdaApiUserSignUp")
            event = get_lambda_test_data(fullpath)
            event['body']['username'] = tester
            response = invoke(fullpath, event)
            assert response['body']
            body = json.loads(response['body'])
            if response['statusCode'] == STATUS_BAD_REQUEST:
                assert body['Code'] == "UsernameExistsException"
                payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
                # noinspection PyTypeChecker,PyUnusedLocal
                response = invoke(fullpath, payload)
            else:
                assert response['statusCode'] == STATUS_OK
                assert body['Username']

        if is_production():
            # noinspection PyBroadException,PyUnusedLocal
            event = get_lambda_test_data(get_lambda_fullpath("LambdaApiUserSignUp"))
            event['body']['username'] = tester
            event['body'].pop('newpassword', None)
            url = get_api_url(apigateway_client, 'API', '/v1', '/user/signup')
            response = requests.put(url, headers=event['headers'], data=json.dumps(event['body']))
            response_data = json.loads(response.text)
            if response.status_code == STATUS_BAD_REQUEST:
                assert response_data['Code'] == "UsernameExistsException"
                # noinspection PyUnusedLocal
                response = requests.get(url, params=event['body'])
            else:
                assert response.status_code == STATUS_OK

        # update database
        session = Session(region_name=get('aws_region_name'))

        data = {
            "username": tester,
            "avatar": "00000000-0000-0000-0000-000000000000"
        }
        # noinspection PyBroadException,PyUnusedLocal
        with User_profile.atomic():
            query = User_profile.update(**data).where(User_profile.username == tester)
            count = query.execute()
            assert count == 1
def really_delete_users():
    # Unconditionally Delete testers
    for tester in TESTERS:
        # noinspection PyBroadException,PyUnusedLocal
        try:
            event, fullpath = get_secure_event("LambdaApiUserContact")
            event['body']['username'] = tester
            payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
            response2 = invoke(fullpath, payload)
            if response2['statusCode'] == STATUS_OK:
                response_data = json.loads(response2['body'])
                assert 'TopicArn' in response_data
                assert response_data['TopicArn'].startswith("arn:aws:sns:")
                # noinspection PyShadowingBuiltins
                payload = {"httpMethod": "DELETE", "queryStringParameters": {"topic_arn": response_data['TopicArn']}}
                # noinspection PyTypeChecker
                response3 = invoke(fullpath, payload)
                assert response3['statusCode'] == STATUS_OK
        except Exception as ex:
            pass

        try:
            fullpath = get_lambda_fullpath("LambdaApiUserSignUp")
            event = get_lambda_test_data(fullpath, authorization_token=_ID_TOKEN)
            # noinspection PyTypeChecker
            event['httpMethod'] = 'DELETE'
            event['queryStringParameters'] = {
                'force': True,
                'username': tester
            }
            event.pop('body', None)
            if is_test():
                response2 = invoke(fullpath, event)
                assert response2  # "/user should return Status \"OK\"")
                assert response2.status_code == STATUS_OK
            elif is_production():
                url = get_api_url(apigateway_client, 'API', '/v1', '/user/signup')
                # noinspection PyUnusedLocal
                response3 = requests.delete(url, params=event['queryStringParameters'])
                assert response3.status_code != STATUS_FORBIDDEN

        # except cognito_idp_client.exceptions.UserNotFoundException as ex:
        except Exception as ex:
            logger.info(str(ex))
示例#9
0
def test():
    if is_test():
        fullpath = get_lambda_fullpath("LambdaApiSwagger")
        event = get_lambda_test_data(fullpath)
        # noinspection PyTypeChecker
        response1 = invoke(fullpath, event)
        assert response1['statusCode'] == STATUS_OK
        assert len(response1['body'])
        assert json.loads(response1['body'])

    elif is_production():
        fullpath = get_lambda_fullpath("LambdaApiSwagger")
        event = get_lambda_test_data(fullpath)
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/swagger')
        response3 = requests.get(url, params=event['queryStringParameters'])
        assert response3.status_code == STATUS_OK
        assert len(response3.text)
        assert json.loads(response3.text)
        with open("API.json", "w") as text_file:
            text_file.write(response3.text)
def test():
    if is_test():
        fullpath = get_lambda_fullpath("LambdaApiHealth")
        event = get_lambda_test_data(fullpath)
        # https://github.com/nficano/python-lambda
        # noinspection PyTypeChecker
        response1 = invoke(fullpath, event)
        assert response1 is not None
        assert response1['statusCode'] == STATUS_OK
        # dict'{"health": "OK", "statusCode": 200, "headers": {"Content-Type": "application/json"}}'
        response_data = json.loads(response1['body'])
        assert response_data['health'] == "OK"

    elif is_production():
        event = get_lambda_test_data(get_lambda_fullpath("LambdaApiHealth"))
        # http://docs.python-requests.org/en/master/user/quickstart
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/health')
        response2 = requests.get(url, params=event['queryStringParameters'])
        assert response2 is not None
        assert response2.status_code == STATUS_OK
        response_data = response2.json()
        # dict'{"health": "OK"}'
        assert response_data['health'] == "OK"
def test(empty_database, create_and_delete_user):
    if is_test():
        fullpath = get_lambda_fullpath("LambdaApiUsers")
        event = get_lambda_test_data(fullpath)
        # https://github.com/nficano/python-lambda
        response1 = invoke(fullpath, event)
        assert response1 is not None
        assert response1["statusCode"] == STATUS_OK
        assert "body" in response1
        body = response1['body']
        response_data = json.loads(body)
        assert response_data
        assert len(response_data)

    elif is_production():
        fullpath = get_lambda_fullpath("LambdaApiUsers")
        event = get_lambda_test_data(fullpath)
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/users')
        # http://docs.python-requests.org/en/master/user/quickstart
        response3 = requests.get(url, params=event['queryStringParameters'])
        assert response3.status_code == STATUS_OK
        response_data = response3.json()
        assert response_data
        assert len(response_data)
def test(empty_database, create_and_delete_user, create_login_session):
    if is_test():
        event, fullpath = get_secure_event("LambdaApiUserProfile")
        response1 = invoke(fullpath, event)
        assert response1['statusCode'] == STATUS_OK

        event, fullpath = get_secure_event("LambdaApiMedia")
        payload = {"httpMethod": "PUT", "body": event['body']}
        # noinspection PyTypeChecker
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK

        event, fullpath = get_secure_event("LambdaApiMediaQuery")
        payload = {"httpMethod": "POST", "body": event['body']}
        # noinspection PyTypeChecker
        response3 = invoke(fullpath, payload)
        assert response3['statusCode'] == STATUS_OK

        event, fullpath = get_secure_event("LambdaApiMediaQuery")
        event['body'].pop('description', None)
        event['body'].pop('tags', None)
        event['body'].pop('likes', None)
        payload = {"httpMethod": "POST", "body": event['body']}
        # noinspection PyTypeChecker
        response4 = invoke(fullpath, payload)
        assert response4['statusCode'] == STATUS_OK

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiMediaQuery")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/media/query')
        response5 = requests.post(url,
                                  headers=event['headers'],
                                  data=json.dumps(event['body']))
        assert response5.status_code == STATUS_OK
        data = json.loads(response5.text)
示例#13
0
def test(empty_database, create_and_delete_user, create_login_session):
    cognito_idp_client = boto3.client('cognito-idp')
    if is_test():
        event, fullpath = get_secure_event("LambdaApiUserBlocked")
        response1 = invoke(fullpath, event)
        assert response1['statusCode'] == STATUS_OK

        event, fullpath = get_secure_event("LambdaApiUserBlocked")
        payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK
        response_data = json.loads(response2['body'])
        assert response_data['blocked']

        payload = {
            "httpMethod": "DELETE",
            "queryStringParameters": {
                "id": response_data["id"]
            }
        }
        response3 = invoke(fullpath, payload)
        assert response3['statusCode'] == STATUS_OK

        # negative test
        payload = {
            "httpMethod": "GET",
            "queryStringParameters": {
                "recipient_username": "******",
                "blocked_username": event['body']['blocked_username']
            }
        }
        response4 = invoke(fullpath, payload)
        assert response4['statusCode'] == STATUS_NOT_FOUND
        response_data = json.loads(response4['body'])
        assert response_data['Message']

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiUserBlocked")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/blocked')

        response5 = requests.put(url,
                                 headers=event['headers'],
                                 data=json.dumps(event['body']))
        assert response5.status_code == STATUS_OK

        response6 = requests.get(url,
                                 headers=event['headers'],
                                 params=event['body'])
        assert response6.status_code == STATUS_OK
        response_data = json.loads(response6.text)

        response7 = requests.delete(url,
                                    headers=event['headers'],
                                    params={"id": response_data["id"]})
        assert response7.status_code == STATUS_OK

        # negative test
        event['body']['recipient_username'] = "******"
        response8 = requests.get(url,
                                 headers=event['headers'],
                                 params=event['body'])
        assert response8.status_code == STATUS_NOT_FOUND
        response_data = json.loads(response8.text)
        assert response_data
def test(empty_database, create_and_delete_user, create_login_session):
    from ..conftest import _ID_TOKEN
    if is_test():
        fullpath = get_lambda_fullpath("LambdaApiUserSignUp")
        event = get_lambda_test_data(fullpath)
        # Read user TESTER1
        payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
        # noinspection PyTypeChecker
        response1 = invoke(fullpath, payload)
        assert response1['statusCode'] == STATUS_OK
        assert len(response1['body'])
        response_data = json.loads(response1['body'])
        assert response_data['Username']
        username = response_data['Username']
        assert 'UserAttributes' in response_data
        # TODO: iterate through UserAttributes list and verify given_name and family_name
        # assert any(event['username'] in s['username'] for s in data)
        # assert event['body']['given_name'] == response_data['given_name']
        # assert event['body']['family_name'] == response_data['family_name']
        assert 'UserCreateDate' in response_data
        assert 'UserLastModifiedDate' in response_data
        assert 'Enabled' in response_data
        assert 'UserStatus' in response_data

        # Update user TESTER1
        event = get_lambda_test_data(fullpath, authorization_token=_ID_TOKEN)
        event['body'].pop('password', None)
        event['body'].pop('newpassword', None)
        event['body']['authorization_token'] = _ID_TOKEN
        event['body']['username'] = username
        payload = {"httpMethod": "POST", "body": event['body']}
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK
        assert len(response2['body'])
        response_data = json.loads(response2['body'])
        assert response_data['Username']
        assert 'UserCreateDate' in response_data
        assert 'UserLastModifiedDate' in response_data
        assert 'Enabled' in response_data
        assert 'UserStatus' in response_data

        # Get errors
        event['body'][
            'username'] = "******"
        payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
        response4 = invoke(fullpath, payload)
        assert response4['statusCode'] == STATUS_BAD_REQUEST
        response_data = json.loads(response4['body'])
        assert response_data['Message'] == 'User does not exist.'
        # assert response_data['Code'] == 'UserNotFoundException'

        # event['body'].pop('username', None)
        # event['body']['xyzzy'] = "*****@*****.**"
        # payload = {"httpMethod": "GET", "queryStringParameters": event['body']}
        # response5 = invoke(fullpath, payload)
        # assert response5['statusCode'] == STATUS_BAD_REQUEST
        # response_data = json.loads(response5['body'])
        # assert response_data['Message'] == 'Param ["username"] is not valid'

    elif is_production():
        fullpath = get_lambda_fullpath("LambdaApiUserSignUp")
        event = get_lambda_test_data(fullpath)
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/user/signup')
        response6 = requests.get(url, params=event['body'])
        assert response6.status_code == STATUS_OK

        response_data = response6.json()
        event['body']['username'] = response_data['Username']
        event['body']['password'] = event['body']['newpassword']
        event['body'].pop('email', None)
        event['body'].pop('newpassword', None)
        event['body'].pop('aws_access_key_id', None)
        event['body'].pop('aws_secret_access_key', None)
        event['body'].pop('aws_account_id', None)

        response7 = requests.post(url,
                                  headers=event['headers'],
                                  data=json.dumps(event['body']))
        assert response7.status_code == STATUS_OK
def test(empty_database, create_and_delete_user, create_login_session):
    cognito_idp_client = boto3.client('cognito-idp')
    event, fullpath = get_secure_event("LambdaApiUserProfile")
    response1 = invoke(fullpath, event)
    assert response1['statusCode'] == STATUS_OK
    response_data = json.loads(response1['body'])
    username = response_data['username']
    if is_test():
        event, fullpath = get_secure_event("LambdaApiMedia")
        event['body']['username'] = username
        payload = {"httpMethod": "PUT", "body": event['body']}
        # noinspection PyTypeChecker
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK

        payload = {
            "httpMethod": "GET",
            "queryStringParameters": {
                "media_uuid": event['body']['media_uuid']
            }
        }
        # noinspection PyTypeChecker
        response3 = invoke(fullpath, payload)
        assert response3['statusCode'] == STATUS_OK
        response_data = json.loads(response3['body'])
        assert response_data['likes'] == event['body']['likes']

        event, fullpath = get_secure_event("LambdaApiMedia")
        new_likes = event['body']['likes'] + 1
        event['body']['likes'] = new_likes
        payload = {"httpMethod": "POST", "body": event['body']}
        # noinspection PyTypeChecker
        response4 = invoke(fullpath, payload)
        assert response4['statusCode'] == STATUS_OK

        payload = {
            "httpMethod": "GET",
            "queryStringParameters": {
                "media_uuid": event['body']['media_uuid']
            }
        }
        # noinspection PyTypeChecker
        response5 = invoke(fullpath, payload)
        assert response5['statusCode'] == STATUS_OK
        response_data = json.loads(response5['body'])
        assert response_data['likes'] == new_likes

        payload = {
            "httpMethod": "DELETE",
            "queryStringParameters": {
                "media_uuid": event['body']['media_uuid']
            }
        }
        # noinspection PyTypeChecker
        response6 = invoke(fullpath, payload)
        assert response6['statusCode'] == STATUS_OK

    elif is_production():
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/media')
        event, fullpath = get_secure_event("LambdaApiMedia")
        event['body']['username'] = username
        response7 = requests.put(url,
                                 headers=event['headers'],
                                 data=json.dumps(event['body']))
        assert response7.status_code == STATUS_OK
        response_data = json.loads(response7.text)

        media_uuid = response_data['media_uuid']
        response8 = requests.get(url,
                                 headers=event['headers'],
                                 params={"media_uuid": media_uuid})
        assert response8.status_code == STATUS_OK

        event['body']['likes'] = 4
        event['body']['media_uuid'] = media_uuid
        response9 = requests.post(url,
                                  headers=event['headers'],
                                  data=json.dumps(event['body']))
        assert response9.status_code == STATUS_OK

        response10 = requests.delete(url,
                                     headers=event['headers'],
                                     params={"media_uuid": media_uuid})
        assert response10.status_code == STATUS_OK

        # negative test
        response11 = requests.get(url,
                                  headers=event['headers'],
                                  params={"media_uuid": media_uuid})
        assert response11.status_code == STATUS_NOT_FOUND
def test_local(empty_database, fixture_directory, create_and_delete_user,
               create_login_session):
    if is_test():
        event, fullpath = get_secure_event("LambdaApiMediaUploadUrl")
        payload = {"httpMethod": "GET"}
        # noinspection PyTypeChecker
        response2 = invoke(fullpath, payload)
        assert response2['statusCode'] == STATUS_OK
        data = json.loads(response2['body'])
        assert len(data) == 2
        media_uuid = data['media_uuid']
        assert len(media_uuid)

        url = data['url']
        assert len(url)
        # headers = {'Content-Type': 'image/jpeg'}
        # https://stackoverflow.com/questions/8710456/reading-a-binary-file-with-python
        with open(fixture_directory + "/image.jpeg",
                  mode='rb') as file:  # b is important -> binary
            file_content = file.read()
        # files = {"file": open(fixture_directory + "/image.jpeg", 'rb')}
        files = {"file": file_content}
        response3 = requests.put(url, files=files)
        assert response3.status_code == STATUS_OK or response3.status_code == STATUS_OK_NO_CONTENT

        event, fullpath = get_secure_event("LambdaApiMediaDownloadUrl")
        event["queryStringParameters"]["media_uuid"] = data['media_uuid']
        payload = {
            "httpMethod": "GET",
            "queryStringParameters": event["queryStringParameters"]
        }
        # noinspection PyTypeChecker
        response4 = invoke(fullpath, payload)
        assert response4['statusCode'] == STATUS_OK
        url = json.loads(response4['body'])['url']

        response5 = requests.get(url)
        assert response5.status_code == STATUS_OK

        event, fullpath = get_secure_event("LambdaApiMedia")
        payload = {
            "httpMethod": "DELETE",
            "queryStringParameters": {
                "media_uuid": media_uuid
            }
        }
        # noinspection PyTypeChecker
        response3 = invoke(fullpath, payload)
        assert response3['statusCode'] == STATUS_OK

    elif is_production():
        event, fullpath = get_secure_event("LambdaApiMediaUploadUrl")
        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/media/uploadurl')
        response6 = requests.get(url, headers=event['headers'])
        assert response6.status_code == STATUS_OK
        data = json.loads(response6.text)

        s3_url = data['url']
        assert len(s3_url)

        media_uuid = data['media_uuid']
        assert len(media_uuid)

        # headers = {'Content-Type': 'image/jpeg'}
        files = {"file": open(fixture_directory + "/image.jpeg", 'rb')}

        # response = requests.post(s3_url, data=fields, files=open(fixture_directory + "/image.jpeg", 'rb'))
        response7 = requests.put(s3_url, files=files)
        assert response7.status_code == STATUS_OK or response7.status_code == STATUS_OK_NO_CONTENT

        url = get_api_url(boto3.client("apigateway"), 'API', '/v1',
                          '/media/downloadurl')
        # noinspection PyTypeChecker
        response8 = requests.get(url,
                                 headers=event['headers'],
                                 params={"media_uuid": media_uuid})
        assert response8.status_code == STATUS_OK
        data = json.loads(response8.text)

        response9 = requests.get(data['url'])
        assert response9.status_code == STATUS_OK

        url = get_api_url(boto3.client("apigateway"), 'API', '/v1', '/media')
        response9 = requests.delete(url,
                                    headers=event['headers'],
                                    params={"media_uuid": media_uuid})
        assert response9.status_code == STATUS_OK