def test_add_two_users_with_same_email(self, api_client: ApiClient): """Test that it is impossible to create two users with same email Steps: - Make request to application with path /api/add_user and JSON in valid format - Make another request to application with path /api/add_user but different username and password Expected results: Status code for the first request is in 200-300 range Status code for the first request is in 400-500 range """ username, email, password = make.auth_data() username2, _, password2 = make.auth_data(email=email) with allure.step( 'Add the first user and check status code is in range 200 to 300' ): response = api_client.add_user(username=username, email=email, password=password) attach_http(response, '1') assert response.status_code in range(200, 300) with allure.step( 'Add the second user and check status code is in range 400 to 500' ): response2 = api_client.add_user(username=username2, email=email, password=password2) attach_http(response2, '2') assert response2.status_code in range(400, 500)
def test_added_users(self, username, email, password, api_client: ApiClient): """Tests that users blocked Steps: - Make request to application with path /api/add_user and JSON in valid format - Make request to application with path /api/block_user/<username> - Make request to application with path /api/block_user/<username> again Expected results: Status code for the first request is in 200-300 range Status code for the second request is 200 Status code for the third request is 304 """ response = api_client.add_user(username=username, email=email, password=password) attach_http(response, '1') if response.status_code not in range(200, 300): raise Exception('there was error with add_user function') with allure.step('Block user'): response2 = api_client.block_user(username) attach_http(response2, '2') assert response2.status_code == status_codes.OK with allure.step('Block user again'): response3 = api_client.block_user(username) attach_http(response3, '3') assert response3.status_code == status_codes.NOT_CHANGED
def api_client(settings: Settings, admin_keys: Keys): """Return `ApiClient` object with valid `Keys` You can test API without authorization through web interface each time You should use it to test API as authorized user""" ApiClient.netloc = settings.app_api_netloc ApiClient.admin_keys = admin_keys return ApiClient()
def put(self): form_id = self.request.matchdict.get('form_id') result = ApiClient( ConfigurationWrapper.get_auth('admin')).form_client.create_form( self.user.id, id=form_id) if not result.is_success: return {'user': self.user, 'error': result.data} return HTTPOkWithRedirect('/admin/form/' + form_id)
def create(self): client = ApiClient(ConfigurationWrapper.get_auth('admin')) form_id = self.request.matchdict.get('form_id') place_id = self.request.matchdict.get('place_id') result = client.form_client.create_binding(form_id, place_id) if not result.is_success: return {'error': result.data, 'user': self.user} return HTTPOkWithRedirect('/admin/form/%s/place' % form_id)
def delete(self): form_id = self.request.matchdict.get('form_id') result = ApiClient(ConfigurationWrapper.get_auth( 'admin')).form_client.delete_form(form_id) if not result.is_success: logging.warning("Fail to delete form '%s': %s" % (form_id, result.data.message)) return HTTPOkWithRedirect('/admin/form')
def index(req: Request): client = ApiClient(ConfigurationWrapper.get_auth("map")) form = client.form_client.get_form(req.params.get("id")) place_id = client.form_client.get_form(req.params.get("place_id")) return { 'inputs': json.loads(form.data.content), 'place_id': place_id, 'form_id': req.params.get("id") }
def load_user(request: Request) -> User: client = ApiClient(ConfigurationWrapper.get_auth('admin')) if not (hasattr(request, 'session') and request.session is not None): AuthorizationPolicy(ConfigurationWrapper.get_auth('admin')).authenticated_userid(request) if hasattr(request, 'session') and request.session is not None: result = client.users_client.load(request.session.user_id) if not result.is_success: logging.warning("Fail to load user for session '" + request.session.session_id + "': " + result.data.message) raise Exception(result.data) return result.data return None
def edit(self): answer_id = self.request.matchdict.get('answer_id') answer = dict() for id in self.request.params: answer[id] = self.request.params[id] answer = json.dumps(answer) result = ApiClient( ConfigurationWrapper.get_auth('admin')).form_client.set_answer( answer_id, answer) if not result.is_success: return {'user': self.user, 'error': result.data} return self.get('Ответ записан')
def register(self): login = self.request.params.get('login') email = self.request.params.get('email') new_password1 = self.request.params.get('new_password1') new_password2 = self.request.params.get('new_password2') if new_password1 != new_password2: return {'error': 'Пароли не совпадают'} client = ApiClient(ConfigurationWrapper.get_auth('map')) result = client.users_client.create(login, new_password1, email) if not result.is_success: return {'error': 'Логин занят'} return HTTPOkWithRedirect('/enter')
def __call__(self): client = ApiClient(ConfigurationWrapper.get_auth('admin')) skip = int(self.request.params.get('skip', 0)) take = int(self.request.params.get('take', 50000)) result = client.permission_client.get_user_permissions (self.user.id, skip, take) if not result.is_success: raise Exception(result.data) return { 'user': self.user, 'permissions': result.data }
def enter(self): login = self.request.params.get('login', '') password = self.request.params.get('password', '') remember = self.request.params.get('remember') result = ApiClient(ConfigurationWrapper.get_auth( 'map')).auth_client.authenticate_by_pass(login, password, self.request.client_addr) if not result.is_success: return {'result': result.data} max_age = 30 * 24 * 60 * 60 if remember else None return self.redirect(lambda r: r.set_cookie( 'auth.sid', result.data, httponly=True, max_age=max_age))
def __call__(self): client = ApiClient(ConfigurationWrapper.get_auth('admin')) skip = int(self.request.params.get('skip', 0)) take = int(self.request.params.get('take', 50000)) answer_result = client.form_client.get_answers( self.request.session.user_id, skip, take) if not answer_result.is_success: return {'user': self.user, 'error': answer_result.data} answer_result.data.items = list( map(lambda answer: self.add_form_info(client, answer), answer_result.data.items)) return {'user': self.user, 'answers': answer_result.data}
def __call__(self): client = ApiClient(ConfigurationWrapper.get_auth('admin')) skip = int(self.request.params.get('skip', 0)) take = int(self.request.params.get('take', 50000)) forms_result = client.form_client.get_forms( self.request.session.user_id, skip, take) if not forms_result.is_success: return {'user': self.user, 'error': forms_result.data} return { 'user': self.user, 'forms': forms_result.data, 'random_uuid': str(uuid.uuid4()) }
def test_valid_credentials(self, username, email, password, api_client: ApiClient): """Test add_user API function with valid credentials Steps: - Make request to application with path /api/add_user. JSON in valid format like {"username": "******", "email": "*****@*****.**", "password": "******"} Expected results: Response status code is 201 """ response = api_client.add_user(username=username, email=email, password=password) assert response.status_code == 201
def edit(self): form_id = self.request.matchdict.get('form_id') answer = dict() for id in self.request.params: answer[id] = self.request.params[id] title = answer.pop('title') description = answer.pop('description') content = json.dumps(answer) result = ApiClient( ConfigurationWrapper.get_auth('admin')).form_client.set_form( form_id, title, description, content) if not result.is_success: return {'user': self.user, 'error': result.data} return self.get('Формы поправлена')
def get(self, success=None): form_id = self.request.matchdict.get('form_id') form_result = ApiClient(ConfigurationWrapper.get_auth( 'admin')).form_client.get_form(form_id) if not form_result.is_success: return {'user': self.user, 'error': form_result.data} inputs = json.loads(form_result.data.content) return { 'success': success, 'user': self.user, 'form': form_result.data, 'inputs': inputs }
def index_228(req: Request): client = ApiClient(ConfigurationWrapper.get_auth("map")) user = load_user(req) ids = user.id if user else \ "00000000-0000-0000-0000--000000000000" answer = dict() for id in req.params: answer[id] = req.params[id] form_id = answer.pop("form_id") place_id = answer.pop("place_id") answer = json.dumps(answer) form = client.form_client.create_answer(ids, form_id, place_id, answer) return HTTPOkWithRedirect("/")
def test_status(api_client: ApiClient): """Test that get_status API function works well Steps: - Make request to application with path '/status' Expected results: Response status code is 200 Response header 'Content-Type' has value 'application/json' Response body is valid JSON that has field 'status' wit value 'ok' """ response = api_client.get_status() check.equal(response.status_code, status_codes.OK) check.equal(response.headers['Content-Type'], 'application/json') check.equal(response.json()['status'], 'ok')
def __call__(self): client = ApiClient(ConfigurationWrapper.get_auth('admin')) form_id = self.request.matchdict.get('form_id') skip = int(self.request.params.get('skip', 0)) take = int(self.request.params.get('take', 50000)) bindings_result = client.form_client.get_bindings(form_id, skip, take) if not bindings_result.is_success: return {'user': self.user, 'error': bindings_result.data} return { 'user': self.user, 'form_id': form_id, 'places': bindings_result.data, 'random_uuid': str(uuid.uuid4()) }
def test_add_user_negative(self, username, email, password, mysql_client: MysqlClient, api_client: ApiClient): """Test status code of API function 'add_user' Steps: Call 'add_user' with some credentials and check record with these credentials in the users' table Expected results: Status code is 400 and record with these credentials no exists in the users' table or another status code and the record exists """ response = api_client.add_user(username, email, password) record = mysql_client.get_record(username) assert response.status_code == 400 and record is None \ or record == Record(username, email, password, 1, 0, None)
def test_authorize_after_add(self, authorization_page: AuthorizationPage, api_client: ApiClient): """Test that user, created by API, can authorize properly Steps: - Make request to application with path /api/add_user and JSON in valid format - Try to authorize with the same credentials Expected results: Response status code is 200 for API request User succeed to authorize """ username, email, password = make.auth_data() response = api_client.add_user(username=username, email=email, password=password) assert response.status_code in range(200, 300) try: authorization_page.authorize(username=username, password=password) except WebDriverException as err: raise AssertionError from err
def test_integrity(self, username, email, password, authorization_page: AuthorizationPage, api_client: ApiClient): """Test integrity of add_user API function and authorization Steps: - Make request to application with path /api/add_user and JSON in valid format like {"username": "******", "email": "*****@*****.**", "password": "******"} - Try to authorize to the site with the same credentials Expected results: If request to /api/add_user has status code 400 or more, user mustn't be able to authorize to the site with these credentials In other cases user must be able to authorize to the site with these credentials """ response = api_client.add_user(username=username, email=email, password=password) if response.status_code >= 400: with allure.step( "'add_user' not succeed. Check that authorization will not succeed" ): with pytest.raises(AuthorizationError): authorization_page.authorize(username=username, password=password) else: with allure.step( "'add_user' succeed. Check that authorization will succeed" ): try: authorization_page.authorize(username=username, password=password) except AuthorizationError as err: allure.attach.file( authorization_page.make_screenshot( 'not_succeed_authorization'), attachment_type=allure.attachment_type.PNG, name='not_succeed_authorization.png') raise AssertionError from err # to mark test as failed, not broken
def get(self, success: str = None): client = ApiClient(ConfigurationWrapper.get_auth('admin')) answer_id = self.request.matchdict.get('answer_id') answer_result = client.form_client.get_answer(answer_id) if not answer_result.is_success: return {'user': self.user, 'error': answer_result.data} form_result = client.form_client.get_form(answer_result.data.form_id) if not form_result.is_success: return {'user': self.user, 'error': form_result.data} inputs = json.loads(form_result.data.content) answers = json.loads(answer_result.data.answer) for input_id in inputs: label = inputs[input_id] inputs[input_id] = { 'label': label, 'answer': answers.get(input_id, '') } return { 'success': success, 'user': self.user, 'answer_id': answer_id, 'form': form_result.data, 'inputs': inputs }
def index(req: Request): client = ApiClient(ConfigurationWrapper.get_auth("map")) #print(req.params.get("place_id")) forms = client.form_client.get_forms_place_id(req.params.get("place_id")) return {'forms': forms.data.items, 'place_id': req.params.get("place_id")}
def __init__(self, auth: IAuthProvider): self.client = ApiClient(auth)
def test_scenario2(api_client: ApiClient): """Test scenario with several requests Steps: 0 Generate credentials 1 Delete user via del_user API function (user not exists) 2 Block user via block_user API function (user not exists) 3 Accept user via accept_user API function (user not exists) 4 Add user via add_user API function with credentials 5 Accept user via accept_user API function 6 Block user via block_user API function 7 Block user via block_user API function 8 Accept user via accept_user API function 9 Accept user via accept_user API function 0 Delete user via del_user API function 1 Add user via add_user API function with the same credentials 2 Add user via add_user API function 3 Add user via add_user API function with different email 4 Add user via add_user API function with different username Expected results: Steps 1-3 fail, status code 404 Step 4 succeed, status code 201 Step 5 status code 304 Step 6 status code 200 Step 7 status code 304 Step 8 status code 200 Step 9 status code 304 Step 10 status code 204 Step 11 status code 201 Step 12 status code 304 Step 13 status code 304 Step 14 status code 304 """ username = '******' email = '*****@*****.**' password = '******' with allure.step(f"Del user {username} who doesn't exist"): response = api_client.del_user(username) attach_http(response) assert response.status_code == status_codes.NOT_EXIST with allure.step(f"Block user {username} who doesn't exist"): response = api_client.block_user(username) attach_http(response) assert response.status_code == status_codes.NOT_EXIST with allure.step(f"Accept user {username} who doesn't exist"): response = api_client.accept_user(username) attach_http(response) assert response.status_code == status_codes.NOT_EXIST with allure.step( f'Add user with credentials ({username}, {email}, {password})'): response = api_client.add_user(username=username, email=email, password=password) attach_http(response) assert response.status_code == status_codes.CREATED with allure.step(f"Accept user {username}"): response = api_client.accept_user(username) attach_http(response) assert response.status_code == status_codes.NOT_CHANGED with allure.step(f"Block user {username}"): response = api_client.block_user(username) attach_http(response) assert response.status_code == status_codes.OK with allure.step(f"Block user {username} again"): response = api_client.block_user(username) attach_http(response) assert response.status_code == status_codes.NOT_CHANGED with allure.step(f"Accept user {username}"): response = api_client.accept_user(username) attach_http(response) assert response.status_code == status_codes.OK with allure.step(f"Accept user {username}"): response = api_client.accept_user(username) attach_http(response) assert response.status_code == status_codes.NOT_CHANGED with allure.step(f"Del user {username}"): response = api_client.del_user(username) attach_http(response) assert response.status_code == status_codes.DELETED with allure.step( f'Add user with credentials ({username}, {email}, {password})'): response = api_client.add_user(username=username, email=email, password=password) attach_http(response) assert response.status_code == status_codes.CREATED with allure.step( f'Try to add user with credentials ({username}, {email}, {password})' ): response = api_client.add_user(username=username, email=email, password=password) attach_http(response) assert response.status_code == status_codes.NOT_CHANGED with allure.step( f'Try to add user with credentials ({username}, {email}, {password})' ): response = api_client.add_user(username=username, email='a' + email, password=password) attach_http(response) assert response.status_code == status_codes.NOT_CHANGED with allure.step( f'Try to add user with credentials ({username}, {email}, {password})' ): response = api_client.add_user(username='******' + username, email=email, password=password) attach_http(response) assert response.status_code == status_codes.NOT_CHANGED
def test_scenario_single_user_2(self, api_client: ApiClient, mysql_client: MysqlClient, registration_page: RegistrationPage): """Test scenario for API Steps: 0 Generate credentials 1 Pass registration with these credentials 2 Block user via API 3 Refresh page 4 Try to authorize to the site 5 Accept user via API 6 Try to authorize user Expected results: Step 1: database table has record with these credentials and values `access` = 1, `active` = 1, `start_active_time` ~ time.time() Step 2: `access` = 0, no other changes Step 3: user is redirected to authorization page, `access` = 0, `active` = 0 Step 4: user doesn't succeed to authorize, Step 6: `access` = 1, no other changes Step 7: User succeeds to authorize, `active` changed to 1, start_active_time changed and almost equal time.time(), no other changes Step 8: `active` = 0, no other changes Step 9: `access` = 0, no other changes Step 10: User doesn't succeed to authorize, the record doesn't changed """ username, email, password = make.auth_data() with allure.step('Register user'): main_page = registration_page.pass_registration( username, email, password) start_time = time.time() record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 1, 1, start_time) # access = 1, active = 1 with allure.step('Block user'): api_client.block_user(username=username) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 0, 0, start_time) # access = 0, active = 0 with allure.step('Refresh page'): main_page.refresh() assert not MainPage.is_opened(main_page.driver) assert AuthorizationPage.is_opened(main_page.driver) # logout record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 0, 0, start_time) # no change authorization_page = AuthorizationPage(main_page.driver, main_page.settings) with allure.step('Authorize user (who is blocked)'): with pytest.raises(AuthorizationError): authorization_page.authorize(username, password) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 0, 0, start_time) # no change with allure.step('Accept user'): api_client.block_user(username=username) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 1, 0, start_time) # access = 1 with allure.step('Authorize user (who was accepted)'): authorization_page.authorize(username, password) record = mysql_client.get_record(username) start_time = time.time() assert record is not None assert record == Record(username, email, password, 1, 1, start_time) # active = 1
def test_scenario1(registration_page: RegistrationPage, api_client: ApiClient): """Test how API functions influence user Steps: 1 Pass registration with generated credentials 2 Block user via block_user API function 3 Refresh page 4 Open registration page and try to register with the same credentials again 5 Open authorization page and try to authorize to the site with the same credentials 6 Accept user via accept_user API function 7 Refresh page 8 Delete user via del_user API function 9 Refresh page 0 Open authorization page and try to authorize to the site with the same credentials 1 Open registration page and register with same credentials again Expected results: Steps 1-2 succeed Step 3 redirect to authrization page Steps 4-5 fail, pytest.raises catch Exception Step 6 succeed Step 7 redirect to main page Step 8 succeed Step 9 redirect to authorization page Step 10 fail, pytest.raises catch Exception Step 11 succeed """ username, email, password = make.auth_data() with allure.step("Pass registration"): main_page = registration_page.pass_registration(username=username, password=password, email=email) assert 'welcome' in urlparse(main_page.current_url).path with allure.step(f"Block user {username}"): response = api_client.block_user(username) attach_http(response) with allure.step("Refresh page"): main_page.refresh() assert 'welcome' not in urlparse(main_page.current_url).path with allure.step( "Open registration page and try to register with same credentials again" ): registration_page.make_request() with pytest.raises(RegistrationError): registration_page.pass_registration(username=username, email=email, password=password) with allure.step("Try to authorize"): authorization_page = registration_page.go_to_authorization_page() with pytest.raises(AuthorizationError): authorization_page.authorize(username=username, password=password) with allure.step("Accept user"): response = api_client.accept_user(username) attach_http(response) with allure.step('User was redirected to main page after refresh'): authorization_page.refresh() assert 'welcome' in urlparse(authorization_page.current_url).path with allure.step("Delete user"): api_client.del_user(username) attach_http(response) with allure.step("User was redirected from main page after refresh"): main_page.refresh() assert 'welcome' not in urlparse(authorization_page.current_url).path with allure.step("Try to authorize"): authorization_page.make_request() with pytest.raises(AuthorizationError): authorization_page.authorize(username=username, password=password) with allure.step("Pass registration"): registration_page.make_request() registration_page.pass_registration(username=username, email=email, password=password)
def test_scenario_single_user(self, api_client: ApiClient, mysql_client: MysqlClient, authorization_page: AuthorizationPage): """Test scenario for API Steps: 0 Generate credentials 1 Add user via API 2 Delete user via API 3 Add user via API 4 Accept user via API 5 Block user via API 6 Accept user via API 7 Authorize user via API 8 Logout 9 Block user via API 0 Try to authorize user Expected results: Step 1: database table has record with these credentials and values `access` = 1, `active` = 0, `start_active_time` = None Step 2: record does not exist for this username Steps 3-4: database table has record with these credentials and values `access` = 1, `active` = 0, `start_active_time` = None Step 5: `access` = 0, no other changes Step 6: `access` = 1, no other changes Step 7: User succeeds to authorize, `active` changed to 1, start_active_time changed and almost equal time.time(), no other changes Step 8: `active` = 0, no other changes Step 9: `access` = 0, no other changes Step 10: User doesn't succeed to authorize, the record doesn't changed """ username, email, password = make.auth_data() with allure.step('Add user'): api_client.add_user(username=username, email=email, password=password) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 1, 0, None) with allure.step('Del user'): api_client.del_user(username=username) assert mysql_client.get_record( username) is None # record not exists with allure.step('Add user'): api_client.add_user(username=username, email=email, password=password) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 1, 0, None) with allure.step('Accept user'): api_client.accept_user(username=username) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 1, 0, None) # no changes with allure.step('Block user'): api_client.block_user(username=username) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 0, 0, None) # access = 0 with allure.step('Accept user'): api_client.accept_user(username=username) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 1, 0, None) with allure.step('Authorize user'): main_page = authorization_page.authorize(username, password) record = mysql_client.get_record(username) start_time = time.time() assert record is not None assert record == Record(username, email, password, 1, 1, start_time) # active = 1 with allure.step('Logout'): main_page.logout() assert record is not None assert record == Record(username, email, password, 1, 0, start_time) # active = 0 with allure.step('Block user'): api_client.block_user(username=username) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 0, 0, start_time) # access = 0 with allure.step('Authorize user (who is blocked)'): with pytest.raises(AuthorizationError): authorization_page.authorize(username, password) record = mysql_client.get_record(username) assert record is not None assert record == Record(username, email, password, 0, 0, start_time) # no changes