def test_count_all(self): ids = [self.user.id] for _ in range(3): user = yield User(first_name="blah").save() ids.append(user.id) results = yield User.count() self.assertEqual(4, results)
def login(): if request.method == 'GET': return ''' <form action='login' method='POST'> <input type='text' name='username' id='username' placeholder='username'></input> <input type='password' name='password' id='password' placeholder='password'></input> <input type='submit' name='submit'></input> </form> ''' username = request.form['username'] try: if request.form['password'] == users[username]['password']: user = User() #Attribute this user to a player object player_to_be_attributed = None for player in glob.players: if not player.isAttributed(): player_to_be_attributed = player break player_to_be_attributed.attribute() user.id = username glob.usernameToPlayer[username] = player_to_be_attributed flask_login.login_user(user) return flask.redirect(flask.url_for('index')) except KeyError: return flask.redirect(flask.url_for('unprotected'))
def test_findOrCreate(self): # make sure we didn't create a new user r = yield User.findOrCreate(first_name="First") self.assertEqual(r.id, self.user.id) # make sure we do create a new user r = yield User.findOrCreate(first_name="First", last_name="Non") self.assertTrue(r.id != self.user.id)
def test_count(self): ids = [] for _ in range(3): user = yield User(first_name="blah").save() ids.append(user.id) yield User(first_name="not blah").save() results = yield User.count(where=["first_name = ?", "blah"]) self.assertEqual(3, results)
def test_all(self): ids = [self.user.id] for _ in range(3): user = yield User(first_name="blah").save() ids.append(user.id) results = yield User.all() resultids = [result.id for result in results] self.assertEqual(ids, resultids)
def test_update(self): tablename = User.tablename() user = yield User(first_name="Another First").save() args = {'first_name': "test", "last_name": "foo", "age": 91} yield self.dbconfig.update(tablename, args, ['id = ?', user.id]) yield user.refresh() for key, value in args.items(): self.assertEqual(value, getattr(user, key))
def setUp(self): self.USER_GNUPGHOME = tempfile.TemporaryDirectory() self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory() self.NEW_USER_GNUPGHOME = tempfile.TemporaryDirectory() self.NEW_ADMIN_GNUPGHOME = tempfile.TemporaryDirectory() self.SEED_DIR = tempfile.TemporaryDirectory() self.config = ConfigParser() self.config.read_string(""" [mtls] min_lifetime=60 max_lifetime=0 seed_dir={seed_dir} [ca] key = secrets/certs/authority/RootCA.key cert = secrets/certs/authority/RootCA.pem issuer = My Company Name alternate_name = *.myname.com [gnupg] user={user_gnupghome} admin={admin_gnupghome} [storage] engine=sqlite3 [storage.sqlite3] db_path=:memory: """.format( user_gnupghome=self.USER_GNUPGHOME.name, admin_gnupghome=self.ADMIN_GNUPGHOME.name, seed_dir=self.SEED_DIR.name, )) self.common_name = "user@host" self.key = generate_key() self.engine = storage.SQLiteStorageEngine(self.config) cur = self.engine.conn.cursor() cur.execute("DROP TABLE IF EXISTS certs") self.engine.conn.commit() self.engine.init_db() self.cert_processor = CertProcessor(self.config) self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name) self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name) self.new_user_gpg = gnupg.GPG(gnupghome=self.NEW_USER_GNUPGHOME.name) self.new_admin_gpg = gnupg.GPG(gnupghome=self.NEW_ADMIN_GNUPGHOME.name) self.new_users = [ User("user@host", gen_passwd(), generate_key(), gpg=self.new_user_gpg) ] self.new_admins = [ User("admin@host", gen_passwd(), generate_key(), gpg=self.new_admin_gpg) ]
def test_delete_all(self): users = yield User.all() ids = [user.id for user in users] for _ in range(3): yield User(first_name="blah").save() yield User.deleteAll(["first_name = ?", "blah"]) users = yield User.all() resultids = [user.id for user in users] self.assertEqual(resultids, ids)
def test_delete(self): tablename = User.tablename() yield User(first_name="Another First").save() yield self.dbconfig.delete(tablename, ['first_name like ?', "%nother Fir%"]) result = yield self.dbconfig.select(tablename) self.assertEqual(len(result), 1) self.assertTrue(result[0]['id'] == self.user.id)
def test_find(self): ids = [] for _ in range(3): user = yield User(first_name="blah").save() ids.append(user.id) yield User(first_name="not blah").save() results = yield User.find(where=["first_name = ?", "blah"]) resultids = [result.id for result in results] self.assertEqual(ids, resultids)
def run(txn): tablename = User.tablename() args = {'first_name': "test", "last_name": "foo", "age": 91} objid = self.dbconfig.insert(tablename, args, txn) users = self.dbconfig._doselect(txn, "select * from %s" % User.tablename(), [], User.tablename()) self.assertEqual(len(users), 2) self.assertEqual(users[1]['id'], objid) for key, value in args.items(): self.assertEqual(value, users[1][key])
def test_new_rating(self): new_rating = self.gl2.create_rating() user = User(self.app, username="******", perfs={variant: DEFAULT_PERF for variant in VARIANTS}) result = user.get_rating("chess", False) self.assertEqual(result.mu, new_rating.mu)
def user_loader(username): try: if username not in users: return user = User() user.id = username user.loadUser(glob.usernameToPlayer[username]) return user except: return
def setUp(self): self.USER_GNUPGHOME = tempfile.TemporaryDirectory() self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory() config = ConfigParser() config.read_string( """ [ca] key = secrets/certs/authority/RootCA.key cert = secrets/certs/authority/RootCA.pem issuer = My Company Name alternate_name = *.myname.com [gnupg] user={user_gnupghome} admin={admin_gnupghome} [storage] engine=postgres [storage.postgres] database = mtls user = postgres password = postgres host = localhost """.format( user_gnupghome=self.USER_GNUPGHOME.name, admin_gnupghome=self.ADMIN_GNUPGHOME.name, ) ) self.common_name = "user@host" self.key = generate_key() self.engine = storage.PostgresqlStorageEngine(config) cur = self.engine.conn.cursor() cur.execute("DROP TABLE IF EXISTS certs") self.engine.conn.commit() self.engine.init_db() self.cert_processor = CertProcessor(config) self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name) self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name) self.users = [ User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg), User("user2@host", gen_passwd(), generate_key(), gpg=self.user_gpg), User("user3@host", gen_passwd(), generate_key(), gpg=self.user_gpg), ] self.invalid_users = [ User("user4@host", gen_passwd(), generate_key(), gpg=self.user_gpg) ] self.admin_users = [ User("admin@host", gen_passwd(), generate_key(), gpg=self.admin_gpg) ] for user in self.users: self.user_gpg.import_keys(self.user_gpg.export_keys(user.fingerprint)) for user in self.admin_users: self.admin_gpg.import_keys(self.admin_gpg.export_keys(user.fingerprint))
def test_joinMultipleWheres(self): yield User(first_name="First", last_name="Last", age=20).save() first = ['first_name = ?', "First"] last = ['last_name = ?', "Last"] age = ['age <> ?', 20] where = utils.joinMultipleWheres([first, last, age], joiner='AND') results = yield User.count(where=where) self.assertEqual(1, results)
def test_update(self): args = {'first_name': "a", "last_name": "b", "age": 10} u = yield User(**args).save() args = {'first_name': "b", "last_name": "a", "age": 100} for key, value in args.items(): setattr(u, key, value) yield u.save() u = yield User.find(u.id) for key, value in args.items(): self.assertEqual(getattr(u, key), value)
def setUp(self): dir_path = os.path.dirname(os.path.realpath(__file__)) self.USER_GNUPGHOME = tempfile.TemporaryDirectory(prefix=dir_path + "/secrets/") self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory(prefix=dir_path + "/secrets/") relative_user = "******" + self.USER_GNUPGHOME.name.split(dir_path)[1] relative_admin = "." + self.ADMIN_GNUPGHOME.name.split(dir_path)[1] config = ConfigParser() config.read_string( """ [ca] key = secrets/certs/authority/RootCA.key cert = secrets/certs/authority/RootCA.pem issuer = My Company Name alternate_name = *.myname.com [gnupg] user={user_gnupghome} admin={admin_gnupghome} [storage] engine=sqlite3 [storage.sqlite3] db_path=:memory: """.format( user_gnupghome=relative_user, admin_gnupghome=relative_admin ) ) self.common_name = "user@host" self.key = generate_key() self.engine = storage.SQLiteStorageEngine(config) cur = self.engine.conn.cursor() cur.execute("DROP TABLE IF EXISTS certs") self.engine.conn.commit() self.engine.init_db() self.cert_processor = CertProcessor(config) self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name) self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name) self.users = [ User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg), User("user2@host", gen_passwd(), generate_key(), gpg=self.user_gpg), User("user3@host", gen_passwd(), generate_key(), gpg=self.user_gpg), ] self.invalid_users = [ User("user4@host", gen_passwd(), generate_key(), gpg=self.user_gpg) ] self.admin_users = [ User("admin@host", gen_passwd(), generate_key(), gpg=self.admin_gpg) ] for user in self.users: self.user_gpg.import_keys(self.user_gpg.export_keys(user.fingerprint)) for user in self.admin_users: self.admin_gpg.import_keys(self.admin_gpg.export_keys(user.fingerprint))
def setUp(self): self.USER_GNUPGHOME = tempfile.TemporaryDirectory() self.ADMIN_GNUPGHOME = tempfile.TemporaryDirectory() self.AUTHORITY_FOLDER = tempfile.TemporaryDirectory() config = ConfigParser() config.read_string( """ [ca] key = {authority_folder}/RootCA.key cert = {authority_folder}/RootCA.pem issuer = My Company Name alternate_name = *.myname.com [gnupg] user={user_gnupghome} admin={admin_gnupghome} [storage] engine=sqlite3 [storage.sqlite3] db_path=:memory: """.format( user_gnupghome=self.USER_GNUPGHOME.name, admin_gnupghome=self.ADMIN_GNUPGHOME.name, authority_folder=self.AUTHORITY_FOLDER.name, ) ) self.common_name = "user@host" self.key = generate_key() self.engine = storage.SQLiteStorageEngine(config) cur = self.engine.conn.cursor() cur.execute("DROP TABLE IF EXISTS certs") self.engine.conn.commit() self.engine.init_db() self.cert_processor = CertProcessor(config) self.user_gpg = gnupg.GPG(gnupghome=self.USER_GNUPGHOME.name) self.admin_gpg = gnupg.GPG(gnupghome=self.ADMIN_GNUPGHOME.name) self.users = [ User("user@host", gen_passwd(), generate_key(), gpg=self.user_gpg), User("user2@host", gen_passwd(), generate_key(), gpg=self.user_gpg), User("user3@host", gen_passwd(), generate_key(), gpg=self.user_gpg), ] self.invalid_users = [ User("user4@host", gen_passwd(), generate_key(), gpg=self.user_gpg) ] self.admin_users = [ User("admin@host", gen_passwd(), generate_key(), gpg=self.admin_gpg) ] for user in self.users: self.user_gpg.import_keys(self.user_gpg.export_keys(user.fingerprint)) for user in self.admin_users: self.admin_gpg.import_keys(self.admin_gpg.export_keys(user.fingerprint))
def test_joinWheres_precedence(self): yield User(first_name="Second").save() first = ['first_name = ?', "First"] last = ['last_name = ?', "Last"] second = ['first_name = ?', "Second"] last_or_second = utils.joinWheres(last, second, joiner='OR') where = utils.joinWheres(first, last_or_second, joiner='AND') results = yield User.count(where=where) self.assertEqual(1, results)
def test_select(self): # make a fake user user = yield User(first_name="Another First").save() tablename = User.tablename() where = ['first_name = ?', "First"] result = yield self.dbconfig.select(tablename, where=where, limit=1, orderby="first_name ASC") self.assertTrue(result is not None) self.assertEqual(result['id'], self.user.id) result = yield self.dbconfig.select(tablename, limit=100, orderby="first_name ASC") self.assertEqual(len(result), 2) self.assertTrue(result[0]['id'] == user.id and result[1]['id'] == self.user.id)
def test_update_obj(self): args = {'first_name': "test_insert_obj", "last_name": "foo", "age": 91} user = yield User(**args).save() args = {'first_name': "test_insert_obj_foo", "last_name": "bar", "age": 191} for key, value in args.items(): setattr(user, key, value) yield self.dbconfig.updateObj(user) user = yield User.find(user.id) for key, value in args.items(): self.assertEqual(value, getattr(user, key))
def test_insert_obj(self): args = {'first_name': "test_insert_obj", "last_name": "foo", "age": 91} user = User(**args) saved = yield self.dbconfig.insertObj(user) user = yield User.find(where=['first_name = ?', "test_insert_obj"], limit=1) # ensure that id was set on save self.assertEqual(saved.id, user.id) # and all values are still the same self.assertEqual(saved, user) for key, value in args.items(): self.assertEqual(value, getattr(user, key))
def test_insert_many(self): tablename = User.tablename() args = [] for counter in range(10): args.append({'first_name': "test_insert_many", "last_name": "foo", "age": counter}) yield self.dbconfig.insertMany(tablename, args) users = yield User.find(where=['first_name = ?', "test_insert_many"], orderby="age ASC") for counter in range(10): for key, value in args[counter].items(): self.assertEqual(value, getattr(users[counter], key))
def test_insert(self): tablename = User.tablename() args = {'first_name': "test", "last_name": "foo", "age": 91} id = yield self.dbconfig.insert(tablename, args) where = ['first_name = ? AND last_name = ? AND age = ?'] where = where + ["test", "foo", 91] users = yield User.find(where=where) self.assertEqual(len(users), 1) self.assertEqual(users[0].id, id) for key, value in args.items(): self.assertEqual(value, getattr(users[0], key))
def test_beforeDelete(self): User.beforeDelete = lambda user: False u = yield User().save() oldid = u.id yield u.delete() result = yield User.find(oldid) self.assertEqual(result, u) User.beforeDelete = lambda user: True yield u.delete() result = yield User.find(oldid) self.assertEqual(result, None) # restore user's beforeDelete User.beforeDelete = DBObject.beforeDelete
def register(self, conn, user_name): '''register new user, and login the user''' if user_name in users: self.__send_data_close(conn, usr_exist) return False user = User(username=user_name) user.login(conn) users[user_name] = user conn_user_map[conn] = user token_user_map[user.token] = user self.__send_data(conn=conn, info=info_ok, kind=kind_register, token=user.token) return True
def on_join(self, c, e): """Hook for someone joining the channel (/join). --> e.target() == channel --> e.source() == nick!~user@hostname """ nick, channame, hostname = nm_to_n( e.source()), e.target().lower(), nm_to_h(e.source()) if self.nick != nick: chan = self.chans[channame] self.users[nick] = user = User(nick, hostname, self.connection) if \ not nick in self.users else self.users[nick] user.channels += [chan] chan.users += [user] data = Data(line_raw=nick, reaction_type="join", chan=chan, user=user) self.dispatch(data) else: self.chans[channame] = chan = Channel(channame, self.connection) data = Data(line_raw=channame, reaction_type="enter_channel", chan=chan) self.dispatch(data)
def new_external_order(): if request.method == 'POST': data = request.form.to_dict() try: scenelist = data['input_product_list'] _u, _p = base64.b64decode(data['user']).split(':') resp_json = api_get('/user', uauth=(_u, _p)) if 'username' in resp_json: session['logged_in'] = True resp_json['wurd'] = _p session['user'] = User(**resp_json) else: logger.info( '*** Failed external order user login: {}'.format(_u)) return jsonify({'msg': 'user auth failed'}), 401 except KeyError: return jsonify({ 'error': "'input_product_list' and 'user' fields are required" }), 401 except Exception as e: logger.info( "*** espa-web exception - problem parsing external order request. message: {}" .format(e.message)) return jsonify({'error': 'problem parsing request'}), 400 else: # GET redirect from ESPA after order validation scenelist = session['ipl'] return render_template('new_order.html', form_action=url_for('submit_order'), scenelist=scenelist)
def log_out(self, message_content): user_to_remove = message_content.get(MessageFields.SENDER_USERNAME) if user_to_remove: self.users_dict[user_to_remove] = User(None, None, False) print("Went offline: {}".format(user_to_remove)) else: warnings.warn('no such user exists')
def setup_test_context(request): recipient = User( email=request.config.getoption('--recipient'), password=request.config.getoption('--recipient_password') ) sender = User( email=request.config.getoption('--sender'), password=request.config.getoption('--sender_password') ) return SetupConfig( recipient=recipient, sender=sender, imap_endpoint=TestSettings.imap_endpoint, smtp_endpoint=TestSettings.smtp_endpoint )
def test_select_id(self): tablename = User.tablename() result = yield self.dbconfig.select(tablename, self.user.id, where=None, limit=1, orderby="first_name ASC") self.assertTrue(result is not None) where = ['first_name = ?', "DNE"] result = yield self.dbconfig.select(tablename, self.user.id, where=where, limit=1, orderby="first_name ASC") self.assertTrue(result is None)
def test_validation(self): User.validatesPresenceOf('first_name', message='cannot be blank, fool.') User.validatesLengthOf('last_name', range=xrange(1, 101)) User.validatesUniquenessOf('first_name') u = User() yield u.validate() self.assertEqual(len(u.errors), 2) first = yield User(first_name="not unique", last_name="not unique").save() u = yield User(first_name="not unique", last_name="not unique").save() self.assertEqual(len(u.errors), 1) self.assertEqual(u.id, None) # make sure first can be updated yield first.save() self.assertEqual(len(first.errors), 0) User.clearValidations()
def test_afterInit(self): def afterInit(user): user.blah = "foobar" User.afterInit = afterInit u = yield User.find(limit=1) self.assertTrue(hasattr(u, 'blah')) self.assertEqual(u.blah, 'foobar') # restore user's afterInit User.afterInit = DBObject.afterInit
def test_loadRelations(self): user = yield User.find(limit=1) all = yield user.loadRelations() pictures = yield user.pictures.get() self.assertEqual(pictures, all['pictures']) avatar = yield user.avatar.get() self.assertEqual(avatar, all['avatar']) suball = yield user.loadRelations('pictures') self.assertTrue('avatar' not in suball) self.assertEqual(pictures, suball['pictures'])
def test_clear_has_many(self): pics = [self.picture] for _ in range(3): pic = yield Picture(name="a pic").save() pics.append(pic) yield self.user.pictures.set(pics) yield self.user.pictures.clear() userpics = yield self.user.pictures.get() self.assertEqual(userpics, []) # even go so far as to refetch user yield User.find(self.user.id) userpics = yield self.user.pictures.get() self.assertEqual(userpics, []) # picture records should be updated pics = yield Picture.find(where=["user_id=?", self.user.id]) self.assertEqual(pics, []) # but still exist pics = yield Picture.all() self.assertEqual(len(pics), 4)
def test_findBy(self): r = yield User.findBy(first_name="Non", last_name="Existant") self.assertEqual(r, []) r = yield User.findBy(first_name="First", last_name="Last", age=11) self.assertEqual(r, []) r = yield User.findBy(first_name="First", last_name="Last", age=10) self.assertEqual(r[0], self.user) r = yield User.findBy(first_name="First", last_name="Last") self.assertEqual(r[0], self.user) yield User(first_name="Bob").save() r = yield User.findBy() self.assertEqual(len(r), 2) yield User(first_name=None).save() r = yield User.findBy(first_name=None) self.assertEqual(len(r), 1)
def __init__(self): self.users = User.query().fetch(10)
def test_delete(self): u = yield User().save() oldid = u.id yield u.delete() result = yield User.find(oldid) self.assertEqual(result, None)
def test_validation_function(self): def adult(user): if user.age < 18: user.errors.add('age', "must be over 18.") User.addValidator(adult) u = User(age=10) valid = yield u.isValid() self.assertEqual(valid, False) yield u.save() self.assertEqual(len(u.errors), 1) self.assertEqual(len(u.errors.errorsFor('age')), 1) self.assertEqual(len(u.errors.errorsFor('first_name')), 0) User.clearValidations() u = User(age=10) valid = yield u.isValid() self.assertEqual(valid, True) User.clearValidations()