def test_user_is_present_by_phone(self, db): """ This test try to test the simple operation to create a new operator Test flow: - Make the JSON object with the correct data - user the UserService to share the request - clean DB """ json = { "firstname": "Vincenzo", "lastname": "Palazzo", "password": "******", "phone": "345432234", "dateofbirth": "1996-12-12", "email": "*****@*****.**", } user = UserService.create_user(db, json, 2) assert user is not None assert user.role_id is not 3 assert user.role_id is 2 user = UserService.user_is_present(db, phone=json["phone"]) assert user is not None Utils.del_user_on_db_with_id(db, user.id)
def test_unmark_user_as_covid_positive(self, db): """ This function test try to discover fault inside the mark postivive function inside the USerServices Flow tests is: - Create a new User - Mark this user as positive - check if the user if positive on the table - clean db (remove the user and the positive) """ json = Utils.get_json_about_new_user() user = UserService.create_user(db, json) assert user is not None assert user.role_id is 3 success_mark = UserService.mark_user_as_positive( db, json["email"], json["phone"]) assert success_mark is True success_unmark = UserService.unmark_user_as_not_positive(db, user.id) assert success_unmark is True Utils.del_user_on_db_with_id(db, user.id) user = Utils.del_user_on_db_with_id(db, user.id) assert user is None
def post(self): user_schema_register = UserRegistrationSchema() user_json = request.get_json() try: user = user_schema_register.load(user_json) except ValidationError as e: return e.messages if UserService.get_by_username(user["username"]): return {"message": USER_ALREADY_EXISTS}, 400 if UserService.get_by_email(user["email"]): return {"message": EMAIL_ALREADY_EXISTS}, 400 try: user = UserService.create( user["username"], user["email"], user["password"], user["first_name"], user["last_name"], ) user_schema = UserSchema() return user_schema.dump(user), 201 except: # failed to save user to db traceback.print_exc() if user: user.delete() return {"message": FAILED_TO_CREATE}, 500
def get(self, nickname): service = UserService() self.set_header("Content-type", "application/json") result, status = service.get_user(nickname) self.set_status(int(status)) self.write(result)
def post(self, nickname): service = UserService() self.set_header("Content-type", "application/json") result, status = service.update_user( nickname, tornado.escape.json_decode(self.request.body)) self.set_status(int(status)) self.write(result)
def attemptlogin(request): uid = extractkeyfromrequest(request, 'u') emailid = request.get('e') studentid = request.get('s') if emailid and studentid: userservice = UserService() uid = userservice.registersession(emailid, studentid) insession = isinsession(uid) return (uid, insession)
def register(): data = request.get_json() user_service = UserService(data) user_service.register_user() return (jsonify({ "Token": base64.b64encode( ("%s:%s" % (data["email"], data["password"])).encode()).decode("utf-8") }), 201)
def get(self, id=None): try: if id is None: (status, data) = UserService().read_all() return {'status': status, 'data': data} else: (status, data) = UserService().read(id) return {'status': status, 'data': data.to_json() if callable(getattr(data, "to_json", None)) else str(data)} except Exception as x: return {'status': False, 'message': str(x)}
def create_game(message): sid = request.sid game = GameService.create(message['game_name']) task = TaskService.create( message['task_name'], game['id'], ) UserService.create(sid, message['user_name']) UserTaskService.create_or_update(task['id'], sid, 0) emit('send:game_data', {'game': game['uuid'], 'task': task['id']})
def add_user(): pb_user = PBUser() pb_user.basic_info.uname = 'kk' pb_user.basic_info.nick = 'kk' print pb_user user = User() basic_info = UserBasic() basic_info.uname = pb_user.basic_info.uname basic_info.nick = pb_user.basic_info.nick user.basic_info = basic_info userService = UserService() userService.save(user)
async def register(request): data = await request.json() username, password = data['username'], data['password'] if UserService.get_user(username=username): return utils.json_response({ "errors": [ {"username": "******"} ] }) user = UserService.add_user(username, password) return web.Response(text=utils.create_jwt_token(user.id))
def get(self): uid, insession = attemptlogin(self.request) coursesservice = CoursesService() userservice = UserService() emailid = userservice.getemailidforsession(uid) usercourses = coursesservice.listusercourses(emailid) template_values = {} header_template_values = buildheadertemplatevalues(insession, uid) template_values.update(header_template_values) course_template_values = buildmycoursestemplatevalues( insession, uid, usercourses) template_values.update(course_template_values) template = JINJA_ENVIRONMENT.get_template('mycourses.html?s=' + str(sessionid)) self.response.write(template.render(template_values))
def test_get_user_by_email(self, db): """ This function contains the code to test the user service tha allows to retetrive the user having the email :param db: database session """ json = Utils.get_json_about_new_user() user = UserService.create_user(db, json) assert user is not None assert user.role_id is 3 assert UserService.get_user_by_email(db, user.email).id == user.id is_delete = UserService.delete_user(db, user.id) assert is_delete is True
def delete(self, id=None, visit_id=None): try: if id is None: return { 'status': False, 'message': 'User Id is required.' } if visit_id is None: return { 'status': False, 'message': 'Visit Id is required.' } (status, user) = UserService().read(id) if status is False: return { 'status': False, 'message': 'User Id {} is not valid.'.format(id) } (status, visits) = VisitService().read(visit_id) if status is True and len(visits) > 0: visit = visits[0] if visit.get('user_id') == id: (status, visit) = VisitService().delete(visit_id) return { 'status': status, 'message': 'Visit has been deleted.' if status else 'An error exists', 'data': visit.to_json() } else: return { 'status': False, 'message': 'Visit Id {} does not correspond with User Id {}'.format(visit_id, id) } except Exception as x: return {'status': False, 'error': str(x)}
def test_user_delete_ok(self, db): """ This function contains the code to test the User services about the login, and I will aspect a good result. :param db: database session """ json = Utils.get_json_about_new_user() user = UserService.create_user(db, json) assert user is not None assert user.role_id is 3 user = UserService.user_login(db, user.email, json["password"]) is_delete = UserService.delete_user(db, user.id) assert is_delete is True user = Utils.get_user_on_db_with_email(db, user.email) assert user is None
def prepare(self): self.channel_string = '' self.server_string = [] ip = self.get_ip() if ip!='192.168.2.70': print(ip) user_id = self.current_user self.start_now = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00') if not user_id: self.redirect('/login/') self.url = (self.request.uri.split('?')[0]) self.urls = (caching.get(str(user_id))) self.privilege = True if self.urls is not None: if self.admin_flag is False: if self.url not in (list(self.urls.values()) if self.urls else []): self.privilege = False if self.admin_flag is False: user_secontrol_data = yield UserService.GetByUser(int(user_id)) secontrol = json.loads(user_secontrol_data.get('secontrol','{}')) for k,v in secontrol.items(): if self.channel_string: self.channel_string+=',' + k else: self.channel_string = k self.server_string+=v self.server_string = ','.join(self.server_string)
def test_login_user_ok(self, client, db): """ This function test the perform the request to login the user :param client: flask test client :param db: database session """ json_create = { "firstname": "Vincenzo", "lastname": "Palazzo", "password": "******", "phone": "100023", "dateofbirth": "1996-12-12", "email": "*****@*****.**", } user = UserService.create_user(db, json_create) assert user is not None json_login = { "email": json_create["email"], "password": json_create["password"], } response = Utils.login_user(client, json_login) user = Utils.get_user_on_db_with_email(db, json_create["email"]) assert response.status_code == 200 assert user.email in response.data.decode("utf-8") Utils.del_user_on_db_with_id(db, user.id) user = Utils.get_user_on_db_with_email(db, json_create["email"]) assert user is None
def test_modify_user_ok(self, client, db): """ This test method perform the request to modify the user :param client: flask test client :param db: database session """ json = { "firstname": "Bart", "lastname": "Simpson", "password": "******", "phone": "100023", "dateofbirth": "1996-12-12", "email": "*****@*****.**", } user = UserService.create_user(db, json) assert user is not None json["firstname"] = "Homer" json["role"] = user.role_id json["id"] = user.id response = Utils.modify_user(client, json) logging.debug(response.data) user = Utils.get_user_on_db_with_email(db, json["email"]) assert response.status_code == 200 assert "Homer" in response.data.decode("utf-8") assert "Bart" not in response.data.decode("utf-8") Utils.del_user_on_db_with_id(db, user.id) user = Utils.get_user_on_db_with_email(db, json["email"]) assert user is None
def test_delete_user_ok(self, client, db): """ This test method perform the request to modify the user :param client: flask test client :param db: database session """ json = { "firstname": "Bart", "lastname": "Simpson", "password": "******", "phone": "100023", "dateofbirth": "1996-12-12", "email": "*****@*****.**", } user = UserService.create_user(db, json) assert user is not None json_login = { "email": json["email"], "password": json["password"], } response = Utils.login_user(client, json_login) response = Utils.delete_user(client, user.id) assert response.status_code == 200 assert "OK" in response.data.decode("utf-8") user = Utils.get_user_on_db_with_email(db, json["email"]) assert user is None
def add_user(): uid = request.args.get('uid') uname = request.args.get('uname') nick = request.args.get('nick') user = User() basic_info = UserBasic() basic_info.uid = uid basic_info.uname = uname basic_info.nick = nick user.basic_info = basic_info userService = UserService() userService.save(user) return ''
def post(self, id=None): try: state = request.form.get('state') city = request.form.get('city') if id is None or state is None or city is None: return { 'status': False, 'message': 'User id, State and City are required.' } if id is not None: (status, user) = UserService().read(id) if status is False or user is None: return { 'status': False, 'message': 'User id [{}] is not valid'.format(id) } if state is not None: (status, state) = StateService().read(None, state) if status is False or state is None: return { 'status': False, 'message': 'State provided [{}] is not valid'.format(state) } if city is not None: (status, city) = CityService().read(None, city) if status is False or city is None: return { 'status': False, 'message': 'City provided [{}] is not valid'.format(city) } (status, visit) = VisitService().create(user.id, state.id, city.id) return { 'status': status, 'message': 'Visit has been added.' if status else 'An error exists', 'data': visit.to_json()} except Exception as x: return {'status': False, 'message': str(x)}
async def __run_gain(self): if len(self.args) not in [2]: await self.reply([ "Incorrect number of arguments!!!", self.__class__.gain_help() ]) return if not represents_int(self.args[1]) or int(self.args[1]) > 50 or int( self.args[1]) <= 0: await self.reply([ f"**{self.args[1]}** must be whole positive number and be less or equal 50!" ]) return sorted_users = UserService.order_by_current_gain(int(self.args[1])) msg = ["```asciidoc"] msg.append(" = Place = | = Gain = | = Investor =") for i, (position, value, user) in enumerate(sorted_users): msg.append("{:3d}. |{:9.2f} | {:s}".format( position, value, user.short_name())) msg.append("```") await self.reply(msg) return
def test_get_user_by_id(self, client, db): """ Test flow: - Create User - Get user by id - check user - clean db :param client: flask test client :param db: db session """ json_create = { "firstname": "Vincenzo", "lastname": "Palazzo", "password": "******", "phone": "100023", "dateofbirth": "1996-12-12", "email": "*****@*****.**", } user = UserService.create_user(db, json_create) assert user is not None response = Utils.get_user_by_id(client, user.id) assert response.status_code == 200 json = response.data.decode("utf-8") assert user.firstname in json assert user.phone in json assert user.email in json assert str(user.role_id) in json Utils.del_user_on_db_with_id(db, user.id) user = Utils.get_user_on_db_with_email(db, json_create["email"]) assert user is None
def on_join_jap(self, data: dict): """Call on message JOIN_JAP. Emit USER_JOINED_JAP in the room 'jap_event/jap_id'. and USER_JOINED_TABLE if the user has one Args : data = {user_id, jap_event_id, ?table_id} Emit : USER_JOINED_JAP = { "jap_event_id": int, "new_member": asdict(new_member), "members": list(User) } """ app.logger.info("JOIN_JAP") app.logger.info(request.sid) session_id = request.sid user_id = data["user_id"] jap_event_id = data["jap_event_id"] self.session_id_user_id[session_id] = { "user_id": user_id, "jap_event_id": jap_event_id, } jap_event = JapEventService.get_jap_event(jap_event_id) table = TableService.get_user_table(user_id, jap_event_id) new_member = UserService.get_user(user_id) new_member_dict = asdict(new_member) room = self.__get_jap_event_room(data["jap_event_id"]) if (room not in self.connected_by_jap_event or new_member_dict not in self.connected_by_jap_event[room]): join_room(room) self.__add_to_event(new_member, room) emit( socket_messages["USER_JOINED_JAP"], { "jap_event_id": data["jap_event_id"], "new_member": new_member_dict, "members": self.connected_by_jap_event[room], }, room=room, ) if table: self.on_join_table({ "user_id": user_id, "jap_event_id": jap_event_id, "table_id": table.id, }) else: # checkt that the user is not a jap creator, otherwise it must have a table. if jap_event.creator_id == user_id: raise (Exception( "Error at jap creation for jap creator, not added to a table" ))
def register(username): """Register a new user, with his username. Args : username: string """ user = UserService.create_user(username, username, username, None) return user
def test_report_positive_after_one(self, db): json = Utils.get_json_about_new_user() user = UserService.create_user(db, json) assert user is not None assert user.role_id is 3 success_mark = UserService.mark_user_as_positive( db, json["email"], json["phone"]) assert success_mark is True users = UserService.report_positive(db) assert len(users) == 1 success_unmark = UserService.unmark_user_as_not_positive(db, user.id) assert success_unmark is True Utils.del_user_on_db_with_id(db, user.id) user = Utils.del_user_on_db_with_id(db, user.id) assert user is None
def sendSignUpInfo(packet): minersInfo = usr.checkOnlineMiners() skt = socket.socket() for i in minersInfo: host = i[1] port = i[2] skt.connect((host, port)) skt.send(packet) skt.close()
def create_user_on_db(db_session, ran: int = randrange(100000)): json = { "firstname": "User_{}".format(ran), "lastname": "user_{}".format(ran), "password": "******".format(ran), "phone": "1234562344{}".format(ran), "dateofbirth": "12/12/2000", "email": "alibaba{}@alibaba.com".format(str(ran)), } return UserService.create_user(db_session, json)
def startClient(packet): freeMiners = usr.checkOnlineMiners() miners = [] for i in freeMiners: miners.append([i[1],i[2]]) skt = socket.socket() for j in miners: skt.connect((j[0],j[1])) skt.send(packet) skt.close()
def login(username): """Log a user in, using his username. Args : username: string """ user = UserService.get_user_by_name(username) if not user: return AuthService.register(username) return user
def test_user_login_ko(self, db): """ This function contains the code to test the User services about the login, and I will aspect a good result. :param db: database session """ json = Utils.get_json_about_new_user() user = UserService.user_login(db, json["email"], json["password"]) assert user is None
def getServices(body, userId): userService = UserService(userServiceApi+"?format=json&agencyId="+agencyId+"&userId="+str(userId)) print(" [x] Loading user service "+userServiceApi+"?format=json&agencyId="+agencyId+"&userId="+str(userId)) box = BlackBox(serviceApi, userService) services = box.getWidgets(body) for service in services: service["AgencyID"] = agencyId result = json.dumps(services) return result
def count_user(): userService = UserService() users = userService.find() count = users.count() return str(count)
def list_user(): userService = UserService() users = userService.find() return ""
def count_user(): userService = UserService() count = userService.count() resp = Response(str(count), status=200, mimetype='application/json') return resp
def list_user(): userService = UserService() users = userService.find() resp = Response(users, status=200, mimetype='application/json') return resp
def setUp(self): self.db = connect_db(':memory:') init_db(self.db) self.s = UserService(self.db, SecureHashService('salt', 'sha256'))
class UserServiceTests(unittest.TestCase): def setUp(self): self.db = connect_db(':memory:') init_db(self.db) self.s = UserService(self.db, SecureHashService('salt', 'sha256')) def tearDown(self): self.db.close() def test_signup_success(self): #given user = '******' self.assertEqual(self.s.user_exists(user), False) #when self.s.signup(user, 'any') #then self.assertEqual(self.s.user_exists(user), True) def test_signup_failed(self): #given user = '******' self.s.signup(user, 'any') #expect with self.assertRaises(Exception): self.s.signup(user, 'any') def test_check_credential_matched(self): #given user, password = ('teohm', 'password') self.s.signup(user, password) #expect self.assertEqual(self.s.check_credential(user, password), True) def test_check_credential_not_matched(self): #given user, password = ('teohm', 'password') wrong_password = '******' self.s.signup(user, password) #expect self.assertEqual(self.s.check_credential(user, wrong_password), False)