def test_create_user_fail_none_entity_provided(app): with app.app_context(): user_service = UserService(app) with pytest.raises( ValueError, match=r"None object was provided to create new entity.*"): user = user_service.create(None)
def setUp(self): # Initializing Service and invoking register(...) user_service = UserService("test") user = user_service.register({ "email": "*****@*****.**", "name": "John", "password": "******", "confirmPassword": "******", "phone": "+11231231231" }) self.user_id = user.user_id self.headers['Authorization'] = self.__get_jwt_token(user.user_id) self.board = {'name': 'board1', "color": "#fefefe"} # Initializing BoardService and creating board board_service = BoardService("test") response = board_service.create_board(self.board, self.headers) self.board_id = response.board_id # Initializing SwimLaneService and creating a swim lane swim_lane_service = SwimLaneService("test") self.swim_lane = { "title": "todo", "boardId": self.board_id, "position": "0" } response = swim_lane_service.create_swim_lane(self.swim_lane, self.headers)
def login(): if request.method == 'GET': return render_template("login.html") req = request.form username = req.get("uname") password = req.get("psw") user_svc = UserService() try: login_info = user_svc.login(username, password) id_token = login_info.get("IdToken") lex_token = id_token[:80] # Creating Lex user session to talk to bot using the same ID token of Cognito payload = {"user_id": lex_token} payload_json = json.dumps(payload) headers = {'Content-Type': 'application/json'} response = requests.request("POST", f"{LEX_PROXY_URL}/create_session", headers=headers, data=payload_json) response_json = response.json() print(f"INFO {response_json}") session["session_token"] = id_token session["lex_token"] = lex_token return redirect(url_for('home')) except Exception as e: logging.warning(e) return redirect(url_for('login'))
def test_update_user_cannot_change_login(app): with app.app_context(): user_service = UserService(app) with pytest.raises(ValueError, match=r"Login cannot be presented to update user*"): updated_user = user_service.update( id_entity=1, fields_to_update={'login': '******'})
def setUp(self): self.user_repository = UserRepository(test_database_connection()) self.user_service = UserService(self.user_repository) self.user_repository.delete_all() self.test_user_one = User('testuser', 'testuser1', 1) self.test_user_two = User('secondo', 'testuser2', 2)
class AppLibrary: def __init__(self): self._io = StubIO() self._user_repository = UserRepository() self._user_service = UserService(self._user_repository) self._app = App(self._user_service, self._io) def input(self, value): self._io.add_input(value) def output_should_contain(self, value): outputs = self._io.outputs if not value in outputs: raise AssertionError( f"Output \"{value}\" is not in {str(outputs)}") def run_application(self): self._app.run() def create_user(self, username, password): try: self._user_service.create_user(username, password) self._io.write("New user registered") except Exception as e: self._io.write(str(e))
def create_user(): """ This flask method give the possibility to create a new customer with a json request :return: the correct response that looks like {"result": "OK"}, 200 :return: """ if request.method == "POST": json = request.get_json() email = json["email"] phone = json["phone"] user = UserService.user_is_present(db_session, email, phone) if user is not None: return _get_response( "User with email {} and/or phone already exist".format(email, phone), 500, ) user = UserService.create_user(db_session, json) if user is not None: return _get_response("OK", 200) else: return _get_response( "User not created because we have an error on server", 500 ) return _get_response("Resource not found", 404)
def transfer(): user_id = get_jwt_identity() user = UserService().get_user_by_id(user_id) data = { 'amount': request.json.get('amount', None), 'code': request.json.get('code', None), 'user_agent': request.headers.get('User-Agent'), 'ip': request.headers.get('ip-address'), 'location': request.headers.get('location'), 'author': user.get('username'), 'user_id': user_id } v = Validator(bank_transfer_validation_schema) if v.validate(data): wallet_service = WalletService(data) if wallet_service.check_balance(): wallet_service.transfer() return {"msg": "transaction success."}, 200 else: return { "msg": "user balance is not sufficient, transaction failed." }, 400 return { "msg": "validation error, transaction failed.", "errors": v.errors }, 400
class AppLibrary: def __init__(self): self._io = StubIO() self._user_repository = UserRepository() self._user_service = UserService(self._user_repository) self._app = App(self._user_service, self._io) def input(self, value): self._io.add_input(value) def output_should_contain(self, value): outputs = self._io.outputs if value not in outputs: raise AssertionError(f'Output "{value}" is not in {str(outputs)}') def run_application(self): self._app.run() def create_user(self, username, password): try: self._user_service.create_user(username, password) except Exception as err: self._io.outputs.append(str(err)) def user_should_exist(self, username): if not self._user_repository.find_by_username(username): raise AssertionError(f"User {username} does not exist")
def del_user(user_id): try: UserService.delete_user(int(user_id)) return '', 204 except ValueError as e: return "Not a valid ID or No such user exist with this ID", 400 # Bad Request except ResourceNotFound as r: return r.message, 404
def test_create_user(app): with app.app_context(): user_service = UserService(app) user = User() user.login = '******' user.password = '******' user = user_service.create(user) assert user.id is not None
def put_user(user_id): try: user = User.json_parse(request.json) user.user_id = int(user_id) UserService.update_user(user) return jsonify(user.json()), except ValueError as e: return "Not a valid ID or No such user exist with this ID", 400 # Bad Request except ResourceNotFound as r: return r.message, 404
def test_get_by_id(app): with app.app_context(): user_service = UserService(app) user = User() user.login = '******' user.password = '******' user = user_service.create(user) assert user_service.get_by_id( user.id).id == user.id and user_service.get_by_id( user.id).login == user.login
def test_update_user_cannot_assign_bad_column(app): with app.app_context(): user_service = UserService(app) user = User() user.login = '******' user.password = '******' user = user_service.create(user) with pytest.raises(ValueError, match=r"Model definition does not have such key*"): updated_user = user_service.update(user.id, {'metadata': 'test'})
def test_login_invalid_email(self): # Initializing Service and invoking login(...) user_service = UserService("test") # Trying to login with invalid user email response = user_service.login({ "email": "*****@*****.**", "password": "******" }) # Validating the response self.assertEqual(response, "User not available")
def __init__(self): self.user_service = UserService() self.parser = reqparse.RequestParser() self.parser.add_argument('login', type=str, required=True, help='Login cannot be en empty string.') self.parser.add_argument('password', type=str, required=True, help='Password cannot be en empty string.')
def get_user_by_id(id): user = UserService.get_user_by_id(db_session, id) if user is None: if user is None: return _get_response("User not found", 404) is_positive = UserService.user_is_positive(db_session, user.id) json_user = user.serialize() if is_positive is None: json_user["is_positive"] = False else: json_user["is_positive"] = True return _get_response(json_user, 200, True)
def setUp(self): self.password_repository = PasswordRepository(test_database_connection()) self.password_service = PasswordService(self.password_repository) self.password_repository.delete_all_passwords() self.user_repository = UserRepository(test_database_connection()) self.user_service = UserService(self.user_repository) self.test_user_one = User("test_user_one", "test_pw1") self.test_user_two = User("test_user_two", "test_pw2") self.user_service.create_user(self.test_user_one) self.user_service.create_user(self.test_user_two)
def get_user_session(code): config = ConfigReader().get_config() app_id = config.get("wechat", "app_id") secret = config.get("wechat", "secret") user_session_url = config.get("wechat", "user_session_url") url = user_session_url + app_id + '&secret=' + secret + '&grant_type=authorization_code&js_code=' + code user_session_from_wechat = requests.get(url) user_service = UserService() if user_session is not None: user_service.handle_user_session(json.loads(user_session_from_wechat.text).get('openid')) return Response(user_session_from_wechat.text) return Response('failed')
def __init__(self, root, handle_login_view): """Rekisteröitymisnäkymästä vastaava käyttöliittymäluokka Args: root: Juurielementti, joka hallitsee nykyistä näkymää handle_login_view: UI-luokan metodi, joka siirtää näkymän LoginViewiin """ self._root = root self._frame = None self._initialize() self._handle_login_view = handle_login_view self._user_service = UserService()
def test_register_invalid_email_id(self): # Initializing Service and invoking register(...) user_service = UserService("test") response = user_service.register({ "email": "doe@g", "name": "John", "password": "******", "confirmPassword": "******", "phone": "+11231231231" }) # Validating the response self.assertEqual(response, "Invalid email or password")
def init_login(): login_manager = LoginManager() login_manager.init_app(app) user_service = UserService(db) user_service.initialize_users() # Create user loader function @login_manager.user_loader def load_user(user_id): if (user_id): return User(user_id) else: return None
def setUp(self): # Initializing Service and invoking register(...) user_service = UserService("test") user = user_service.register({ "email": "*****@*****.**", "name": "John", "password": "******", "confirmPassword": "******", "phone": "+11231231231" }) self.user_id = user.user_id self.headers['Authorization'] = self.__get_jwt_token(user.user_id) self.board = {'name': 'board1', "color": "#fefefe"}
def delete_user(): username = request.form.get("username") print username user = UserService.get_user(username) print user if user is None or username not in UserService.users: print("User does not exist") abort(404) else: status = UserService.delete_user(username) if status: return render_template("userProfileDetails.html ", name=username) else: abort(404)
def authentication(): email = request.json.get('email', None) password = request.json.get('password', None) user = UserService().get_user_by_email(email) if user: check = check_password(user.get('password'), password) if check: access_token = create_access_token(identity=user.get('id')) refresh_token = create_refresh_token(identity=user.get('id')) resp = jsonify({'msg': 'login success.'}) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp, 200 return jsonify({'msg': 'login failed.'}), 401
def get_user_by_email(): """ thi method returns the user givene the email in the POST request """ json = request.get_json() user = UserService.get_user_by_email(db_session, json["email"]) if user is None: return _get_response("User not found", 404) is_positive = UserService.user_is_positive(db_session, user.id) json_user = user.serialize() if is_positive is None: json_user["is_positive"] = False else: json_user["is_positive"] = True return _get_response(json_user, 200, True)
def test_register(self): # Initializing Service and invoking register(...) user_service = UserService("test") response = user_service.register({ "email": "*****@*****.**", "name": "John", "password": "******", "confirmPassword": "******", "phone": "+11231231231" }) # Validating the response assert isinstance(response, User) assert response.user_id is not None user_service.delete_user(response.user_id)
def delete_user(id): """ This API method contains the logic to delete a user on database :return: the correct response that looks like {"result": "OK"}, 200 """ if request.method == "DELETE": user = UserService.user_is_present_with_id(db_session, id) if user is None: current_app.logger.warning( "The user with id {} doesn't exist, I can not delete it".format(id) ) return _get_response("User doesn't exist", 404) UserService.delete_user(db_session, id) return _get_response("OK", 200) return _get_response("Resource not found", 404)
class TestPasswordService(unittest.TestCase): def setUp(self): self.password_repository = PasswordRepository(test_database_connection()) self.password_service = PasswordService(self.password_repository) self.password_repository.delete_all_passwords() self.user_repository = UserRepository(test_database_connection()) self.user_service = UserService(self.user_repository) self.test_user_one = User("test_user_one", "test_pw1") self.test_user_two = User("test_user_two", "test_pw2") self.user_service.create_user(self.test_user_one) self.user_service.create_user(self.test_user_two) def test_num_of_users_correct(self): users = self.user_repository.get_all_users() self.assertEqual(len(users), 2) def test_add_new_password(self): user_for_password = self.user_repository.get_single_user(self.test_user_one) password_to_add = Password( "test_username", "test_pw", "test_site", user_for_password.user_id ) added_password = self.password_service.add_new_password(password_to_add) self.assertEqual(added_password.user_id, user_for_password.user_id) self.assertEqual(added_password, password_to_add) def test_get_passwords_by_user(self): user_for_password = self.user_repository.get_single_user(self.test_user_one) for i in range(5): password_to_add = Password( f"test_username{i}", f"test_pw{i}", f"test_site{i}", user_for_password.user_id ) self.password_service.add_new_password(password_to_add) passwords_by_user = self.password_service.get_passwords_by_user(user_for_password) self.assertEqual(len(passwords_by_user), 5) self.assertEqual(passwords_by_user[0].username, "test_username0")
def get_all_acct(userid): try: if UserService.get_user(userid): return jsonify(AccountService.all_account()), 200 except ResourceNotFound as r: r.message return "This client does not exist", 404
def create_user(): """ Params a username:password (required) and attempts to create a user. Username is a unique field. """ auth = request.authorization user_service = UserService() created_user = user_service.create(auth.username, auth.password) if created_user: user_presenter = UserPresenter() user_result = user_presenter.dump(created_user) return jsonify(user_result.data) return Response(response='400 Unable to create user. User already exists.', status=400, mimetype="application/json")
def init_dev_data(): """ Init dev data """ UserService.sync_users() FSWatcher()
def init_test_data(): """ Init test data """ UserService.sync_users()
def init_prod_data(): """ Init prod data """ UserService.sync_users() FSWatcher() #UserDataService.index_all_users()