Best Python code snippet using Testify_python
test_api_actions.py
Source:test_api_actions.py  
...50    login = Login(run_as_user=None, request=request)51    assert not login.run()52    assert 'jwt' not in login.response53    # teardown the test54    assert _test_teardown()55def test_change_password() -> None:56    """57    Test the change password action58    :return: None59    """60    # set up the test61    assert _test_setup()62    user, plain_text = _get_sample_user('admin')63    assert add_user_to_system(user)64    # create the request and run the action - valid change password65    request = {66        'password0': plain_text,67        'password1': 'mys@f#newpasw#rd',68        'password2': 'mys@f#newpasw#rd'69    }70    chpass = ChangePassword(run_as_user=user, request=request)71    assert chpass.run()72    # check that the password was really changed73    user_ = get_user_from_system(user.email)74    assert user_.validate_password('mys@f#newpasw#rd')75    # create the request and run the action - change anonymous user password76    request = {77        'password0': plain_text,78        'password1': 'mys@f#newpasw#rd',79        'password2': 'mys@f#newpasw#rd'80    }81    chpass = ChangePassword(run_as_user=None, request=request)82    assert not chpass.run()83    # create the request and run the action - new passwords do not match84    request = {85        'password0': 'mys@f#newpasw#rd',86        'password1': 'fdsafdsafdsa',87        'password2': 'asdfasdfasdf'88    }89    chpass = ChangePassword(run_as_user=user, request=request)90    assert not chpass.run()91    # check that the password was not changed92    user_ = get_user_from_system(user.email)93    assert user_.validate_password('mys@f#newpasw#rd')94    # create the request and run the action - invalid current password95    request = {96        'password0': 'myWRONGpasw#rd',97        'password1': 'asdfasdfasdf',98        'password2': 'asdfasdfasdf'99    }100    chpass = ChangePassword(run_as_user=user, request=request)101    assert not chpass.run()102    # check that the password was not changed103    user_ = get_user_from_system(user.email)104    assert user_.validate_password('mys@f#newpasw#rd')105def test_invalid_request_parameters() -> None:106    """107    Check error handling for invalid request parameters108    :return: None109    """110    # set up the test111    assert _test_setup()112    user, plain_text = _get_sample_user('admin')113    assert add_user_to_system(user)114    # create the request and run the action - invalid request parameters115    request = {116        'email': user.email,117        'wrong_key': plain_text118    }119    login = Login(request=request)120    assert not login.run()121    assert not login.success122    assert 'jwt' not in login.response123    # teardown the test124    assert delete_user_from_system(user)125    assert _test_teardown()126def test_setup_new_user() -> None:127    """128    Test the CreateUser action129    :return: None130    """131    # set up the test132    assert _test_setup()133    admin, plain_text = _get_sample_user('admin')134    assert add_user_to_system(admin)135    # create the request to create a new user136    reg_user, user_pw = _get_sample_user('regular')137    request = {138        'user': {139            'full_name': reg_user.full_name,140            'email': reg_user.email,141            'role_id': reg_user.role_id142        }143    }144    # create and run the action145    action = CreateUser(run_as_user=admin, request=request)146    assert action.run()147    assert action.success148    assert not action.errors149    # get the new user from the database150    user = get_user_from_system(reg_user.email)151    assert user is not None152    assert not user.active153    assert user.password is None154    assert user.reset_token is None155    assert not user.validate_password('None')156    assert not user.validate_password(None)157    assert not user.validate_password('')158    # activate the user with a new action159    request = {160        'email': user.email,161        'activation_key': user.activation_key,162        'new_password': user_pw163    }164    action = ActivateUser(run_as_user=None, request=request)165    assert action.run()166    assert action.success167    assert not action.errors168    # get the updated user from the database169    user = get_user_from_system(user.email)170    assert user is not None171    assert user.active172    assert user.validate_password(user_pw)173    # run the action again -- should fail174    assert not action.run()175    assert not action.success176    assert 'Account is already active' in action.errors177    # teardown the test178    assert _test_teardown()179def test_user_with_same_email() -> None:180    """181    Try to set up a new user with the same email as another user182    """183    # set up the test case184    assert _test_setup()185    admin, plain_text = _get_sample_user('admin')186    assert add_user_to_system(admin)187    # try to create a new user with the same email address188    reg_user, _ = _get_sample_user('regular')189    request = {190        'user': {191            'full_name': reg_user.full_name,192            'email': admin.email,193            'role_id': reg_user.role_id194        }195    }196    action = CreateUser(run_as_user=admin, request=request)197    assert not action.run()198    assert not action.success199    assert 'Email address is already in use' in action.errors200    # teardown the test case201    assert _test_teardown()202def test_activate_user_twice() -> None:203    """204    Try to activate the user again with the same activation key205    """206    # set up the test case207    assert _test_setup()208    admin, plain_text = _get_sample_user('admin')209    admin.active = True210    assert add_user_to_system(admin)211    # create an activation request212    request = {213        'email': admin.email,214        'activation_key': admin.activation_key,215        'new_password': plain_text216    }217    action = ActivateUser(run_as_user=None, request=request)218    assert not action.run()219    assert not action.success220    assert 'Account is already active' in action.errors221    # teardown the test case222    assert _test_teardown()223def test_activate_user_with_weak_password() -> None:224    """225    Try to activate the user again with the same activation key226    """227    # set up the test case228    assert _test_setup()229    admin, _ = _get_sample_user('admin')230    admin.active = False231    assert not admin.active232    assert add_user_to_system(admin)233    # create an activation request234    request = {235        'email': admin.email,236        'activation_key': admin.activation_key,237        'new_password': 'abc123'238    }239    action = ActivateUser(run_as_user=None, request=request)240    assert not action.run()241    assert not action.success242    assert 'Password must be at least 10 characters long' in action.errors243    # teardown the test case244    assert _test_teardown()245def test_activate_unknown_user() -> None:246    """247    Try to activate a user not in the system248    """249    # set up test case250    assert _test_setup()251    # create an activate request252    reg_user, plain_text = _get_sample_user('regular')253    request = {254        'email': reg_user.email,255        'activation_key': reg_user.activation_key,256        'new_password': plain_text257    }258    action = ActivateUser(run_as_user=None, request=request)259    assert not action.run()260    assert not action.success261    assert 'Invalid activation key' in action.errors262    # teardown the test case263    assert _test_teardown()264def test_list_users() -> None:265    """266    Test the action to list all users in the system267    """268    # set up the test269    _test_setup()270    users = _get_all_sample_users()271    for user in users:272        assert add_user_to_system(user)273    # create a list users request274    admin, _ = _get_sample_user('regular')275    request = {}276    action = ListUsers(run_as_user=admin, request=request)277    assert action.run()278    assert action.success279    assert len(action.response['users']) == len(users)280    for user_data in action.response['users']:281        for attr in ['email', 'full_name', 'role_id']:282            assert attr in user_data283        for sani_key in User.SANITIZE_KEYS:284            assert sani_key not in user_data285    # teardown the test case286    assert _test_teardown()287def test_update_user() -> None:288    """289    Test the action to update a user in the system290    """291    # set up the test292    _test_setup()293    user, _ = _get_sample_user('regular')294    admin, _ = _get_sample_user('admin')295    assert add_user_to_system(user)296    assert add_user_to_system(admin)297    # create an update user request298    request = {299        'user': {300            'email': user.email,301            'full_name': 'Joe Bauers'302        }303    }304    action = UpdateUser(run_as_user=admin, request=request)305    assert action.run()306    assert action.success307    response_user = User(action.response['user'])308    assert response_user.email == user.email309    assert response_user.full_name == 'Joe Bauers'310    db_user = get_user_from_system(user.email)311    assert db_user.full_name == 'Joe Bauers'312    # teardown the test case313    assert _test_teardown()314def test_update_unknown_user() -> None:315    """316    Test the action to update a user in the system317    """318    # set up the test319    _test_setup()320    user, _ = _get_sample_user('regular')321    admin, _ = _get_sample_user('admin')322    assert add_user_to_system(admin)323    # create an update user request324    request = {325        'user': {326            'email': user.email,327            'full_name': 'Joe Bauers'328        }329    }330    action = UpdateUser(run_as_user=admin, request=request)331    assert not action.run()332    assert not action.success333    assert 'Unknown user' in action.errors334    # teardown the test case335    assert _test_teardown()336def test_delete_user() -> None:337    """338    Test the delete user action339    """340    # set up the test341    assert _test_setup()342    admin, _ = _get_sample_user('admin')343    user, _ = _get_sample_user('regular')344    assert add_user_to_system(admin)345    assert add_user_to_system(user)346    # create a request to delete a user347    request = {'email': user.email}348    action = DeleteUser(run_as_user=admin, request=request)349    assert action.run()350    assert action.success351    # teardown the test352    assert _test_teardown()353def test_delete_unknown_user() -> None:354    """355    Test the delete user action356    """357    # set up the test358    assert _test_setup()359    admin, _ = _get_sample_user('admin')360    user, _ = _get_sample_user('regular')361    assert add_user_to_system(admin)362    # create a request to delete a user363    request = {'email': user.email}364    action = DeleteUser(run_as_user=admin, request=request)365    assert not action.run()366    assert not action.success367    assert 'User not found' in action.errors368    # teardown the test369    assert _test_teardown()370def test_whoami() -> None:371    """372    Test the whoami action373    """374    # set up the test375    assert _test_setup()376    user, _ = _get_sample_user('regular')377    assert add_user_to_system(user)378    # create a request to get a user's own information379    request = {}380    action = WhoAmI(run_as_user=user, request=request)381    assert action.run()382    assert action.success383    assert 'user' in action.response384    assert 'active' not in action.response['user']385    # teardown the test386    assert _test_teardown()387def test_password_reset() -> None:388    """389    Test the password reset process390    """391    # set up the test392    assert _test_setup()393    user, _ = _get_sample_user('regular')394    assert add_user_to_system(user)395    # create a request to add a reset token396    assert user.reset_token is None397    request = {'email': user.email}398    action = AddPasswordResetToken(run_as_user=None, request=request)399    assert action.run()400    assert action.success401    user_ = get_user_from_system(user.email)402    assert user_.get_seconds_since_reset_token_sent() < 10403    token = user_.reset_token.split(';')[1]404    assert user_.validate_reset_token(token)405    # try to set another reset token too quickly406    action = AddPasswordResetToken(run_as_user=None, request=request)407    assert not action.run()408    assert not action.success409    assert 'An email was recently sent.' in action.errors410    # user the reset token to reset the password411    request = {412        'email': user_.email,413        'reset_token': user_.reset_token.split(';')[1],414        'new_password': '100shredsOFcabbage'415    }416    action = ResetPassword(run_as_user=None, request=request)417    assert action.run()418    assert action.success419    # verify the password was changed420    user_ = get_user_from_system(user_.email)421    assert user_.validate_password('100shredsOFcabbage')422    # teardown the test423    assert _test_teardown()424def test_reset_password_for_unknown_user() -> None:425    """426    Try to reset a password for an unknown user427    """428    # set up test case429    assert _test_setup()430    # create a request431    request = {432        'email': 'unknown@example.com',433        'reset_token': User().reset_token,434        'new_password': '100shredsOFcabbage'435    }436    action = ResetPassword(run_as_user=None, request=request)437    assert not action.run()438    assert not action.success439    assert 'Password reset failed' in action.errors440    # teardown test case441    assert _test_teardown()442def test_reset_password_with_invalid_token() -> None:443    """444    Try to reset a password with a wrong445    """446    # set up test case447    assert _test_setup()448    user, _ = _get_sample_user('regular')449    assert add_user_to_system(user)450    # test with no reset token set in the system user451    request = {452        'email': user.email,453        'reset_token': User().reset_token,454        'new_password': '100shredsOFcabbage'455    }456    action = ResetPassword(run_as_user=None, request=request)457    assert not action.run()458    assert not action.success459    assert 'Password reset failed' in action.errors460    # test with a valid reset token set in the system user461    user.reset_token = User().reset_token462    assert update_user_in_system(user)463    request = {464        'email': user.email,465        'reset_token': User().reset_token,  # get a random token value466        'new_password': '100shredsOFcabbage'467    }468    action = ResetPassword(run_as_user=None, request=request)469    assert not action.run()470    assert not action.success471    assert 'Password reset failed' in action.errors472    # teardown test case473    assert _test_teardown()474def test_refresh_token() -> None:475    """476    Test the action to get a new JWT with a refresh token477    """478    # set up test case479    assert _test_setup()480    user, _ = _get_sample_user('regular')481    assert add_user_to_system(user)482    # artificially inject a refresh token into the system and create a valid JWT483    jwt = create_jwt({'email': user.email, 'role_id': user.role_id})484    refresh_token = issue_refresh_token(user)485    # create a request to renew a JWT486    request = {487        'email': user.email,488        'refresh_token': refresh_token489    }490    action = RefreshToken(run_as_user=user, request=request)491    assert action.run()492    new_jwt = action.response['jwt']493    new_refresh_token = action.response[action.REQ_KEY_REFRESH]494    # make sure we have new jwt and refresh tokens495    assert new_jwt is not None496    assert new_refresh_token is not None497    assert new_jwt != jwt498    assert new_refresh_token != refresh_token499    assert validate_jwt(new_jwt)500    # make sure the old refresh token was removed501    assert get_refresh_token(refresh_token) is None502    assert get_refresh_token(new_refresh_token) is not None503    # teardown test case...test_api_handler.py
Source:test_api_handler.py  
...43    payload = validate_jwt(login_response['data']['jwt'])44    assert payload is not None45    assert payload[wrfcloud.api.auth.KEY_EMAIL] == user.email46    # teardown the test47    assert _test_teardown()48def test_lambda_handler_insufficient_permissions() -> None:49    """50    Test the lambda handler with a user with insufficient permissions to run the request51    :return: None52    """53    # set up the test54    assert _test_setup()55    user, plain_text = _get_sample_user('admin')56    # create a login request57    chpass_request = {58        'action': 'ChangePassword',59        'data': {60            'password0': plain_text,61            'password1': 'newpassword',62            'password2': 'newpassword'63        }64    }65    event = {66        'body': json.dumps(chpass_request),67        'requestContext': {68            'identity': {69                'sourceIp': '10.0.0.151'70            }71        }72    }73    response = lambda_handler(event, None)74    chpass_response = json.loads(response['body'])75    assert not chpass_response['ok']76    assert 'This action is unauthorized' in chpass_response['errors']77    # teardown the test78    assert _test_teardown()79def test_lambda_handler_action_failed() -> None:80    """81    Test the lambda handler with a request that will fail82    :return: None83    """84    # set up the test85    assert _test_setup()86    user, plain_text = _get_sample_user('admin')87    assert add_user_to_system(user)88    # create a login request89    jwt = create_jwt({90        KEY_EMAIL: user.email,91        KEY_ROLE: user.role_id92    })93    chpass_request = {94        'action': 'ChangePassword',95        'jwt': jwt,96        'data': {97            'password0': 'wrong-password',98            'password1': 'newpassword',99            'password2': 'newpassword'100        }101    }102    event = {103        'body': json.dumps(chpass_request),104        'requestContext': {105            'identity': {106                'sourceIp': '10.0.0.151'107            }108        }109    }110    response = lambda_handler(event, None)111    chpass_response = json.loads(response['body'])112    assert not chpass_response['ok']113    assert 'Current password is not correct' in chpass_response['errors']114    # teardown the test115    assert _test_teardown()116def test_lambda_handler_expired_token() -> None:117    """118    Test the lambda handler function119    :return: None120    """121    # set up the test122    assert _test_setup()123    # create a login request124    user, plain_text = _get_sample_user('admin')125    jwt = create_jwt({126        'email': user.email,127        'role': user.role_id128    }, -1)129    chpass_request = {130        'action': 'ChangePassword',131        'jwt': jwt,132        'data': {133            'password0': plain_text,134            'password1': 'newpassword',135            'password2': 'newpassword'136        }137    }138    event = {139        'body': json.dumps(chpass_request),140        'requestContext': {141            'identity': {142                'sourceIp': '10.0.0.151'143            }144        }145    }146    response = lambda_handler(event, None)147    chpass_response = json.loads(response['body'])148    assert not chpass_response['ok']149    assert 'Please log in first' in chpass_response['errors']150    # teardown the test151    assert _test_teardown()152def test_lambda_handler_unknown_role() -> None:153    """154    Test the lambda handler function155    :return: None156    """157    # set up the test158    assert _test_setup()159    user, plain_text = _get_sample_user('admin')160    assert add_user_to_system(user)161    # update the user's role to something unexpected162    user.role_id = 'doubleadmin'163    assert update_user_in_system(user)164    # create a login request165    jwt = create_jwt({166        KEY_EMAIL: user.email,167        KEY_ROLE: user.role_id168    })169    chpass_request = {170        'action': 'ChangePassword',171        'jwt': jwt,172        'data': {173            'password0': plain_text,174            'password1': 'newpassword',175            'password2': 'newpassword'176        }177    }178    event = {179        'body': json.dumps(chpass_request),180        'requestContext': {181            'identity': {182                'sourceIp': '10.0.0.151'183            }184        }185    }186    response = lambda_handler(event, None)187    chpass_response = json.loads(response['body'])188    assert not chpass_response['ok']189    assert 'This action is unauthorized' in chpass_response['errors']190    # teardown the test...test_dynamodb.py
Source:test_dynamodb.py  
...24    for key in item:25        assert key in item_26        assert item[key] == item_[key]27    # teardown the test resources28    assert _test_teardown()29def test_update_and_read_item() -> None:30    """31    Test the operations to update and read an item32    :return: None33    """34    # set up the test resources35    assert _test_setup()36    # create sample data in item37    item = {'id': 'dynamo1', 'my_value': 11}38    # create DAO and add the item to the database39    dao = DynamoDao(TABLE, KEY_FIELDS, ENDPOINT_URL)40    assert dao.put_item(item)41    # update the item in the table42    item['my_value'] = 1543    assert dao.update_item(item)44    # retrieve the item from the table and check the new expected value45    item_ = dao.get_item({'id': 'dynamo1'})46    assert item_['my_value'] == 1547    # teardown the test resources48    assert _test_teardown()49def test_create_and_delete_item() -> None:50    """51    Test the operations to create and delete an item52    :return: None53    """54    # set up the test resources55    assert _test_setup()56    # create sample data in item57    item = {'id': 'dynamo1', 'my_value': 11}58    # create DAO and add the item to the database59    dao = DynamoDao(TABLE, KEY_FIELDS, ENDPOINT_URL)60    assert dao.put_item(item)61    # retrieve the item from the table62    item_ = dao.get_item({'id': 'dynamo1'})63    assert item_ is not None64    # delete the item from the table65    dao.delete_item(item)66    # retrieve the item from the table (expected to be missing)67    item_ = dao.get_item({'id': 'dynamo1'})68    assert item_ is None69    # teardown the test resources70    assert _test_teardown()71def test_create_and_get_all_items() -> None:72    """73    Test the operations to create and delete an item74    :return: None75    """76    # set up the test resources77    assert _test_setup()78    # create dao79    dao = DynamoDao(TABLE, KEY_FIELDS, ENDPOINT_URL)80    # get all items (none expected)81    items = dao.get_all_items()82    assert not items83    # create sample data84    for n in range(50):85        item = {'id': f'dynamo{n}', 'my_value': n*n}86        assert dao.put_item(item)87    # retrieve all items from the table88    items = dao.get_all_items()89    assert len(items) == 5090    # teardown the test resources91    assert _test_teardown()92def test_create_complex_item() -> None:93    """94    Test the operations to create a complex item95    :return: None96    """97    # set up the test resources98    assert _test_setup()99    # create dao100    dao = DynamoDao(TABLE, KEY_FIELDS, ENDPOINT_URL)101    # create complex item102    item = {103        'id': 'dynamo2',104        'my_value': 56,105        'flags': [True, False, False, True],106        'string_set': ['WRF', 'MPAS', 'FV3'],107        'number_set': [22, 443, 576],108        'mixed_set': [True, 'MPAS', 576],109        'new_map': {110            'variables': ['U10', 'V10', 'T2', 'Q'],111            'compilers': ['Intel oneAPI', 'GNU'],112            'lucky_numbers': ['sqrt(-1)', 8, 3.141592654]113        }114    }115    # put the item into the table116    assert dao.put_item(item)117    # get the item from the table118    item2_ = dao.get_item({'id': 'dynamo2'})119    assert item2_ is not None120    assert item2_['new_map']['lucky_numbers'][1] == 8121    # teardown the test resources122    assert _test_teardown()123def _test_setup() -> bool:124    """125    Setup required test resources (i.e. DynamoDB table in local dynamodb)126    :return: True if successful, otherwise False127    """128    dao = DynamoDao(TABLE, KEY_FIELDS, 'http://localhost:8000')129    try:130        # just in case the table already exists, get rid of it131        dao.delete_table(TABLE)132    except Exception:133        pass134    try:135        # create the table136        return dao.create_table(ATTRIBUTE_DEFINITIONS, KEY_SCHEMA)137    except Exception as e:138        print(e)139        return False140def _test_teardown() -> bool:141    """142    Delete resources created by the tests143    :return: True if successful, otherwise False144    """145    try:146        # get a dynamodb client pointing to local dynamodb147        client = boto3.client('dynamodb', endpoint_url=ENDPOINT_URL)148        # delete the table149        client.delete_table(TableName=TABLE)150    except Exception as e:151        print(e)152        return False...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
