def setUp(self): self.app = tested_app.test_client() self.main = tested_app.app_context() with tested_app.app_context(): db.init_app(tested_app) # removes cyclic dependency?? db.create_all() db.session.commit()
def get_data(self, log_id: int, last_time: str, device_id: str, data_type: str = 'values') -> dict: """ Retrieves data from persistent storage for a specified device. Further filters may be applied through additional parameters. :param log_id: ID of the log item to retrieve. Is ignored if the last_time parameter is not None. :param last_time: The timestamp in format <YYYYmmddHHMMSSfff>. Data from before this time will be excluded from the response. If it's not None, the log_id parameter is ignored. :param device_id: device ID of the device :param data_type: defines the type of data to retrieve, defaults to 'values' :return: a dictionary with the data from persistent storage """ cls = Value if data_type == 'values' else Event if last_time is not None: from main import app with app.app_context(): return self._post_process( cls.query.filter_by(dev_id=device_id).filter( cls.time > last_time).all(), data_type, device_id) else: if log_id is None: log_id = self.last_seen_id[data_type].get(device_id, 0) from main import app with app.app_context(): return self._post_process( cls.query.filter_by(dev_id=device_id).filter( cls.id > log_id).all(), data_type, device_id)
def setUp(self): app1 = app self.test_db_file = tempfile.mkstemp()[1] app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + self.test_db_file with app.app_context(): db.create_all() app.app_context().push() self.app = app.test_client()
def setUp(self): self.app = tested_app.test_client() self.main = tested_app.app_context() with tested_app.app_context(): db.init_app(tested_app) # removes cyclic dependency?? db.create_all() db.session.add(User(username="******", email='*****@*****.**', password='******')) db.session.add(User(username="******", email='*****@*****.**', password='******')) db.session.commit()
def setUp(self): # Make sure database exists app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' with app.app_context(): db.init_app(app) db.create_all() # Get a test client self.app = app.test_client() self.app_context = app.app_context()
def setUp(self): self.app = tested_app.test_client() self.main = tested_app.app_context() with tested_app.app_context(): db.init_app(tested_app) # removes cyclic dependency?? db.create_all() db.session.add(Result(year=1994, type="birth", event="Alice")) db.session.add(Result(year=1995, type="death", event="Bob")) db.session.add( Result(year=1996, month=1, type="birth", event="John")) db.session.add( Result(year=1997, month=2, day=1, type="birth", event="Ann")) db.session.commit()
def session(): # Create app context app.app_context().push() # Create the database and the database table db.create_all() # Import mock data create_mock_data() yield app # In the next call drop all data in the databases drop_tables()
def configure(): imgur_id = request.form.get('imgur', None).encode('utf-8') disqus = request.form.get('disqus', None).encode('utf-8') github = request.form.get('github', None).strip().encode('utf-8') facebook = request.form.get('facebook', None).strip().encode('utf-8') twitter = request.form.get('twitter', None).strip().encode('utf-8') twitter_username = request.form.get('twitter-user', None).strip().encode('utf-8') google_plus = request.form.get('gplus', None).strip().encode('utf-8') email = request.form.get('email', None).strip().encode('utf-8') gallery = True if request.form.get('show-gallery') == 'on' else False projects = True if request.form.get('show-projects') == 'on' else False show_info = True if request.form.get('show-info') == 'on' else False to_update = dict() for key, val in locals().items(): if key in ConfigModel._meta.get_field_names(): to_update[key] = val try: config = ConfigModel.select().get() config.save_settings(**to_update) with app.app_context(): cache.clear() return redirect(url_for('account', username = session['user'])) except: handle_errors("Error when saving configuration") return redirect(url_for("account", username = session["user"]))
def after_all(context): context.browser.get(context.address + "/shutdown") # shut down flask app server context.thread.join() context.browser.quit() with app.app_context(): db.session.remove() db.drop_all()
def db(): from service import db with app.app_context(): db.create_all() yield db db.drop_all() db.session.commit()
def post(self): title = request.form.get("title").strip() body = request.form.get("body").strip() user = Users.get_user_by_username(session["user"]) context = dict(title = title, body = body, author = user) additional = self.get_context() context.update(additional) if not title or not body: error = "Entry can\'t have empty title or body" context.update(dict(error = error)) return self.render_template(context) model = self.get_model() check = model.check_exists(title) if check: error = "Entry with that title already exists, choose a new one.." context.update(dict(error = error)) return self.render_template(context) else: context.update(self.process_additional_fields()) try: func = getattr(model, self.create_method()) func(**context) with app.app_context(): cache.clear() flash("Created") return redirect(url_for("account", username = session["user"])) except Exception as e: logger.debug(e) error = "Processing error see error.log for details" context.update(dict(error = error)) return self.render_template(context)
def test_get_choropleth_configs(self): cc1 = { 'category': ['Test', 'Test1'], 'title': 'Test1', 'statsVars': ['StatVar1'], 'isOverview': True, } cc2 = { 'category': ['Test', 'Test2'], 'title': 'Test2', 'statsVars': ['StatVar2'], 'isChoropleth': False } cc3 = { 'category': ['Test', 'Test2'], 'title': 'Test2', 'statsVars': ['StatVar3'], 'isChoropleth': True } with app.app_context(): app.config['CHART_CONFIG'] = [cc1, cc2, cc3] expected_chart_configs = [cc3] actual_chart_configs = choropleth_api.get_choropleth_configs() assert expected_chart_configs == actual_chart_configs
def test_updateRoom_success(mocker, client): mock_authentication(mocker) mimetype = 'application/json' headers = {'Content-Type': mimetype, 'Accept': mimetype} mocker.patch.object(roomService, "updateRoom") roomService.updateRoom = updateRoomMock with app.app_context(): response = client.put(url_for('room.updateRoom', id=1), headers=headers, data=json.dumps( dict( name='X-wing', info='nice ship dude', seats=dict( count=0, seats=[], ), ))) assert "200 OK" == response.status assert make_response( jsonify( id=None, name='X-wing', info='nice ship dude', seats=dict( count=0, seats=[], ), )).data == response.data
def create_user(email, password): with app.app_context(): db = get_db() with db.cursor() as cursor: sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, (email, generate_password_hash(password))) db.commit()
def test_registerNewApplication(mocker, client): mock_authentication(mocker) mimetype = 'application/json' headers = { 'Content-Type': mimetype, 'Accept': mimetype, "AccessToken": f'Bearer {accessToken}' } mocker.patch.object(applicationService, "registerApplication") applicationService.registerApplication = registerApplicationMock with app.app_context(): response = client.post( url_for('application.registerApplication'), headers=headers, data=json.dumps(dict( username='******', needs='needs', comments='comments', partnerUsername='******', preferredRoom="d1", seatRollover=True, ))) assert "201 CREATED" == response.status assert json.loads(jsonify( comments='comments', needs='needs', user={"id": None, "username": "******", "email": "email", "fullname": "Schnep Schmep"}, id=None, status="SUBMITTED", preferredRoom="d1", seatRollover=True, partnerApplication={}, rank="WRITING_MASTER" ).data) == json.loads(response.data)
def load(path, class_to_load): with open(path) as f: data = loads(f.read()) with app.app_context(): for obj in data: db.db.session.add(class_to_load.load(obj)) db.db.session.commit()
def rdb(c): """ Reload database """ with app.app_context(): db.db.drop_all() db.db.create_all()
def _calculate_ranking(): from main import app with app.app_context(): from model import Project, Score_weight, db year = Project.query.with_entities(Project.year).group_by( Project.year).all() for y in year: y = y[0] projects = to_obj_list(Project.query.filter_by(year=y).all()) score_weight = to_obj_list( Score_weight.query.filter_by(year=y).all()) score_weight = list( map( lambda x: ({ str(x["score_classification_id"]): x["weight"] }), score_weight, )) score_weight = {k: v for d in score_weight for k, v in d.items()} score = list( map( lambda x: sum([(i["score"] * score_weight[str(i[ "score_classification_id"])]) for i in x["score"]]), projects, )) score = list(map(lambda x: max(score) - x, score)) rank = ss.rankdata(score, method="min") for i, r in enumerate(rank): Project.query.get(projects[i]["id"]).rank = r db.session.commit() print("Ranking complete")
def send_email(to, subject, template): msg = Message(subject, recipients=[to], html=template, sender=mail_settings['MAIL_USERNAME']) with app.app_context(): mail.send(msg)
def testCreateCorrect(self): with app.app_context(): content = {"groupName": "ttest", "groupDescription": "Group created via app", "vpcId": "vpc-038b29af8bdb5f634", "authorizeConfiguration": [ { "port": 80, "ipaddress": "0.0.0.0/0", "protocol": "TCP" }, { "port": 80, "ipaddress": "62.178.238.153/32", "protocol": "TCP" } ]} with app.test_client() as client: # send data as POST form to endpoint #sent = {'return_url': 'my_test_url'} result = client.post( '/securityGroup/', json=content ) self.assertTrue( result.data )
def test_deleteRoom(mocker, client): mock_authentication(mocker) mocker.patch.object(roomService, "deleteRoom") roomService.deleteRoom.return_value = "", 200 with app.app_context(): response = client.delete(url_for('room.deleteRoom', id=1)) assert "200 OK" == response.status
def init_db(): """Initializes the database.""" with app.app_context(): db = get_db() with app.open_resource('db/database.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
def test_search_statvar_single_token(self, mock_search_result): expected_query = 'person' expected_places = ["geoId/06"] expected_result = {'statVarGroups': ['group_1', 'group_2']} expected_blocklist_places = ["geoId/07"] expected_blocklist_result = {'statVarGroups': ['group_1']} def side_effect(query, places, enable_blocklist): if query == expected_query and places == expected_places and not enable_blocklist: return expected_result elif query == expected_query and places == expected_blocklist_places and enable_blocklist: return expected_blocklist_result else: return [] with app.app_context(): mock_search_result.side_effect = side_effect app.config['ENABLE_BLOCKLIST'] = False response = app.test_client().get( 'api/browser/statvar/search?query=person&places=geoId/06') assert response.status_code == 200 result = json.loads(response.data) assert result == expected_result app.config['ENABLE_BLOCKLIST'] = True response = app.test_client().get( 'api/browser/statvar/search?query=person&places=geoId/07') assert response.status_code == 200 result = json.loads(response.data) assert result == expected_blocklist_result
def before_all(context): app.config.from_object('config.TestingConfig') # context.client = app.test_client() context.server = main context.address = main.address context.thread = threading.Thread(target=context.server.serve_forever) context.thread.start() # start flask app server context.browser = webdriver.Firefox() db.init_app(app) with app.app_context(): # Extensions like Flask-SQLAlchemy now know what the "current" app # is while within this block. Therefore, you can now run........ db.create_all() user1 = User('Sathwik', 'Singari', '*****@*****.**', 'dm08b048') user1.set_user_farmer() db.session.add(user1) db.session.add(User('Bilbo', 'Baggins', '*****@*****.**', 'bilbobaggins')) db.session.add(Unit('Kg')) db.session.add(Unit('gm')) db.session.add(Unit('l')) db.session.add(Unit('ml')) db.session.flush() db.session.add(Address('123 Hill Rd', None, 'Sydney', 'NSW', 'Australia', 2010)) db.session.add(Address('126 Hill Rd', None, 'Sydney', 'NSW', 'Australia', 2010)) db.session.flush() db.session.add(Farm('Shire Farms', 1)) db.session.add(Farm('Mordor Farms', 2)) db.session.flush() db.session.add(Works(1, 1)) db.session.add(Works(1, 2)) db.session.flush() db.session.add(User('Joe', 'Farmer', '*****@*****.**', 'louise1993')) db.session.commit()
def populate_booking_data(self): with app.app_context(): booking = Booking() booking.userid = "1" booking.carid = "1" db.session.add(booking) db.session.commit()
def del_cache(key): with app.app_context(): try: cache_local.delete(key) return True except Exception as eee: logger.error('删除缓存失败:' + str(eee)) return False
def session(testapp): ctx = app.app_context() ctx.push() yield db_session #db_session.close_all() close_all_sessions() ctx.pop()
def test_get_teams2(self): with app.app_context(): result = Team.lookup('GB') self.assertEqual(result['team_name'], "Packers") self.assertEqual(result['venue_location'], 'Green Bay, WI') self.assertEqual(result['division'], 'NFC North') self.assertEqual(result['points_rank'], 34) self.assertEqual(result['season_wins'], 4)
def test_get_seasons1(self): with app.app_context(): result = Season.lookup('29') self.assertEqual(result['nfc_champion'], "ATL") self.assertEqual(result['year'], 2016) self.assertEqual(result['afc_champion'], 'NE') self.assertEqual(result['start_date'], '2016-09-08') self.assertEqual(result['end_date'], '2017-01-01')
def test_getCurrentSeason_without_a_season(mocker): mock_authentication(mocker) mocker.patch.object(applicationSeasonService, "getCurrentOrNext") applicationSeasonService.getCurrentOrNext.return_value = {} with app.app_context(): response = applicationSeasonController.getCurrentSeason() assert "200 OK" == response.status assert b'{}' == response.data
def test_getRoom_with_no_room(mocker): mock_authentication(mocker) mocker.patch.object(roomService, "getRoomById") roomService.getRoomById.return_value = {} with app.app_context(): response = roomController.getRoom(123) assert "200 OK" == response.status assert b'{}' == response.data
def test_get_seasons2(self): with app.app_context(): result = Season.lookup('28') self.assertEqual(result['nfc_champion'], "CAR") self.assertEqual(result['year'], 2015) self.assertEqual(result['afc_champion'], 'DEN') self.assertEqual(result['start_date'], '2015-09-10') self.assertEqual(result['end_date'], '2016-01-03')
def handle_user_events(self): if not self.user_handler.buffer: return from main import app from app.user.model import User with app.app_context(): User.update_user() self.user_handler.clear_buffer()
def testCreateWithOutBody(self): with app.app_context(): content = {"test": "test"} print(content) with app.test_client() as client: # send data as POST form to endpoint result = client.post('/keypair/', json=content) self.assertRaises(TypeError, result.data)
def publish_article(id): article = Articles.get_article(id) if not article: abort(404) if article.author.username != session["user"]: flash("You can\'t publish other\'s peoples posts") return redirect(url_for("index")) else: Articles.publish_article(article) with app.app_context(): cache.clear() flash("Article has been published") return redirect(url_for("account", username = session["user"]))
def before_all(context): app.config.from_object('config.TestingConfig') # context.client = app.test_client() context.server = main context.address = main.address context.thread = threading.Thread(target=context.server.serve_forever) context.thread.start() # start flask app server context.browser = webdriver.Firefox() db.init_app(app) with app.app_context(): # Extensions like Flask-SQLAlchemy now know what the "current" app # is while within this block. Therefore, you can now run........ db.create_all() db.session.add(User('Sathwik', 'Singari', '*****@*****.**', 'dm08b048')) db.session.add(User('Bilbo', 'Baggins', '*****@*****.**', 'bilbobaggins')) User.query.get(1).set_user_farmer() db.session.add(User('Billy', 'Bogan','*****@*****.**','password')) db.session.add(Unit('Kg')) db.session.add(Unit('gm')) db.session.add(Unit('l')) db.session.add(Unit('ml')) db.session.flush() db.session.add(Address('123 Hill Rd', None, 'Sydney', 'NSW', 'Australia', 2010)) db.session.add(Address('126 Hill Rd', None, 'Sydney', 'NSW', 'Australia', 2010)) db.session.add(Farm('Shire Farms', 1)) db.session.add(Farm('Mordor Farms', 2)) #db.session.add(Image('eggplant.jpg', 'produce/1/eggplant.jpeg')) #db.session.add(Produce('Eggplant', 'Sweet organic eggplants', 'Vegetable', 1, 1)) #db.session.add(Price(1, 1, 4.35)) #db.session.add(Price(1, 2, 2.8)) db.session.add(Produce('corn', 'vegetable', 'tasty', 1, 1)) db.session.add(Produce('milk', 'dairy', 'yum', 2, 2)) db.session.flush() db.session.add(Price(1, 1, 2.2)) db.session.add(Price(2, 1, 4.4)) db.session.add(RecentProduce(1, 1)) db.session.flush() db.session.add(Works(1, 1)) db.session.add(Works(1, 2)) db.session.add(Works(4,1)) db.session.flush() db.session.add(User('Joe', 'Farmer', '*****@*****.**', 'louise1993')) #db.session.add(Works(4, 1)) db.session.add(Field('west block', 'Shire Farms', 1)) db.session.add(Resource('fertiliser', 1)) db.session.commit()
def add_user(): with app.app_context(): username = raw_input("Username: "******"Nickname: ") password = raw_input("Password: "******"Permission: ") user = User() user.name = username user.nickname = nickname user.password = password user.permission = permission user.locked = False user.failed_times = 0 str = user.regenerate_otp_token() print str
def set_info(): user = Users.get_user_by_username(session['user']) real_name = request.form.get("real-name", None) description = request.form.get("description", None) user.real_name = real_name user.description = description try: user.save() except Exception as e: handle_errors("Error updating user info") abort(500) finally: with app.app_context(): cache.clear() return redirect(url_for('account', username = session['user']))
def before_all(context): app.config.from_object('config.TestingConfig') # context.client = app.test_client() context.server = main context.address = address context.thread = threading.Thread(target=context.server.serve_forever) context.thread.start() # start flask app server context.browser = webdriver.Firefox() context.address = address db.init_app(app) with app.app_context(): # Extensions like Flask-SQLAlchemy now know what the "current" app # is while within this block. Therefore, you can now run........ db.create_all() db.session.add(User('Sathwik', 'Singari', '*****@*****.**', 'dm08b048')) db.session.add(User('Bilbo', 'Baggins', '*****@*****.**', 'bilbobaggins')) db.session.commit()
def main(): parser = argparse.ArgumentParser(description="") parser.add_argument('-c', '--create-db', action='store_true', help='create database') parser.add_argument('-d', '--drop-db', action='store_true', help='drop database') parser.add_argument('-t', '--test-data', action='store_true', help='add test data') args = parser.parse_args() with app.app_context(): if args.drop_db: db.drop_all() if args.create_db: db.create_all() if args.test_data: add_test_data()
from main import app ctx = app.app_context() ctx.push() from main import db from models import Project for project in Project.query.all(): print str(project) ctx.pop()
def render_template(self, context = dict()): with app.app_context(): cache.clear() context.update(self.get_context()) return render_template(self.get_template_name(), **context)
# Get or create exam exam = models.Exam.query.filter_by(name=course_json['exam'], course=course).first() if not exam: exam = models.Exam(course_json['exam'], course.id) db.session.add(exam) db.session.commit() questions = course_json['questions'] for question in questions: image = question['image'] if 'image' in question else "" question_object = models.Question(question['question'], exam.id, image) db.session.add(question_object) db.session.commit() for number, answer in enumerate(question['answers']): if type(question['correct']) is int and question['correct'] == number: correct = True elif type(question['correct']) is list and number in question['correct']: correct = True else: correct = False # Setting image if it exists alternative = models.Alternative(answer, number, correct, question_object.id) db.session.add(alternative) db.session.commit() print("Importing completed") if __name__ == '__main__': print("Importing questions...") with app.app_context(): import_questions()
def setUp(self): self.db_fd, self.db_file = tempfile.mkstemp() app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + self.db_file self.app = app.test_client() with app.app_context(): database.init_db()
def logout(): if "user" in session: session.pop("user", None) with app.app_context(): cache.clear() return redirect(url_for("index"))