def setUp(self): #app = main.app.test_client() db.create_all() db.session.add(User("mtest","*****@*****.**", "0d66db5457fc3e401b0eea9e1ba0a1dc","121","picurl.jpeg")) db.session.add(User("m2test","*****@*****.**", "0d66db5457fc3e401b0eea9e1ba0a1dc","345","mypic.jpeg")) env1 = Envelope("env1","mtest","someone","369") env1.eowner = "1" db.session.add(env1) env2 = Envelope("env2","mtest","no one","248") env2.eowner = "1" db.session.add(env2) #env1 = Envelope.query.filter_by(handle="369").first() db.session.add(Image("1","image1.com","image1.jpg")) db.session.add(Image("1","image2.com","image2.png")) db.session.add(Image("1","image3.com","image3.gif")) db.session.add(Image("2","image-a.com","img.jpg")) db.session.add(Image("2","image-b.com","img.png")) db.session.add(History("1","V","1",None)) db.session.add(History("1","V","2",None)) db.session.add(History("1","D","2","3")) db.session.add(History("1","D",None,"1")) db.session.add(History("1","C","1",None)) db.session.add(History("2","C","1",None)) db.session.commit()
def setUp(self): self.u0 = User('U0G9QF9C6') self.u0.email = '*****@*****.**' self.u0.github_id = '305834954' self.u1 = User('Utheomadude') self.u1.email = '*****@*****.**' self.u1.github_id = '349850564' self.admin = create_test_admin('Uadmin') self.lead = User('Ualley') self.lead.email = '*****@*****.**' self.lead.github_id = '2384858' self.lead.permissions_level = Permissions.team_lead self.t0 = Team('305849', 'butter-batter', 'Butter Batters') self.t0.add_member(self.u0.github_id) self.t0.add_member(self.lead.github_id) self.t0.add_team_lead(self.lead.github_id) self.t1 = Team('320484', 'aqua-scepter', 'Aqua Scepter') self.t1.add_member(self.u1.github_id) self.t2 = Team('22234', 'tiger-dear', 'Shakespearean') self.db = MemoryDB(users=[self.u0, self.u1, self.admin, self.lead], teams=[self.t0, self.t1, self.t2]) self.cmd = ExportCommand(self.db)
def register(): from app import db form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data, phone_num=form.phone_num.data) u = User(form.username.data, form.password.data,form.email.data, form.phone_num.data) if (u.isExisted()): message='用户名已存在' return render_template('register.html',message=message, form=form) else: # from twilio.rest import Client # # Your Account Sid and Auth Token from twilio.com/console # account_sid = 'AC379c4955bd0f3e0f9f52ec086dcb7c1c' # auth_token = '79ff623bc3b52af312c0562cad571c66' # # auth_token = '8240d2517918932a997b8bb195911234' # client = Client(account_sid, auth_token) # message = client.messages.create( # from_='+12482152894', # body=str(form.username.data)+'用户名已由%s注册'%form.phone_num.data, # to='+8615966652606' # # to='+8618866812508' # ) # print(message.sid) db.session.add(user) db.session.commit() return redirect(url_for('auth.login'))#重定向登陆页面 return render_template('register.html', form=form)
def test_find_user_multiple(self): NICK, NAME = 'multiple_228', 'Marin Komitsky' sneaky_user = User(nick=NICK, name=NAME, avatar='') sneaky_user2 = User(nick=NICK + '_1', name=NAME + '_1', avatar='') db.session.add_all([sneaky_user, sneaky_user2]) db.session.commit() def _check_multiple(user): self.assertTrue(int(user['id']) in [sneaky_user.id, sneaky_user2.id]) self.assertTrue(user['nick'] in [sneaky_user.nick, sneaky_user2.nick]) self.assertTrue(user['name'] in [sneaky_user.name, sneaky_user2.name]) with self.subTest('Length on many matches'): users = json.loads(find_user(nick=NICK)) self.assertEqual(len(users), 2) with self.subTest('Every user is correct'): users = json.loads(find_user(nick=NICK)) for user in users: _check_multiple(user) with self.subTest('Many by first 3 letters nick'): users = json.loads(find_user(nick=NICK[:3])) self.assertEqual(len(users), 2) for user in users: _check_multiple(user) with self.subTest('Many by first 3 letters name'): users = json.loads(find_user(name=NAME[:3])) self.assertEqual(len(users), 2) for user in users: _check_multiple(user)
def test_user_equality(): """Test the User class method __eq__() and __ne__().""" user = User("brussel-sprouts") user2 = User("brussel-sprouts") user3 = User("brussel-trouts") assert user == user2 assert user != user3
def test_get_returns_200_with_all_users_list(self): # Given user_1 = User(username='******', email='*****@*****.**', password_hash='hash') user_2 = User(username='******', email='*****@*****.**', password_hash='hash') self.db.session.add(user_1) self.db.session.add(user_2) self.db.session.commit() expected = [{ 'id': 1, 'username': '******', 'email': '*****@*****.**', 'email_confirmed': False }, { 'id': 2, 'username': '******', 'email': '*****@*****.**', 'email_confirmed': False }] # When response = self.client.get('/api/users') # Then self.assert200(response) self.assertEqual(expected, response.json)
def create_users(db): print('[*] {0} - Adding users to datbase'.format(datetime.now())) # Create users from app.model import User # Sally user existing_user = User.query.filter_by(email='*****@*****.**').first() if existing_user is None: user = User(name='Sally', email='*****@*****.**', password=generate_password_hash('password123', method='sha256'), website='google.com', balance=100) db.session.add(user) # Bob user existing_user = User.query.filter_by(email='*****@*****.**').first() if existing_user is None: user = User(name='Bob', email='*****@*****.**', password=generate_password_hash('Password123!', method='sha256'), website='google.com', balance=0) db.session.add(user) # Commit users to database db.session.commit() # Query all users users = User.query.all() print(users)
def test_the_is_invalid_method_of_user_repository_with_username_already_in_use( app): """ GIVEN the UserRepository class WHEN the method is_invalid(user) is called with a invalid user THEN check return True """ from app.model import UserRepository, User user_repository = UserRepository() user_repository.session = UnifiedAlchemyMagicMock() user = User() user.id = 1 user.username = '******' user.password = '******' user_repository.session.add(user) user_repository.session.commit() user = User() user.username = '******' is_invalid = user_repository.is_invalid(user) assert is_invalid assert {"username": "******"} in is_invalid
def test_search_user(self): users = [self.users[0]] with self.subTest('Search for the first user'): found, total = User.search(users[0].nick, 1, 100) self.assertEqual(total, 1) self.assertEqual(found[0], users[0]) with self.subTest('User not found'): found, total = User.search('I dont exist at all!', 1, 100) self.assertEqual(total, 0) self.assertEqual(found, []) users = [ User(name='Tom Sayer', nick='free_lancer_228', avatar=''), User(name='Tom Balmer', nick='fire_lancer_300', avatar='') ] db.session.add_all(users) db.session.commit() time.sleep(1) with self.subTest('Sayer by name'): for u in users: found, total = User.search(u.name, 1, 100) # Находит двух, но с разным score self.assertEqual(total, 2) with self.subTest('Say* by name'): found, total = User.search('Tom', 1, 100) self.assertEqual(total, 2, 'Expected to find 2 users') with self.subTest('by nickname'): for u in users: found, total = User.search(u.nick, 1, 100) self.assertEqual(total, 1) self.assertEqual(found[0], u)
def add_user(self): """Adds Test user to database""" try: user = User.query.filter_by(Client_id='testuser').first() db.session.delete(user) db.session.commit() user2 = User.query.filter_by(Client_id='testuser2').first() db.session.delete(user2) db.session.commit() except: pass pass_hash = bcrypt_sha256.encrypt("password", rounds=12) test_user_insert = User(Client_id='testuser', Password=pass_hash, api_key='api-key', current_login_ip='127.0.0.1') db.session.add(test_user_insert) db.session.commit() test_user_insert_2 = User(Client_id='testuser2', Password=pass_hash, api_key='api-key', current_login_ip='127.0.0.2') db.session.add(test_user_insert_2) db.session.commit() return test_user_insert
def test_invalid_confirmation_token(self): u1 = User(password='******') u2 = User(password='******') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_confirmation_token() self.assertFalse(u2.confirm(token))
def setUp(self): self.app = Flask(__name__) self.u0 = User('UFJ42EU67') self.u0.name = 'steve' self.u1 = User('U12346456') self.u1.name = 'maria' self.db = MemoryDB(users=[self.u0, self.u1]) self.testcommand = MentionCommand(self.db)
def test_handle_set_as_non_admin(self): """Test setting karma as non admin.""" user = User("ABCDEFG2F") destuser = User("MMMM1234") user.permissions_level = Permissions.member self.mock_facade.retrieve.side_effect = [user, destuser] self.assertEqual(self.testcommand.handle("karma set MMMM1234 10", "ABCDEFG2F"), (KarmaCommand.permission_error, 200)) self.mock_facade.retrieve.assert_called_once_with(User, "ABCDEFG2F")
def init_prod(): start_mapper() init_prod_db() user1 = User("user1", guard.hash_password("secret1")) user2 = User(username="******", password=guard.hash_password("secret2")) user3 = User(username="******", password=guard.hash_password("secret3")) db_session.add_all([user1, user2, user3]) db_session.commit()
def setUp(self): self.app = Flask(__name__) self.u0 = User('U0G9QF9C6') self.u1 = User('Utheomadude') self.admin = create_test_admin('Uadmin') self.db = MemoryDB(users=[self.u0, self.u1, self.admin]) self.mock_github = mock.MagicMock(GithubInterface) self.testcommand = UserCommand(self.db, self.mock_github, None) self.maxDiff = None
def setUp(self): """Set up example models for use.""" self.brussel_sprouts = User('brussel-sprouts') self.brussel_sprouts2 = User('brussel-sprouts') self.brussel_trouts = User('brussel-trouts') self.no_id = User('') self.admin = User('U0G9QF9C6') self.admin.biography = 'bio test' self.admin.email = '*****@*****.**' self.admin.permissions_level = Permissions.admin
def test_handle_set_as_admin(self): """Test setting karma as admin.""" user = User("ABCDEFG2F") destuser = User("MMMM1234") user.permissions_level = Permissions.admin self.mock_facade.retrieve.side_effect = [user, destuser] self.testcommand.handle("karma set MMMM1234 10", "ABCDEFG2F") retrieve_calls = [mock.call(User, "ABCDEFG2F"), mock.call(User, "MMMM1234")] self.mock_facade.retrieve.assert_has_calls(retrieve_calls) self.mock_facade.store.assert_called_once_with(destuser)
def prepare_user(self): foo = User(name='foo', password='******', mail='*****@*****.**') bar = User(name='bar', password='******', mail='*****@*****.**') baz = User(name='baz', password='******', mail='*****@*****.**') db.session.add(foo) db.session.add(bar) db.session.add(baz) try: db.session.commit() except: db.session.rollback()
def setUp(self): self.app = Flask(__name__) self.u0 = User('U0G9QF9C6') self.u0.karma = KarmaCommand.karma_default_amount self.u1 = User('UFJ42EU67') self.u0.karma = KarmaCommand.karma_default_amount self.admin = create_test_admin('Uadmin') self.db = MemoryDB(users=[self.u0, self.u1, self.admin]) self.testcommand = KarmaCommand(self.db) self.maxDiff = None
def test_handle_add_overwriting(self): """Test user command add method when user exists in db.""" user_id = "U0G9QF9C6" user2_id = "U0G9QF9C69" user = User(user_id) user2 = User(user2_id) self.testcommand.handle('user add -f', user_id) self.mock_facade.store.assert_called_with(user) self.testcommand.handle('user add --force', user2_id) self.mock_facade.store.assert_called_with(user2) self.mock_facade.retrieve.assert_not_called()
def test_make_unique_account_name(self): u=User(account_name='sean',firstname='sean',lastname='scott',email='*****@*****.**',password='******') db.session.add(u) db.session.commit() account_name = User.make_unique_account_name('sean') assert account_name !='sean' u=User(account_name=account_name,firstname='sean1',lastname='scott1',email='*****@*****.**',password='******') db.session.add(u) db.session.commit() account_name2=User.make_unique_account_name('sean') assert account_name2 !='sean' assert account_name2 != account_name
def setUp(self): self.u0 = User('U395474') self.u0.github_id = '321132' self.u1 = User('U85739') self.u1.github_id = '000584' self.u2 = User('U3048485') self.u2.github_id = '11121' self.t0 = Team('305738', 'some-team', 'Some Team') self.t0.add_member(self.u0.github_id) self.t0.add_member(self.u1.github_id) self.t1 = Team('305849', 'some-team', 'Some Team') self.db = MemoryDB(users=[self.u0, self.u1, self.u2], teams=[self.t0])
def setUp(self): self.app = Flask(__name__) self.u0 = User('U0G9QF9C6') self.u1 = User('Utheomadude') self.t0 = Team("BRS", "brs", "web") self.t1 = Team("OTEAM", "other team", "android") self.admin = create_test_admin('Uadmin') self.db = MemoryDB(users=[self.u0, self.u1, self.admin], teams=[self.t0, self.t1]) self.mock_github = mock.MagicMock(GithubInterface) self.testcommand = UserCommand(self.db, self.mock_github, None) self.maxDiff = None
def user_add(self, add_user_id: str, use_force: bool = False) -> bool: """ Add a user to the database via user ID. :param add_user_id: Slack ID of the user to be added :param use_force: If this is set, we store the user even iff they are already added in the database :raises: RuntimeError if the user has already been added and ``user_force`` is False :return: True if the user was successfully added, False otherwise """ # Try to look up and avoid overwriting if we are not using force if not use_force: try: self._db_facade.retrieve(User, add_user_id) msg = f"User with Slack ID {add_user_id} already exists" logging.error(msg) raise RuntimeError(msg) except LookupError: logging.info(f"User with Slack ID {add_user_id} " "not in database") return self._db_facade.store(User(add_user_id))
def test_the_update_method_of_user_repository(app): """ GIVEN the UserRepository class WHEN the method update(user) is called THEN check session method calls and user data """ from app.model import UserRepository, User user_repository = UserRepository() user_repository.session = UnifiedAlchemyMagicMock() user = User(username=get_unique_username(), password="******") user_repository.session.add(user) user_repository.session.commit() # updating username_edited = get_unique_username() user.password = "******" user.username = username_edited user_repository.update(user) # user_repository.session.commit.assert_called_once_with() assert check_password_hash(user.password, "1234") assert user.username == username_edited assert user.serialize() == { 'id': str(user.id), 'username': username_edited } assert str(user) == '<User %r>' % (username_edited)
def test_the_is_invalid_method_of_user_repository_with_corrent_data_of_existent_user( app): """ GIVEN the UserRepository class WHEN the method is_invalid(user) is called with a valid user THEN check return True """ from app.model import UserRepository, User user_repository = UserRepository() user_repository.session = UnifiedAlchemyMagicMock() user = User() user.id = 1 user.username = '******' user.password = '******' user_repository.session.add(user) user_repository.session.commit() # update user.username = '******' user.password = '******' is_invalid = user_repository.is_invalid(user) assert not is_invalid
def test_the_authenticate_method_of_user_repository(app): """ GIVEN the UserRepository class WHEN the method authenticate(username, password) is called THEN check the method returning """ from app.model import UserRepository, User user_repository = UserRepository() user_repository.session = UnifiedAlchemyMagicMock() user = User(username=get_unique_username(), password=generate_password_hash("123")) user_repository.session.add(user) user_repository.session.commit() # correct data result = user_repository.authenticate(user.username, "123") assert result # wrong password result = user_repository.authenticate(user.username, "1234") assert not result # wrong username result = user_repository.authenticate("wrong_username", "123") assert result
def test_timestamps(self): u = User(password='******') db.session.add(u) db.session.commit() self.assertTrue( (datetime.utcnow() - u.member_since).total_seconds() < 3) self.assertTrue((datetime.utcnow() - u.last_seen).total_seconds() < 3)
def test_expired_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token))
def new_user(current_user, roles): """ Protected Route to Create a new user (requires JWT) Send a post request with a json payload consisting of a username and a password Returns: - 200 status code and the newly registered username and password """ # load data from request add_user = request.get_json() # hash password and save user to db hashed_password = generate_password_hash(add_user['password'], method='pbkdf2:sha512') new_user = User(username=add_user['username'], password=hashed_password, email=add_user['email']) db.session.add(new_user) db.session.commit() response_dict = { "status": "Success", "id": new_user.id, "name": add_user['username'] } return jsonify({"data": response_dict})