def RxFx_effectiveness(): # Renders RxFx.html. conn = get_db() # returns connection object indication = '' # GET LIST OF INDICATIONS query_string = ''' SELECT indication, indication_single_term FROM top_indications''' indication_list = pd.io.sql.frame_query(query_string, conn).sort('indication') indications = list(indication_list['indication']) indication_single_term = "" if request.method=='GET': return render_template('RxFx_effectiveness.html', indication="ANXIETY", indications=indications, indication_single_term=indication_single_term) elif request.method=='POST': # HANDLE PROCESSING INFORMATION indication = request.form['indication'] indication_single_term = str(indications_dict[indication]) file_name = "images/" + indication_single_term + ".jpg" app.test_request_context() return render_template('RxFx_effectiveness.html', indication=indication, indications=indications, indication_single_term=indication_single_term) return render_template('RxFx_effectiveness.html', indication=indication, indications=indications, indication_single_term=indication_single_term)
def setUp(self): # Load testing configuration app.config.from_object('config.TestingConfig') self.app = app.test_client() # Initialize the request context app.test_request_context().push()
def test_index_page(self): app = flask.Flask(__name__) with app.test_request_context('/'): assert flask.request.path == '/' assert flask.request.method == 'GET' with app.test_request_context('/index'): assert flask.request.path == '/index' assert flask.request.method == 'GET'
def test_middleware_save_requests(self): client = app.test_client() with app.test_request_context('/'): response = client.get(url_for('request_to_app')) self.assertEqual(response.status_code, 200) with app.test_request_context('/'): response = client.get(url_for('table')) self.assertEqual(response.status_code, 200)
def setUp(self): app.config.from_object('config.TestingConfig') self.app = app.test_client() db.create_all() # Initialize the request context app.test_request_context().push() self.setUpInitialData()
def test_buildjson(): """Test that the buildjson method works correctly. This is not really a unit test, should I maybe monkey patch the constructor?""" with app.test_request_context('/?eq=^^^&xmin=-10&xmax=10&dim=1'): assert "\"errcode\": 0" in buildjson(pl.OneDeePlot).data with app.test_request_context('/?eq=log(x)&xmin=-10&xmax=10&dim=1'): assert "\"errcode\": 1" in buildjson(pl.OneDeePlot).data with app.test_request_context('/?eq=cos(x)&xmin=-10&xmax=10&dim=1'): assert "\"xmin\": -10" in buildjson(pl.OneDeePlot).data
def test_html_widget(self): client = app.test_client() with app.test_request_context('/'): response = client.get(url_for('add_note')) assert response.status_code == 200, u'Status code is not 200' assert '<script type="text/javascript" src=' in response.data with app.test_request_context('/'): response = client.get(url_for('widget')) self.assertEqual(response.status_code, 200) assert len(response.data) >= 0, u'Widget page is empty'
def test_requests_page_return_only_10_records(self): client = app.test_client() for i in range(0, 20): with app.test_request_context('/'): response = client.get(url_for('request_to_app')) self.assertEqual(response.status_code, 200) with app.test_request_context('/'): response = client.get(url_for('table')) self.assertEqual(response.status_code, 200) count = response.data.count('/requests', 0, len(response.data)) self.assertEqual(count, 10)
def test_ajax_form(self): client = app.test_client() with app.test_request_context('/'): response1 = client.get(url_for('list_notes')) assert 'No notes in database' in response1.data with app.test_request_context('/'): response2 = client.get(url_for('ajax_form')) assert response2.status_code is 200 with app.test_request_context('/'): post = client.post(url_for('ajax_add'), data={'note': 'Some note #1'}) # noqa self.assertEqual(post.status_code, 200) with app.test_request_context('/'): response3 = client.get(url_for('list_notes')) assert 'Some note #1' in response3.data
def test_add_note_with_image(self): client = app.test_client() with app.test_request_context('/'): response1 = client.get(url_for('list_notes')) assert 'No notes in database' in response1.data with app.test_request_context('/'): post = client.post(url_for('add_note'), data=dict(new_note='Some note #1', image=(io.BytesIO(b'this is a test'), 'test.jpeg')), follow_redirects=True) # noqa # post = self.app.post('/add-note/', data=dict(new_note='Some note #1', image=(io.BytesIO(b'this is a test'), 'test.jpeg')), follow_redirects=True) # noqa self.assertEqual(post.status_code, 200) with app.test_request_context('/'): response = client.get(url_for('list_notes')) self.assertTrue('Some note #1' in response.data) self.assertTrue('<img src="/static/uploads/test.jpeg"/>' in response.data) # noqa
def on_current_request(self): current, playlist = get_playlist() current = Song.query.filter_by(id=current).first() sketchy_ctx = app.test_request_context() sketchy_ctx.push() self.emit('current_data', render_template('current_bar.html', current=current, played=music.get_time())) sketchy_ctx.pop()
def shell(): """Start an interactive iPython shell""" from IPython.terminal.ipapp import TerminalIPythonApp import app.model as m from trex.support import quantum context = dict( app = app, quantum = quantum, m = m, ) rc_file = os.path.normpath(os.path.join(app.root_path, os.pardir, 'shell.rc')) if os.access(rc_file, os.R_OK): execfile(rc_file, context, dict(context=context)) shell = TerminalIPythonApp.instance( display_banner = False, quick = True, user_ns = context, ) shell.initialize(argv=[]) shell.shell.confirm_exit = False context = app.test_request_context('__shell__') context.push() shell.start() context.pop()
def main(test=False): """Start tornado running hactar.""" conf = load(open('config.json', 'rb'))['production'] if test: config_app(app) else: secrets = load(open(conf['SECRETS'], 'rb')) conf['USERNAME'] = secrets['hactar']['username'] conf['PASSWORD'] = secrets['hactar']['password'] conf['SECRET_KEY'] = secrets['installed']['client_secret'] app.config.update(conf) setup('production') logpath = os.path.join(conf['LOG_DIR'], conf['LOG_MAIN']) handler = logging.handlers.RotatingFileHandler(logpath, maxBytes=100000, backupCount=4) fmtr = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') handler.setFormatter(fmtr) logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(handler) with app.app_context(): db.init_app(app) if not os.path.exists(conf['SQLALCHEMY_DATABASE_URI'].lstrip('sqlite:///')): with app.test_request_context(): db.create_all() app.celery_running = True app.logger.debug('starting app with config: %s' % app.config) http_server = HTTPServer(WSGIContainer(app)) http_server.listen(8080) IOLoop.instance().start()
def cache_worker(feed_id): with app.test_request_context('/'): if feed_id is not None: app.cache.delete(feed_id=feed_id) app.view_functions['feed_view'](feed_id=feed_id, bot_flag=True) app.cache.delete('/') app.view_functions['index']()
def createUser(self, username, password): """Helper method for creating a user in the database. Returns: 0 -> if user was successfully created 1 -> if server reply was SUCCESS:False 2 -> if there was an error communicating with the server (i.e. unparsable JSON or otherwise invalid response) """ dataTest = dict() dataTest['uname'] = username dataTest['pw'] = password dataTest['email'] = '*****@*****.**' # to satisfy required field dataString = json.dumps(dataTest) with app.test_request_context('/createUser', method='POST'): r = self.appTest.post('/createUser', headers={'content-type':'application/json'}, data=dataString) try: j = json.loads(r.data) if j['SUCCESS'] == True: j['result'] = 0 return j j['result'] = 1 return j except ValueError as e: print 'Returned value could not be parsed as a JSON object' return {'result':2}
def createQueue(self, qname): #pdb.set_trace() """Helper method for creating a queue in the database. Returns: 0 -> if queue was successfully created 1 -> if server reply was SUCCESS:False 2 -> if there was an error communicating with the server (i.e. unparsable JSON or otherwise invalid response) """ dataTest = dict() dataTest['qname'] = qname dataString = json.dumps(dataTest) with app.test_request_context('/createQueue', method='POST'): r = self.appTest.post('/createQueue', headers={'content-type':'application/json'}, data=dataString) try: j = json.loads(r.data) if j['SUCCESS'] == True: j['result'] = 0 return j j['result'] = 1 return j except ValueError as e: print 'Returned value could not be parsed as a JSON object' return {'result':2}
def test_logout(self): with app.test_request_context(), app.test_client() as client: login_user(self.user) response = client.get("/user/logout/") self.assertEqual(response.status_code, 200) self.assertFalse(current_user.is_authenticated)
def shell(): """Start an interactive iPython shell""" from IPython.terminal.ipapp import TerminalIPythonApp import app.model as m from trex.support import quantum context = dict( app = app, quantum = quantum, m = m, ) rc_file = os.path.normpath(os.path.join(app.root_path, os.pardir, 'shell.rc')) if os.access(rc_file, os.R_OK): execfile(rc_file, context, dict(context=context)) shell = TerminalIPythonApp.instance( display_banner = False, quick = True, user_ns = context, ) shell.initialize(argv=[]) shell.shell.confirm_exit = False def pretty_print(self, arg): from pprint import pformat import mongoengine import texttable output = None for line in self.shell.history_manager.get_tail(50): try: output = self.shell.history_manager.output_hist[line[1]] except KeyError: pass if isinstance(output, mongoengine.QuerySet): table = texttable.Texttable(max_width=0) table.set_deco(texttable.Texttable.HEADER) fields = output[0]._fields.keys() table.add_row(fields) for obj in output: table.add_row([str(getattr(obj, field)) for field in fields]) pretty_output = table.draw() elif isinstance(output, mongoengine.Document) or isinstance(output, mongoengine.EmbeddedDocument): pretty_output = pformat(output.to_mongo().to_dict()) else: pretty_output = pformat(output) print pretty_output return None shell.shell.define_magic('pp', pretty_print) context = app.test_request_context('__shell__') context.push() shell.start() context.pop()
def test_login_user_not_found(self): data = {"email": "*****@*****.**", "password": "******"} with app.test_request_context(), app.test_client() as client: response = client.get("/user/login/", data=data) self.assertEqual(response.status_code, 401) self.assertFalse(current_user.is_authenticated)
def test_returns_current_user(self): u = User(name='Numpy', google_id='12345', email='*****@*****.**') u.save() with app.test_request_context(): session['user_id'] = '12345' c_user = current_user() self.assertEqual(c_user, u)
def removeFromQueue(self, qid, uname): """Helper method for removing someone from a queue as the currently logged-in user (must be an admin or manager of queue) Returns: 0 -> if user successfully was removed from queue 1 -> if server reply was SUCCESS:False 2 -> if there was an error communicating with the server (i.e. unparsable JSON or otherwise invalid response) """ dataTest = dict() dataTest['qid'] = qid with app.test_request_context('/remove', method='POST'): dataTest['uid'] = database_utilities.get_user_by_uname(uname)['id'] dataString = json.dumps(dataTest) r = self.appTest.post('/remove', headers={'content-type':'application/json'}, data=dataString) try: j = json.loads(r.data) if j['SUCCESS'] == True: j['result'] = 0 return j j['result'] = 1 return j except ValueError as e: print 'Returned value could not be parsed as a JSON object' return {'result':2}
def on_song_request(self, pk): """Returns the html for a song, ready to go into a playlist""" song = Song.query.filter_by(id=pk).first() sketchy_ctx = app.test_request_context() sketchy_ctx.push() self.emit('song_data', render_template('music_bar.html', song=song)) sketchy_ctx.pop()
def login(self, username, password): """Helper method for logging in a user. Returns: 0 -> if user was successfully logged in 1 -> if username/password combination was incorrect 2 -> if there was an error communicating with the server (i.e. unparsable JSON or otherwise invalid response) """ dataTest = dict() dataTest['uname'] = username dataTest['pw'] = password dataString = json.dumps(dataTest) with app.test_request_context('/login', method='POST'): r = self.appTest.post('/login', headers={'content-type':'application/json'}, data=dataString) try: j = json.loads(r.data) if j['SUCCESS'] == True: j['result'] = 0 return j j['result'] = 1 return j except ValueError as e: print 'Returned value could not be parsed as a JSON object' return {'result':2}
def test_login_success(self): data = {"email": self.user.email, "password": '******'} with app.test_request_context(), app.test_client() as client: response = client.get('/user/login/', data=data) self.assertEquals(response.status_code, 200) self.assertTrue(current_user.is_authenticated)
def retrieve_page(url, add_if_not_found=True): print "retrieving Page for ....%s" % (url) with app.test_request_context('/'): # this is to adjust for the fact that we are in celery content and not Flask context app.preprocess_request() if Page.get_total_num_of_pages() > app.config['MAX_CORPUS_SIZE']: ### now we need to stop crawling # celery.control.broadcast('shutdown') # Earlier I had this, but this shuts down celery, it stops Page population # But also stops Extraction population. But there has to be a one-t-one between pages and extractions # Therefore, we just stop consuming from "retrieve" queue. This is the queue to which # app.tasks.retrieve_page is configured to. Rest are on a different queue. Therefore, # other dependent tasks go through celery.control.cancel_consumer("retrieve") #celery.control.add_consumer("retrieve") # We will have to issue this before retrieve_page task is called. return page = Page.get_page_by_url(url) if page is None: if add_if_not_found: # add a page page = Page.add_page(url) else: # just return return pagenotfound() else: pass # do nothing retrieve_extraction.delay(page.id) find_links.delay(page.id) #retrieve_extraction.delay(page.id) # The reason this was commented was because boilerpipe_extract_and_populate task was getting overwhelmed # because the page population was growing so fast. # New approach: First populate 1000 pages. The stop page population and start the extraction process #Using Rest API ''''r = requests.get("http://127.0.0.1:5000/pages", params={"url":url})
def test_login_wrong_password(self): data = {"email": self.user.email, "password": "******"} with app.test_request_context(), app.test_client() as client: response = client.get("/user/login/", data=data) self.assertEqual(response.status_code, 401) self.assertFalse(current_user.is_authenticated)
def testNotExistingItem(self): item = Item('a') item.id = 310 with app.test_request_context(): response = app.test_client().get(item.url) response_dict = json.loads(response.data) assert 'error' in response_dict
def find_links(page_id): with app.test_request_context('/'): # this is to adjust for the fact that we are in celery content and not Flask context app.preprocess_request() page = Page.find_links(page_id) if page is None: return pagenotfound() for link in page.links: retrieve_page.delay(link)
def cron_sync(): print 'start cron_sync ...' with app.test_request_context(): users = User.query.all() for user in users: print user # make sure not conflict if get_user_last_activity(user.id) is not None: continue resp = client.metadata(user.vdisk_token, '/idesktop') if isinstance(resp, str): print 'error in metadata' continue result = json.loads(resp.read()) if result['hash'] == user.vdisk_hash: print 'same hash' continue user.vdisk_hash = result['hash'] db.session.add(user) db.session.commit() contents = [content for content in result['contents'] if is_good(content)] for content in contents: #print content['md5'] pic = Picture.query.filter_by(hash_id=content['md5']).first() if not pic: # need to upload #upload to upyun ret = client.media(user.vdisk_token, content['path']) if isinstance(ret, str): continue url = json.loads(ret.read())['url'] filename = content['md5'] filename += '.' + content['path'].split('.')[-1] low_q.enqueue(down_upload, url, filename) # add to db filename = content['path'].split('/')[-1] picture = Picture(filename, content['md5']) picture.in_yun = True picture.user = user picture.users.append(user) db.session.add(picture) db.session.commit() #print filename + '#' + url elif user not in pic.users: pic.users.append(user) db.session.add(pic) db.session.commit() #handle self delete in local folder hashs = [content['md5'] for content in contents] for pic in user.downloads.all(): if pic.hash_id not in hashs: #need delete pic.users.remove(user) db.session.add(pic) db.session.commit() print 'stop cron_sync ...' ret = {'result':'ok'} return jsonify(**ret)
def test_doubleLogin(client): with app.test_request_context(): login(client, 'user', 'user') response = client.get('/login') var = response.data assert b'' in response.data #all tests are dogshit good job emile, never stores shit
def test_server_error(self): with app.test_request_context(): resp = server_error('') data = json.loads(resp.get_data(as_text=True)) self.assertEqual(500, resp.status_code) self.assertEqual('application/json', resp.content_type) self.assertEqual({'error': 'Internal Server Error'}, data)
def test_app(test_db): app.config['TESTING'] = True app.response_class = CustomResponse with app.test_client() as client: ctx = app.test_request_context() ctx.push() yield client ctx.pop()
def pairSuccess(id): try: print("broadcasting pairing") statusReply = jsonFormat({"station_id": int(id)}, "") with app.test_request_context('/'): socketio.emit('pairing', statusReply, broadcast=True, namespace='/station') except Exception as e: print(redBright(e))
def test_query_1(self): """ Test querying the db by attribute using simple keywords - no entries """ with app.test_request_context(): agency_none = db.session.query( Agency).filter_by(name="not here").first() self.assertTrue(agency_none is None)
def test_get_cookie_data(self): with app.test_request_context('/'): # cookies for high score and number of plays do not exist, but # we can at least check that the dictionary returned has 0 for # number of plays and high score. self.assertEqual(0, get_cookie_data()["nbr_of_plays"]) self.assertEqual(0, get_cookie_data()["score_high"])
def test_proxy_url(self): with app.test_request_context('/'): resp = Response.get_or_create('abc', 'xyz') self.assertIsNone(resp.proxy_url()) resp.source_as2 = 'as2' self.assertEqual('http://localhost/render?source=abc&target=xyz', resp.proxy_url())
def test_agency_model_link_query_1(self): """ Test agency link to launches via db """ with app.test_request_context(): agency1 = db.session.query(Agency).filter_by(name="SpaceX").first() launch1 = agency1.launches[0] self.assertEqual(launch1.rocket, "Saturn V")
def test_location_model_link_1(self): """ Test location link to launches via db """ with app.test_request_context(): location1 = db.session.query(Location).first() launch1 = location1.launches[0] self.assertEqual(launch1.rocket, "Long March 2F")
def test_location_model_query_1(self): """ Test querying the db by attribute using simple keywords - location """ with app.test_request_context(): location1 = db.session.query(Location).first() self.assertEqual( location1.name, "Jiuquan, People's Republic of China")
def test_fileystem_signed_url(): client = clients.FilesystemStore() url = 'file://test_fileystem_signed_url.txt' stream = io.BytesIO(b'test: test_gcs_get_signed_url') client.put(url, stream) with app.test_request_context('http://www.example.com/rest/of/the/route'): assert client.get_signed_url(url) == \ f'http://www.example.com/data/download?url={url}'
def test_mission_model_query_1(self): """ Test querying the db by attribute using simple keywords - mission """ with app.test_request_context(): mission1 = db.session.query(Mission).first() self.assertEqual( mission1.name, "Nuclear Spectroscopic Telescope Array (NuSTAR)")
def test_launch_model_link_query_2(self): """ Test launch link to mission """ with app.test_request_context(): launch1 = db.session.query(Launch).first() mission1 = launch1.mission self.assertEqual(mission1.name, "Vostok 1")
def createsuperuser(display_name, email, password): """Create a superuser""" u = models.User(display_name=display_name, email=email, is_admin=True) u.set_password(password) db.session.add(u) db.session.commit() with app.test_request_context("/"): reverify()
def test_check_permissions_no_study_permission(self): self.setup(researcher=True, apikey=True, study=True) StudyRelation.objects.filter(study=self.study, researcher=self.researcher).delete() with self.assertRaises(PermissionDenied) as cm: with app.test_request_context(headers=self.default_header): TableauApiView().check_permissions( study_id=self.study.object_id)
def updateStatus(bin, station): try: statusReply = jsonFormat({"station_id": int(station), "bins": bin}, "") with app.test_request_context('/'): socketio.emit("status", statusReply, broadcast=True, namespace='/station') print("replied with status") except: print(redBright("Socket Status Error"))
def test_redirect_to_survey_monkey_with_guid(self): with app.test_request_context(): url = flask.url_for( "{0}.redirect_to_survey_monkey_with_guid".format( blueprint_name), hub="sandbox") response = app.test_client().get(url) self.assertEqual(response.status_code, 200)
def app(): from app import app as app_ ctx = app_.test_request_context() ctx.push() yield app_ ctx.pop()
def test_check_permissions_no_tableau(self): self.setup(researcher=True, apikey=True, study=True) ApiKey.objects.filter(access_key_id=self.api_key_public).update( has_tableau_api_permissions=False) with self.assertRaises(PermissionDenied) as cm: with app.test_request_context(headers=self.default_header): TableauApiView().check_permissions( study_id=self.study.object_id)
def test_hook(self): with app4.test_request_context("/"): app4.preprocess_request() local = LocalStorage() self.assertTrue("nowtime" in local.list) nowhour = time.strftime("%Y-%m-%d %H:", time.localtime(time.time())) self.assertIn(nowhour, local.get("nowtime")) del local["nowtime"]
def test_is_valid_user(self, user_1, user_2) -> None: with app.test_request_context(): form = LoginForm() form.email.data = '*****@*****.**' form.password.data = 'testPassword' assert u.is_valid_user(user_1, form) assert not u.is_valid_user(user_2, form) assert not u.is_valid_user(None, form)
def test_check_rate_request_is_required(self): url = '/?destination=NOGJM&date_from=2016-01-01&date_to=2016-01-30' with app.test_request_context(url): app.preprocess_request() try: check_rate_request() assert False except UnprocessableEntity as e: assert e.description.lower() == "origin is required"
def test_check_rate_request_success(self): url = '/?origin=CNNBO&destination=NOGJM&date_from=2016-01-01&date_to=2016-01-30' with app.test_request_context(url): app.preprocess_request() origin, destination, date_from, date_to = check_rate_request() assert origin == "CNNBO" assert destination == "NOGJM" assert date_from == "2016-01-01" assert date_to == "2016-01-30"
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 setUp(self): app.config.update(TESTING=True, SQLALCHEMY_DATABASE_URI='sqlite:///:memory:') self.context = app.test_request_context() self.context.push() self.client = app.test_client() self.runner = app.test_cli_runner() db.create_all()
def test_login_positive(self): with app.test_request_context(): try: user_registration.register_new_user("firstname2", "lastname2", "*****@*****.**", "username2", "password2") log_in.log_in("*****@*****.**", "password2") except Exception: self.fail("Login test failed")
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False self.client = app.test_client() # Application context self.ctx = app.test_request_context() self.ctx.push()
def test_mission_model_link_query_2(self): """ Test mission link to launch_id via db """ with app.test_request_context(): mission1 = db.session.query(Mission).filter_by( name="WGS-4 (USA-233)").first() launch_id1 = mission1.launch_id self.assertEqual(launch_id1, 485)
def setUp(self): self.context = app.test_request_context() self.context.push() self.client = app.test_client() self.runner = app.test_cli_runner() db.drop_all() db.create_all() print('-' * 50) print('\n' * 5)
def test_token_required(mocker, test_id, headers, expected): with app.test_request_context(headers=headers): mock_func = mocker.Mock() decorated_func = token_required(mock_func) resp = decorated_func() if test_id == 1: mock_func.assert_called_with(1) else: assert resp.json == expected
def test_follow_user_negative(self): with app.test_request_context(): user_registration.register_new_user("firstname3", "lastname3", "*****@*****.**", "username3", "password3") log_in.log_in("*****@*****.**", "password3") with self.assertRaises(Exception): user_subscribing.follow_user("bleh2")