def test_init_method(self): """ tests the __init__ method for instantiating new objects both new and from kwargs __init__ method calls on inherited BaseModel with super() """ # creates new instance of Profile new_obj1 = Profile() # tests that the new object is of type Profile self.assertIs(type(new_obj1), Profile) # adds all attributes for testing # (id should be set by primary key) # (created_at, updated_at should be set by datetime) new_obj1.name = "test_name" new_obj1.email = "*****@*****.**" new_obj1.password = "******" new_obj1.company_school_name = "123" new_obj1.about_me = "This is for testing purposes" new_obj1.linkedin = "https://www.linkedin.com/in/test" new_obj1.social_media = "Social media links would go here" # attributes_dict sets up dictionary of attribute names and types attributes_dict = { "id": str, "created_at": datetime, "updated_at": datetime, "name": str, "email": str, "password": str, "company_school_name": str, "about_me": str, "linkedin": str, "social_media": str } # loops through attributes_dict as subTests to check each attribute for attr, attr_type in attributes_dict.items(): with self.subTest(attr=attr, attr_type=attr_type): # tests the expected attribute is in the object's dict self.assertIn(attr, new_obj1.__dict__) # tests the attribute is the expected type self.assertIs(type(new_obj1.__dict__[attr]), attr_type) # sets kwargs using object's dict and uses to create new object kwargs = new_obj1.__dict__ new_obj2 = Profile(**kwargs) # tests that the new object is of type Profile self.assertIs(type(new_obj2), Profile) # loops through attributes_dict as subTests to check each attribute for attr, attr_type in attributes_dict.items(): with self.subTest(attr=attr, attr_type=attr_type): # tests the expected attribute is in the object's dict self.assertIn(attr, new_obj2.__dict__) # tests the attribute is the expected type self.assertIs(type(new_obj2.__dict__[attr]), attr_type) # tests the value of name attribute matches the original object self.assertEqual(new_obj1.__dict__[attr], new_obj2.__dict__[attr]) # tests that __class__ is not set in object 2 self.assertNotIn('__class__', new_obj2.__dict__)
def register(): logging.debug('add profile form : %s', str(request.form)) logging.info('receive socket from /register-data -> profile: %s', request.form['profile-name']) form = request.form if form['profile-password'] != form['profile-repassword']: return render_template('v3-login.html', error=_('Your confirmation password does not match the password you entered')) profile = Profile() profile.name = form['profile-name'] profile.firstname = form['profile-firstname'] profile.address = form['profile-address'] profile.comp_address = form['profile-comp_address'] profile.city = form['profile-city'] profile.zipcode = form['profile-zipcode'] profile.country = form['profile-country'] profile.phone = form['profile-phone'] profile.email = form['profile-email'] profile.siret = form['profile-siret'] profile.password = form['profile-password'] pdao = ProfileDAO() if pdao.insert(profile): logging.info('add profile %s OK', profile.name) session['logged_in'] = pdao.field(pdao.where('email', profile.email), 'id')[0][0] else: logging.info('add profile %s FAILED', profile.name) return render_template('v3-login.html', error=_('Impossible to create new user, please contact an admin !')) return redirect('/')
def register(): if request.method == 'GET': return redirect('/') logging.debug('add profile form : %s', str(request.form)) logging.info('receive socket from /register-data -> profile: %s', request.form['profile-name']) form = request.form profile = Profile() profile.name = form['profile-name'] profile.firstname = form['profile-firstname'] profile.address = form['profile-address'] profile.comp_address = form['profile-comp_address'] profile.city = form['profile-city'] profile.zipcode = form['profile-zipcode'] profile.country = form['profile-country'] profile.phone = form['profile-phone'] profile.email = form['profile-email'] profile.siret = form['profile-siret'] pdao = ProfileDAO() if pdao.insert(profile): logging.info('add profile %s OK', profile.name) session['logged_in'] = pdao.field(pdao.where('email', profile.email), 'id')[0][0] else: logging.info('add profile %s FAILED', profile.name) return redirect('/')
def make_conference(self, conf_name, email): p_key = ndb.Key(Profile, email) profile = Profile(mainEmail=email, key=p_key).put() conf_id = Conference(name=conf_name, organizerUserId=email, parent=p_key).put().urlsafe() return conf_id, profile
def post(self): photo = str(self.request("photo")) user_name = self.request("user_name") first_name = self.request("first_name") last_name = self.request("last_name") twitter = self.requst("twitter") user = App.session.get('profile') if user: invalidFieldFlag = False if len(user_name.strip()) == 0: ProfileHandler.invalidUser_Name = True invalidFieldFlag = True if len(first_name.strip()) == 0: ProfileHandler.invalidFirst_Name = True if len(last_name.strip()) == 0: ProfileHandler.invalidLast_Name = True if not invalidFieldFlag: ProfileHandler.invalidUser_Name = ProfileHandler.invalidFirst_Name = ProfileHandler.invalidLast_Name = False user_id = user['user_id'] new_profile = Profile(parent=App.DEFAULT_KEY) new_profile.user_name = user_name new_profile.first_name = first_name new_profile.last_name = last_name new_profile.photo = photo new_profile.photo_key = uuid.uuid4().hex new_profile.user_id = user_id new_profile.put() self.redirect("/#profiles") else: self.redirect("#login")
def create(self): form = ProfileForm(self.request.POST) if self.request.method == 'POST' and form.validate(): name = ' '.join([form.first_name.data, form.last_name.data]) # Create the webapp2_extras.auth user. model = self.auth.store.user_model ok, user = model.create_user(form.data['email'], password_raw=form.data['password']) if not ok: self.session.add_flash(messages.EDITOR_CREATE_ERROR, level='error') return self.redirect_to('editors.list') # Create the profile. profile = Profile(name=name, email=form.data['email'], is_editor=True, auth_user_id=user.key.id()) profile.put() # Force reload of profile object Profile.get(profile.key()) self.session.add_flash(messages.EDITOR_CREATE_SUCCESS) return self.redirect_to('editors.list') return self.render_to_response('editors/form.haml', {'form': form})
def get_profile_data(username: str) -> Profile: # search user name result = ie.user(username) parsed_data = json.dumps(result, indent=4, sort_keys=True) test = json.loads(parsed_data) # displaying the data user_data = test[0] # print(user_data) profile = Profile( id=user_data["id"], full_name=user_data["full_name"], username=user_data["username"], biography=user_data["biography"], profile_pic_url=user_data["profile_pic_url"], amount_posts=user_data["edge_owner_to_timeline_media"]["count"], amount_followers=user_data["edge_followed_by"]["count"], amount_following=user_data["edge_follow"]["count"], external_url=user_data["external_url"], connected_fb_page=user_data["connected_fb_page"], is_joined_recently=user_data["is_joined_recently"], is_private=user_data["is_private"], is_verified=user_data["is_verified"], is_business_account=user_data["is_business_account"], business_email=user_data["business_email"], business_category_name=user_data["business_category_name"], category_enum=user_data["category_enum"]) return profile
def test_updated_datetime_attributes(self): """ tests that the datetime attribute updated_at changes when the save() method is implemented """ first_time = datetime.now() new_obj = Profile() second_time = datetime.now() # tests if object's created_at time is between timestamps self.assertTrue(first_time <= new_obj.created_at <= second_time) # tests if object's updated_at is within the same timestamps self.assertTrue(first_time <= new_obj.updated_at <= second_time) # gets timestamps of current attributes and pauses a moment original_created_at = new_obj.created_at original_updated_at = new_obj.updated_at sleep(1) # adds required attributes so the object can be saved; saves object new_obj.name = "test_name" new_obj.email = "*****@*****.**" new_obj.save() # tests that the object's updated_at has changed and is later self.assertNotEqual(original_updated_at, new_obj.updated_at) self.assertTrue(original_updated_at < new_obj.updated_at) # tests that only the object's updated_at datetime has changed self.assertEqual(original_created_at, new_obj.created_at)
def generate_profiles(session): from faker import Faker from models.profile import Profile from password_generator import PasswordGenerator faker = Faker() pwo = PasswordGenerator() usernames = [] mails = [] for i in range(0, 8000): profile = faker.simple_profile() while profile['username'] in usernames or profile['mail'] in mails: print('generating profile') profile = faker.simple_profile() username, name, surname, mail, address, sex, birth_date = parse_profile( profile) profile = Profile() profile.username = username profile.name = name profile.surname = surname profile.mail = mail profile.address = address profile.sex = sex profile.birth_date = birth_date profile.password = pwo.generate() profile.profile_id = i + 1 session.add(profile) usernames.append(username) mails.append(mail) session.commit()
def run(): print("---------------------------------------------------------------") print("Apply/Remove Vip Status on Profile") print("---------------------------------------------------------------") i = 1 for profile in Profile.objects: print('{} - {}'.format(i, profile.get_name())) i += 1 try: profile_id = int( input("Type the profile id you want to change status: ")) profile = Profile.objects[profile_id - 1] if (type(profile) == Profile): new_profile = VipProfile(profile.get_name()) else: new_profile = Profile(profile.get_name()) new_profile.set_likes(profile.get_likes()) new_profile.save() profile.delete() except: traceback.print_exc()
def post(self): if request.form is None: return resp_data_invalid_err('Users', []) try: unique_guid = str(uuid.uuid4()) initial_pwd = 'Rckb1000!' img_file = request.files['imageFile'] if img_file: file_ext = img_file.filename.rsplit('.', 1)[1].lower() filename = '{}.{}'.format(unique_guid, file_ext) img_file.save(os.path.join(config.UPLOAD_DIR, filename)) User(guid=unique_guid, username=request.form['username'], active=True if request.form['active'] == 'true' else False, password=bcrypt.hashpw(initial_pwd.encode('utf-8'), bcrypt.gensalt()), profile=Profile(name=request.form['profile.name'], cellPhone=request.form['profile.cellPhone'], avatar=filename), roles=Roles(admin=True if request.form['role'] == 'administrator' else False, superuser=True if request.form['role'] == 'superuser' else False, collaborator=True if request.form['role'] == 'collaborator' else False)).save() return resp_user_created('Users', request.form['username']) except NotUniqueError: return resp_not_unique_err('Users', 'usuário') except Exception as ex: # pylint: disable=broad-except return resp_exception_err('Users', ex.__str__())
def test_delete_profile(self): """ tests the storage.delete() method removes and commits obj to database for an object from the Profile class """ # connect to MySQL database through MySQLdb and get initial count db = connect(host=ION_MYSQL_HOST, user=ION_MYSQL_USER, passwd=ION_MYSQL_PWD, db=ION_MYSQL_DB) cur = db.cursor() cur.execute("""SELECT * FROM profiles""") objs_for_count1 = cur.fetchall() # creates new instance of Profile new_obj = Profile() # tests that the new object is of type Profile self.assertIs(type(new_obj), Profile) # adds all attributes required for testing # (id should be set by primary key) # (created_at, updated_at should be set by datetime) new_obj.name = "test_name" new_obj.email = "*****@*****.**" # save the object with BaseModel save method # save method calls storage.new() and storage.save() new_obj.save() # closes connection to database and restarts connection with MySQLdb cur.close() db.close() db = connect(host=ION_MYSQL_HOST, user=ION_MYSQL_USER, passwd=ION_MYSQL_PWD, db=ION_MYSQL_DB) cur = db.cursor() cur.execute("""SELECT * FROM profiles""") objs_for_count2 = cur.fetchall() # tests that there is one more obj saved to profiles table in db self.assertEqual(len(objs_for_count1) + 1, len(objs_for_count2)) # delete the object with BaseModel delete method # delete instance method calls storage.delete() and storage.save() new_obj.delete() # closes connection to database and restarts connection with MySQLdb cur.close() db.close() db = connect(host=ION_MYSQL_HOST, user=ION_MYSQL_USER, passwd=ION_MYSQL_PWD, db=ION_MYSQL_DB) cur = db.cursor() cur.execute("""SELECT * FROM profiles""") objs_for_count3 = cur.fetchall() # tests that there is one less obj in profiles table in db self.assertEqual(len(objs_for_count2) - 1, len(objs_for_count3)) self.assertEqual(len(objs_for_count1), len(objs_for_count3)) # closes the connection cur.close() db.close()
def test_class_and_subclass(self): """ tests that instances are of Profile class and are a subclass of BaseModel class """ new_obj = Profile() # tests that the new instance is of type Profile self.assertIs(type(new_obj), Profile) # tests that the new instance is a subclass of BaseModel self.assertIsInstance(new_obj, BaseModel)
def test_all_profiles_count(self): """ tests all method retrieves all objects when class is Profile """ # connect to MySQL database through MySQLdb and get initial count db = connect(host=ION_MYSQL_HOST, user=ION_MYSQL_USER, passwd=ION_MYSQL_PWD, db=ION_MYSQL_DB) cur = db.cursor() cur.execute("""SELECT * FROM identities""") identity_objs = cur.fetchall() cur.execute("""SELECT * FROM profiles""") profile_objs = cur.fetchall() cur.execute("""SELECT * FROM skills""") skills_objs = cur.fetchall() total_count = len(identity_objs) + len(profile_objs) + len(skills_objs) total_profile_count = len(profile_objs) # call storage.all() method, both with and without class specified all_objs = storage.all() count1 = len(all_objs.keys()) all_profile_objs = storage.all(Profile) profile_count1 = len(all_profile_objs.keys()) # tests that counts from all method match current database self.assertEqual(total_count, count1) self.assertEqual(total_profile_count, profile_count1) # creates new Profile obj to test with new_obj = Profile() # adds all attributes required for testing # (id should be set by primary key) # (created_at, updated_at should be set by datetime) new_obj.name = "test_name" new_obj.email = "*****@*****.**" # saves new object to the database new_obj.save() # re-call storage.all() method all_objs = storage.all() count2 = len(all_objs.keys()) all_profile_objs = storage.all(Profile) profile_count2 = len(all_profile_objs.keys()) # tests that counts increased by 1 self.assertEqual(count1 + 1, count2) self.assertEqual(profile_count1 + 1, profile_count2) # deletes new object from the database new_obj.delete() # re-call storage.all() method all_objs = storage.all() count3 = len(all_objs.keys()) all_profile_objs = storage.all(Profile) profile_count3 = len(all_profile_objs.keys()) # tests that count decreased by 1 self.assertEqual(count2 - 1, count3) self.assertEqual(count1, count3) self.assertEqual(profile_count2 - 1, profile_count3) self.assertEqual(profile_count1, profile_count3)
def test_all_profiles_dict(self): """ tests return of all method when class is Profile """ # connect to MySQL database through MySQLdb and get initial count db = connect(host=ION_MYSQL_HOST, user=ION_MYSQL_USER, passwd=ION_MYSQL_PWD, db=ION_MYSQL_DB) cur = db.cursor() cur.execute("""SELECT * FROM profiles""") profile_objs = cur.fetchall() total_profile_count = len(profile_objs) # call storage.all() method all_profile_objs = storage.all(Profile) profile_count1 = len(all_profile_objs.keys()) # tests that all method returns same count of Identity objects self.assertEqual(total_profile_count, profile_count1) # tests that all method returns dictionary self.assertIsInstance(all_profile_objs, dict) # creates new Profile obj to test with new_obj = Profile() # adds all attributes required for testing # (id should be set by primary key) # (created_at, updated_at should be set by datetime) new_obj.name = "test_name" new_obj.email = "*****@*****.**" # saves new object to the database new_obj.save() # re-call storage.all() method and test that count increased by 1 all_profile_objs = storage.all(Profile) profile_count2 = len(all_profile_objs.keys()) self.assertEqual(profile_count1 + 1, profile_count2) # tests that newly created obj is in dictionary with correct key self.assertIsInstance(storage.all(), dict) dict_key = "{}.{}".format("Profile", new_obj.id) self.assertIn(dict_key, storage.all()) # get obj attributes from stroage.all() dictionary using obj id # test that retrieved attributes match expected values obj_class = storage.all().get("Profile.{}".format( new_obj.id)).__class__.__name__ self.assertEqual("Profile", obj_class) obj_name = storage.all().get("Profile.{}".format(new_obj.id)).name self.assertEqual("test_name", obj_name) obj_email = storage.all().get("Profile.{}".format(new_obj.id)).email self.assertEqual("*****@*****.**", obj_email) # delete new object from the database new_obj.delete() # re-call storage.all() method and test that count decreased by 1 all_profile_objs = storage.all(Profile) profile_count3 = len(all_profile_objs.keys()) self.assertEqual(profile_count2 - 1, profile_count3) self.assertEqual(profile_count1, profile_count3) # tests that new object is no longer in return dictionary self.assertNotIn(dict_key, storage.all())
def post(self): args = parser.parse_args() profile = Profile(email=args['email'], name=args['name'], password=hashlib.sha224( args['password'].encode('utf-8')).hexdigest(), thelmies=100) db.add(profile) db.commit() return jsonify(profile)
def test_str_method(self): """ tests the __str__ method returns the correct format this method is inherited from BaseModel, but should show Profile class """ # creates new instance of Profile and saves variables new_obj = Profile() obj_id = new_obj.id obj_dict = new_obj.__dict__ # tests the string representation of object is formatted correctly self.assertEqual(str(new_obj), "[Profile.{}] {}".format(obj_id, obj_dict))
async def test_body(): p = Profile(102) wp = WeightProfile(p) target_weight = 88 points = await wp.get_weight_points_for_profile() if not points: n_days = 25 current_date = datetime.now() - timedelta(minutes=30) current_weight = 96.7 d_w = [] for _ in range(n_days): d_w.append([current_date, current_weight]) current_weight -= random.uniform(-1.5, 0.6) current_date -= timedelta(days=1) for d, w in d_w: print(f'{d} ==> {w:.1f}') await WeightProfile._report_weight(p.ident, d, w, 50) points = await wp.get_weight_points_for_profile() a, b = wp.estimate_weight_curve(points) if a is not None: def solve_lin(target_y, a, b): return (target_y - b) / a target_ts = solve_lin(target_weight, a, b) print(datetime.fromtimestamp(target_ts)) time_stamps = np.array([tp.ts for tp in points], dtype=np.uint32) weights = np.array([tp.weight for tp in points], dtype=np.float) plt.axvline(datetime.fromtimestamp(target_ts)) dates = [datetime.fromtimestamp(tp.ts) for tp in points] plt.plot(dates, weights, 'g^') ts_fit = np.linspace( np.min(time_stamps) - 3 * DAY, target_ts + 3 * DAY, 100) weights_fit = a * ts_fit + b date_fit = [datetime.fromtimestamp(ts) for ts in ts_fit] plt.plot(date_fit, weights_fit, 'r') plt.show() else: print('unkown!')
async def handle(self, input_message: Message): profile = Profile(input_message.from_user.id) io_obj = await DialogIO.load(profile, input_message.text, input_message.location, self.sender) io_obj.username = input_message.from_user.username io_obj.message = input_message await io_obj.profile.set_username(io_obj.username) await io_obj.profile.activity() if await self.command_handler(input_message, io_obj): return await self.revolve_io(io_obj)
def register(): request_json = request.get_json() if request.method == 'POST': user = Profile(request_json['name'], request_json['password'], None, 2000) tmp = session.query(Profile).filter(Profile.name == user.name).first() if tmp is None: session.add(user) session.commit() return "True" else: return "False" else: return "not post"
def setUp(self): self.pdao = ProfileDAO(DB_PATH) self.profile = Profile() self.profile.address = 'TEST 1' self.profile.comp_address = 'TEST 2' self.profile.zipcode = '13132' self.profile.email = '[email protected]' self.profile.name = 'TEST' self.profile.password = '******' self.profile.country = 'FRANCE' self.profile.firstname = 'TEST 4' self.profile.siret = '0292029102' self.profile.phone = '0439403920' self.profile.city = 'MARSEILLE'
def run(): print("---------------------------------------------------------------") print("Create a new Profile") print("---------------------------------------------------------------") profile_vip = input("Is the profile vip? (y/n) ") profile_name = input("Type the profile name: ") if (profile_vip == 'y' or profile_vip == 'Y'): profile = VipProfile(profile_name) else: profile = Profile(profile_name) profile.save()
def create(): try: hashed_pass = bcrypt.hashpw(FC_ADMIN_PASS.encode('utf-8'), bcrypt.gensalt()) unique_guid = str(uuid.uuid4()) User( guid = unique_guid, username = FC_ADMIN_USER, password = hashed_pass, active=True, roles=Roles(admin=True, collaborator=False, superuser=False), profile=Profile(name='Administrator', cellPhone='(99)99999-9999', avatar='') ).save() except Exception as e: pass
def test_save_method(self, mock_storage): """ tests that the save() method inherited from BaseModel calls on storage.new() to add and commit the object to the database """ # creates new instance of Profile new_obj = Profile() # adds name and email as required attribute for database # (id should be set by primary key) # (created_at, updated_at should be set by datetime) new_obj.name = "test_name" new_obj.email = "*****@*****.**" # saves new instance and tests if storage method new is called new_obj.save() self.assertTrue(mock_storage.new.called)
async def _notify_one_user(self, user_id, now_ts): profile = Profile(user_id) wp = WeightProfile(profile) today_weight = await wp.get_today_weight() if today_weight is not None: # he has entered weight for today -> skip return last_ts = await profile.get_prop(self.KEY_LAST_SENT_TS) last_ts = 0 if last_ts is None else int(last_ts) if now_ts > last_ts + self.NOTIFICATION_COOLDOWN: await profile.set_prop(self.KEY_LAST_SENT_TS, now_ts) await self._send_notification(profile)
def create_profile(): form = ProfileForm() if form.is_submitted() and form.errors == {}: print("check herer 2") profile = Profile(user_id=current_user.id, position=form.position.data, location=form.location.data, skills=form.more_skill.data) print(form.more_skill.data) storage.new(profile) storage.save() flash('Your post has been created!', 'success') return redirect(url_for('profile')) return render_template('create_profile.html', title='Profile', form=form, method='POST')
def create_profile(): """ create a new instance of Profile through POST request """ # get JSON from POST request json = request.get_json(silent=True) # checks for missing attributes if json is None: abort(400, 'Not a JSON') if 'name' not in json: abort(400, 'Missing name attribute') if 'email' not in json: abort(400, 'Missing email attribute') # create new instance with **kwargs from json new_obj = Profile(**json) new_obj.save() # return json version of object's to_dict() return jsonify(new_obj.to_dict()), 201
def create_profile(cls, email=None, password=None, beta_tester=True, is_admin=False, is_manager=False, is_editor=False, activated=True, account=None): # TODO: Move this into a top level function (testing.create_profile) # Use defaults if anything here is missing. UserModel = cls.get_auth().store.user_model if not email: # Generate an e-mail that should be unique... email = '%s-%s' % (UserModel.query().count(), cls.DEFAULT_EMAIL) password = password or cls.DEFAULT_PASSWORD # Create the auth.user_model. ok, user = UserModel.create_user(email, password_raw=password) if not ok: raise Exception('Error creating auth.User: %s' % email) if not account: account = cls.create_account() # Create the profile. profile = Profile(name=cls.DEFAULT_PROFILE_NAME, is_admin=is_admin, is_manager=is_manager, is_editor=is_editor, email=email, beta_tester=beta_tester, activated=activated, auth_user_id=user.key.id(), timezone='UTC', parent=account) profile.put() # Return the profile (we can get everything else with that) return profile
def user_profile(): if request.method == 'GET': submit_url = url_for('.user_profile', _method='POST') return render_template('profile_form.html', submit_url=submit_url) else: session = Session() try: form = request.form username = form['username'] if username_already_used(session, username): return "Username %s is already used. Click on <a href='%s'>Back</a> to go back" \ % (username, url_for(user_profile)) prof = Profile() prof.userid = gen_random_uid() prof.username = username prof.created = str(int(time.time() * 1000)) prof.firstname = form['firstname'] prof.lastname = form['lastname'] prof.age = form['age'] prof.bio = form['biography'] prof.gender = form['gender'] file = request.files['image'] img_filename = secure_filename(file.filename) prof.image = img_filename try: file.save( os.path.join(app.config['UPLOAD_FOLDER'], prof.userid + '_' + img_filename)) except Exception: pass session.add(prof) session.commit() except Exception: session.rollback() return "Profile submitted. Click on <a href='%s'>Back</a> to go back" % url_for( '.user_profile')
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get Profile from datastore user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # create new Profile if not there if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile # return Profile