def test_update(self): app = Flask(__name__) with app.test_request_context('/'): """Test for correct return if version != request.form['version']""" request.form = ImmutableMultiDict([ ('version', str(__version__) + 'bla') ]) # faulty version request.form = ImmutableMultiDict([('song', 'Sweeter Without You') ]) # song in unsupported.txt request.form = ImmutableMultiDict([('artist', 'Borgeous') ]) # artist in unsupported.txt self.assertEqual( update(), 'Please update SwagLyrics to the latest version to get better support :)' ) """Test if right return if version below 1.0.0""" request.form = ImmutableMultiDict([('version', '0.0.9') ]) # version below 1.0.0 self.assertEqual( update(), 'Please update SwagLyrics to the latest version to get better support :)' ) """Test correct output given song and artist that exist in unsupported.txt""" request.form = ImmutableMultiDict([('version', str(__version__)) ]) # correct version self.assertEqual(update(), 'Issue already exists on the GitHub repo. \n')
def test_store_organization(client): """End-to-end tests of submitting the /validate-org-infon route with a new user and new organization.""" orgform = ImmutableMultiDict([('financial_classification', 'For-Profit'), ('coverage_scope', 'City'), ('coverage_focus', 'Investigative'), ('platform', 'Digital Only'), ('employee_range', '5 or fewer'), ('budget', '$500k-$2m'), ('news_revenue_hub', True), ('other_affiliation', True), ('other_affiliation_name', 'Baz')]) with client as c: with c.session_transaction() as sess: sess['user_name'] = 'Foo' sess['email'] = '*****@*****.**' sess['email_hash'] = 'f3ada405ce890b6f8204094deb12d8a8' sess['org'] = 'Bar' response = c.post('/validate-org-info', data=orgform) assert response.get_json()['user'] == 'other' user = AppUser.query.filter_by(email='*****@*****.**').first() assert user.name == 'Foo' assert len(user.orgs) == 1 org = user.orgs[0] assert org.name == 'Bar' assert org.budget == '$500k-$2m' assert org.affiliations == '["News Revenue Hub", "Baz"]'
def login(nickname=None, password=None, login_method=None, action='', remember_me=False, referer=None): if CFG_ACCESS_CONTROL_LEVEL_SITE > 0: return abort(401) # page is not authorized if action: try: action, arguments = mail_cookie_check_authorize_action(action) except InvenioWebAccessMailCookieError: pass form = LoginForm(CombinedMultiDict([ ImmutableMultiDict({'referer': referer} if referer else {}), request.values ]), csrf_enabled=False) try: user = None if not CFG_EXTERNAL_AUTH_USING_SSO: if login_method is 'Local': if form.validate_on_submit(): user = update_login(nickname, password, remember_me) elif login_method in ['openid', 'oauth1', 'oauth2']: pass req = request.get_legacy_request() (iden, nickname, password, msgcode) = webuser.loginUser(req, nickname, password, login_method) if iden: user = update_login(nickname) else: flash(_('Invalid login method.'), 'error') else: req = request.get_legacy_request() # Fake parameters for p_un & p_pw because SSO takes them from the environment (iden, nickname, password, msgcode) = webuser.loginUser(req, '', '', CFG_EXTERNAL_AUTH_USING_SSO) if iden: user = update_login(nickname) if user: flash(_("You are logged in as %s.") % user.nickname, "info") if referer is not None: # Change HTTP method to https if needed. referer = referer.replace(CFG_SITE_URL, CFG_SITE_SECURE_URL) return redirect(referer) except: flash(_("Problem with login."), "error") current_app.config.update( dict((k, v) for k, v in vars(websession_config).iteritems() if "CFG_" == k[:4])) return render_template('webaccount_login.html', form=form)
def test_store_existing_user(client, caplog): """End-to-end test of submitting the /validate-basic-info route with an existing user and an existing organization.""" existing_org = Organization(name='Foo Bar', financial_classification='', coverage_scope='', coverage_focus='', platform='', employee_range='', budget='', affiliations='') db.session.add(existing_org) existing_user = AppUser(name='Foo', email='*****@*****.**', email_hash='f3ada405ce890b6f8204094deb12d8a8', approved=True, orgs=[existing_org]) db.session.add(existing_user) db.session.commit() userform = ImmutableMultiDict([('name', 'bar'), ('email', '*****@*****.**'), ('news_org', 'foo bar')]) response = client.post('/validate-basic-info', data=userform) user = AppUser.query.filter_by(email='*****@*****.**').first() assert user.name == 'Bar' assert len(user.orgs) == 1 assert user.orgs[0].name == 'Foo Bar' assert response.get_json()['user'] == 'approved' assert ('Suppressing an email with the following params: ' 'Sender: [email protected]. Recipients: [\'[email protected]\']. ' 'Subject: You\'re all set to access our benchmarks!' in caplog.text)
def post(self): parser = reqparse.RequestParser() parser.add_argument('id', required=True, type=str) parser.add_argument('password', required=True, type=str) parser.add_argument('nickname', required=True, type=str) args = parser.parse_args() form = RegisterForm(ImmutableMultiDict(args)) if form.validate(): count = User.query.filter((User.id == form.id.data) | (User.nickname == form.nickname.data)).count() if count > 0: return {"message": "이미 존재하는 ID나 별명입니다."}, 409 hashedPassword = bcrypt.hashpw(form.password.data.encode('UTF-8'), bcrypt.gensalt()).decode('UTF-8') newUser = User(id=form.id.data, password=hashedPassword, nickname=form.nickname.data) db.session.add(newUser) db.session.commit() return {"data": { "id": newUser.id, "nickname": newUser.nickname } }, 201 else: return {"message": "파라미터 값이 유효하지 않습니다."}, 400
def test_record_day(self): # create user self.app.post('/register', data=self.user_dict()) # login user self.app.post('/login', data=dict(email=self.user_dict()['email'], password=self.user_dict()['password'])) #add new habit self.app.post('/add_habit', data=dict(habit_name='habit1')) #log habit date = datetime.datetime(year=2019, month=1, day=1) user = User.query.filter_by(email='*****@*****.**').first() habit = Habit.query.filter_by(user_id=user.id).first() data = ImmutableMultiDict([(f'{habit.id}', f'{habit.id}')]) rv = self.app.post(f'/day/2019/1/1', data=dict([("1", "1")])) day_info = Day.query.filter_by(user_id=user.id, habit_id=habit.id, date=date).first() assert day_info.habit_complete == True assert day_info.day_desc == 'testing'
def styles(): """ render a form in which they can render stylesheets """ user_css = op.join(current_app.root_path, 'static/scss/user_styles.css') css_data = ImmutableMultiDict(dict(css=open(user_css).read())) form = EditStylesForm(css_data) if form.validate_on_submit(): with open(user_styles, mode="w") as f: f.write(form.css.data) return render_template('admin/styles.html', form=form)
def test_add_stripper(self): app = Flask(__name__) with app.test_request_context('/'): request.form = ImmutableMultiDict([('auth', passwd)]) cnt = del_line(self.song, self.artist) self.assertEqual( add_stripper, f"Added stripper for {self.song} by {self.artist} to server database " f"successfully, deleted {cnt} instances from unsupported.txt")
def test_book_update(self): '''should be able to edit an book and redirect to book index''' with self.client: response = self.client.patch( '/authors/2/books/1', data=ImmutableMultiDict([('tags', '2'), ('title', "Brand New Title")]), follow_redirects=True ) self.assertEqual(response.status_code, 200) self.assertIn(b'Brand New Title', response.data) self.assertNotIn(b'Night of the Living Decorator', response.data)
def fillPasswordChangeForm(self, current_password, password1, password2): """ helper to fill UserSettingsPasswordForm form """ FormClass = views.UserSettingsPasswordForm request_form = ImmutableMultiDict([ ('usersettings_password_password_current', current_password), ('usersettings_password_password1', password1), ('usersettings_password_password2', password2), ('usersettings_password_submit', u'Save') ]) form = FormClass.from_flat(request_form) return form
def test_book_update_tags(self): '''BONUS: should be able to edit a book's associated tags''' with self.client: self.client.patch( '/authors/2/books/1', data=ImmutableMultiDict([('tags', '3'), ('title', 'Night of the Living Decorator')]), follow_redirects=True ) response = self.client.get('/authors/2/books/1') self.assertIn(b'Biography', response.data) self.assertNotIn(b'Sci Fi', response.data) self.assertNotIn(b'Horror', response.data)
def test_book_create_tags(self): '''BONUS: should be able to add tags to a book upon creation''' with self.client: self.client.post( '/authors/2/books', data=ImmutableMultiDict([('tags', '1'), ('tags', '2'), ('title', 'Cool cool cool')]), follow_redirects=True ) response = self.client.get('authors/2/books/3') self.assertIn(b'Cool cool cool', response.data) self.assertIn(b'Sci Fi', response.data) self.assertIn(b'Horror', response.data) self.assertNotIn(b'Biography', response.data)
def test_failing_to_select_one_to_keep(self, test_app_client, logged_in_admin_user): DataSourceFactory.create() data_source_1 = DataSourceFactory.create(title="Police Statistics 2019") data_source_2 = DataSourceFactory.create(title="Police Stats 2019") response = test_app_client.post( self.__path_with_data_source_ids(data_source_ids=[data_source_1.id, data_source_2.id]), data=ImmutableMultiDict((("ids", data_source_1.id), ("ids", data_source_2.id))), follow_redirects=False, ) assert response.status_code == 200
def __init__(self, model: db.Model, arguments: ImmutableMultiDict, fields=List[str]) -> None: # Database table self._model: db.Model = model # Column mapper for validation and column access self._column_mapper = self._model.__mapper__.columns # List of all valid columns for filtering and sorting self._valid_columns = fields # Request query arguments self._arguments: dict = arguments.to_dict() # Parse request arguments self._parse_arguments() # Validate request arguments self._validate_arguments() # Prepare base query self._query = db.session.query(self._model)
def login(nickname=None, password=None, login_method=None, action='', remember=False, referer=None): """Login.""" if cfg.get('CFG_ACCESS_CONTROL_LEVEL_SITE') > 0: return abort(401) # page is not authorized if action: from invenio.modules.access.mailcookie import \ InvenioWebAccessMailCookieError, \ mail_cookie_check_authorize_action try: action, arguments = mail_cookie_check_authorize_action(action) except InvenioWebAccessMailCookieError: pass form = LoginForm(CombinedMultiDict([ ImmutableMultiDict({ 'referer': referer, 'login_method': 'Local' } if referer else {'login_method': 'Local'}), request.values ]), csrf_enabled=False) if request.method == "POST": try: if login_method == 'Local' and form.validate_on_submit() and \ authenticate(nickname, password, login_method=login_method, remember=remember): flash(_("You are logged in as %(nick)s.", nick=nickname), "success") return login_redirect(referer) else: flash(_("Invalid credentials."), "error") except Exception as e: current_app.logger.error('Exception during login process: %s', str(e)) flash(_("Problem with login."), "error") return render_template('accounts/login.html', form=form), 401
def prepare_message(msgForm): msg = Message(msgForm) # Inject user-defined variables into the initial text, by parsing its # textBody for tokens prefixced with '#' if msg.textBody: newFormItems = [] for key, val in msgForm.to_dict().items(): if key == 'textBody': # inject our variables into it. if '#' in val: newTextBody = inject_user_structures(val) newFormItems.append((key, newTextBody)) continue newFormItems.append((key, val)) msgForm = ImmutableMultiDict(newFormItems) return msgForm
def test_store_new_user(client): """End-to-end test of submitting the /validate-basic-info route with a new user and an existing organization.""" existing_org = Organization(name='Foo Bar', financial_classification='', coverage_scope='', coverage_focus='', platform='', employee_range='', budget='', affiliations='') db.session.add(existing_org) db.session.commit() userform = ImmutableMultiDict([('name', 'foo'), ('email', '*****@*****.**'), ('news_org', 'foo bar')]) response = client.post('/validate-basic-info', data=userform) user = AppUser.query.filter_by(email='*****@*****.**').first() assert user.name == 'Foo' assert len(user.orgs) == 1 assert existing_org in user.orgs assert response.get_json()['user'] == 'other'
def test_merging_two_data_sources(self, test_app_client, logged_in_admin_user): DataSourceFactory.create() data_source_1 = DataSourceFactory.create(title="Police Statistics 2019") data_source_2 = DataSourceFactory.create(title="Police Stats 2019") response = test_app_client.post( self.__path_with_data_source_ids(data_source_ids=[data_source_1.id, data_source_2.id]), data=ImmutableMultiDict((("ids", data_source_1.id), ("ids", data_source_2.id), ("keep", data_source_1.id))), follow_redirects=False, ) assert response.status_code == 302 assert response.location == url_for("admin.data_sources", _external=True) # Now follow the redirect response_2 = test_app_client.get(response.location) assert response_2.status_code == 200 page = BeautifulSoup(response_2.data.decode("utf-8"), "html.parser") assert "Police Statistics 2019" in page.find("main").text assert "Police Stats 2019" not in page.find("main").text
def process_reply(): # Main route for processing requests. Based on information we detect in the # flask.request.form (logic provided in models.py), we can figure out if # we are sending the response back to Signal, iMessage, and from there-- # a group, or an individual. Cool, huh? if app.config['DEBUG']: print('Old form:') pprint(flask.request.form) # flask.request.form'textBody'] = flask.request.form['textBody'].upper() command = check_command(flask.request.form) if not command: # User isn't talking to Sue. Ignore. return '' # message metadata will be used to direct response output. msg = Message._create_message(flask.request.form) # parse message textBody to see if we need to inject any user-defined # variables into it. if msg.textBody: newFormItems = [] for key, val in flask.request.form.to_dict().items(): if key == 'textBody': # inject our variables into it. if '#' in val: newTextBody = inject_user_structures(val) newFormItems.append((key, newTextBody)) continue newFormItems.append((key, val)) flask.request.form = ImmutableMultiDict(newFormItems) print(flask.request.form) # get a list of our available functions sue_funcs = {} for r in app.url_map.iter_rules(): sue_funcs[r.rule] = app.view_functions[r.endpoint] f = sue_funcs.get('/' + command) if f: # Command exists. Execute it and get the response. sue_response = f() else: # It's not a command we made. Check to see if it is user defined. sue_response = sue_funcs['/callDefn']() # cast her response to a string. (ex: lists are reduced). attachment = None if isinstance(sue_response, list): sue_response = reduce_output(sue_response, delimiter='\n') elif isinstance(sue_response, DataResponse): # set the attachment to our image path attachment = sue_response.data # set the sue_response to a blank string (we won't send it anyway) sue_response = '' elif not isinstance(sue_response, str): try: sue_response = str(sue_response) except: sue_response = "Couldn't convert from {0} to str".format( type(sue_response)) # TODO: Create consts for these, so we have less `magic string` usage. if msg.platform is 'imessage': # forward to applescript handler Response(msg, sue_response, attachment=attachment) return 'success' elif msg.platform is 'signal': # return to GET request from run_signal.py return sue_response elif msg.platform is 'debug': return 'SUE :\n{0}'.format(sue_response) else: print('Unfamiliar message platform: {0}'.format(msg.platform)) return 'failure'