def app(): app = create_app(TestConfig()) with app.app_context(): db.drop_all() db.create_all() yield app
def client(): from backend.app import create_app, app app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" with create_app().test_client() as test_client: yield test_client
def wrap_io(fn: callable) -> (str, str): out = StringIO() err = StringIO() # noinspection PyBroadException try: with redirect_stderr(err): with redirect_stdout(out): with create_app().app_context(): print(f"Running {fn.__name__}") fn() # catch-all case for potential SystemExit(1) except BaseException: pass out = out.getvalue() err = err.getvalue() # print captured outputs sys.stdout.write(f"stdout: {out}") sys.stderr.write(f"stderr: {err}") # a cheap state caching trick, but does the job wrap_io._out = getattr(wrap_io, "_out", "") + out wrap_io._err = getattr(wrap_io, "_err", "") + err out, err = wrap_io._out, wrap_io._err return out, err
def test_client(): flask_app = create_app() flask_app.config["SECRET_KEY"] = "dev" flask_app.config[ "SQLALCHEMY_DATABASE_URI" ] = "postgresql+psycopg2://postgres:password@localhost/test_db" flask_app.config["TESTING"] = True flask_app.config["JWT_SECRET_KEY"] = "dev" flask_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False flask_app.config["JWT_TOKEN_LOCATION"] = ["cookies"] flask_app.config["JWT_ACCESS_COOKIE_PATH"] = "/api" flask_app.config["JWT_REFRESH_COOKIE_PATH"] = "/token/refresh" flask_app.config["JWT_COOKIE_CSRF_PROTECT"] = False flask_app.config["JWT_CSRF_IN_COOKIES"] = False # Flask provides a way to test your application by exposing the Werkzeug test Client # and handling the context locals for you. testing_client = flask_app.test_client() # Establish an application context before running the tests. ctx = flask_app.app_context() ctx.push() yield testing_client # this is where the testing happens! ctx.pop()
def main(): app = create_app() with app.app_context(): db.create_all() write_to_db(app)
def app(): flask_app = create_app(TestingConfig) # Establish an application context before running the tests. ctx = flask_app.app_context() ctx.push() yield flask_app
def _app(config_class, init_scheduler=False) -> Flask: __app: Flask = create_app(config_class, init_scheduler) if config_class is TestingConfig: db.drop_all() db.create_all() return __app
def setup(self): self.graph = create_app(testing=True) self.account_store = self.graph.account_store self.name = "NAME" with SessionContext(self.graph) as context: context.recreate_all()
def setUp(self): """ Called before each test case """ # Create new instance of our application app = create_app('testing') # Allows for requests to e made self.client = app.test_client(self)
def app(): """An application for the tests.""" _app = create_app('tests.settings') ctx = _app.test_request_context() ctx.push() yield _app ctx.pop()
def create_app_and_client_with_forced_album(self, forced_album_name): self.album_handler = FolderAlbumHandler(self.static_dir_name, "albums") qr_code_handler = QrCodeHandler(self.static_dir_name) app = create_app(self.album_handler, self.static_dir_name, self.camera_module, qr_code_handler, forced_album_name=forced_album_name) self.test_client = app.test_client()
def main(): app = create_app() with app.app_context(): db.create_all() read_from_file_and_write_to_db() geocode_cities()
async def test_sign_up_validation(aiohttp_client, login, abt, status, psql_port, psql_creds, fake_user): app = create_app(None) client = await aiohttp_client(app) resp = await client.post( "/api/sign_up/", json={"username": login} if login else {}, headers={aiohttp.hdrs.AUTHORIZATION: f"Basic {abt}"} if abt else {}) assert resp.status == status
async def fake_user(psql_port, psql_creds, aiohttp_client): app = create_app(None) await aiohttp_client(app) connector = psql_connector.get_psql_connector_from_app(app) try: await connector.users.add_user(*test_app_creds) except psql_connector.UserExistsError: pass await app.shutdown()
def setup(self): self.graph = create_app(testing=True) self.client = self.graph.flask.test_client() recreate_all(self.graph) self.name = "name" self.account = Account( id=new_object_id(), name=self.name, )
def __initialise_app(self): qr_code_handler = self.create_qr_code_handler(self.production_port) album_handler = self.get_album_handler_instance() self.ensure_forced_album_is_created(album_handler) camera_module = self.get_camera_module_instance() return create_app(album_handler, self.static_folder_name, camera_module, qr_code_handler, forced_album_name=self.args.force_album)
def setUp(self): # Create a temporary static dir which is deleted after every test self.static_dir = tempfile.TemporaryDirectory(dir=".") self.static_dir_name = self.static_dir.name.split("./")[1] camera_module = create_fast_dummy_module() album_handler = FolderAlbumHandler(self.static_dir_name, "albums") self.qr_code_handler = QrCodeHandler(self.static_dir_name) app = create_app(album_handler, self.static_dir_name, camera_module, self.qr_code_handler) self.test_client = app.test_client()
def app(): """Create app, instantiate test client, drop DB after use.""" application = create_app(**TEST_SETTINGS) application.test_client_class = TestClient application.client = application.test_client() # Using __get__ binds the function to the application instance application.user = user.__get__(application) # pylint: disable=E1121 application.admin = admin.__get__(application) # pylint: disable=E1121 yield application drop_database(application)
async def test_update_status(aiohttp_client, producer, query_request_id, status_update_payload, status_check_result): client = await aiohttp_client(create_app(producer)) response = await client.post("/api/status/", json=status_update_payload) response.raise_for_status() json_data = await response.json() assert json_data["status"] == "captured" response = await client.get("/api/status/", params={"request_id": query_request_id}) json_data = await response.json() assert json_data == status_check_result
def app(): """ Creates a new Flask application for each test. :returns Iterator[Flask App] _app: The Flask application for the test """ _app = create_app(TestingConfig) context = _app.app_context() context.push() yield _app context.pop()
def app(): # setup _app = create_app(TestConfig) # create test tables with _app.app_context(): db.drop_all() db.create_all() yield _app # teardown with _app.app_context(): db.drop_all()
def migration(event, context): with create_app().app_context(): # db commands can exit with os.exit(1) - we _have_ to catch that with wrap_io(catch=BaseException) as (out, err): upgrade() if "Please use the 'init' command" in err(): init() upgrade() if "Target database is not up to date" in err(): stamp() upgrade() return {"stdout": out(), "stderr": err()}
def _db(): """Create and configure a new db instance for pytest-flask-sqlalchemy.""" db_fd, db_path = tempfile.mkstemp() app = create_app() app.config["TESTING"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["DATABASE"] = db_path app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" with app.app_context(): db.init_app(app) db.create_all() yield db os.close(db_fd) os.unlink(db_path)
def test_route_favicon(): app = create_app(TestConfig) # setup client client = app.test_client() url = "/favicon.svg" response = client.get(url) # get expected file dist_dir = app.config['DIST_DIR'] entry = os.path.join(dist_dir, 'favicon.svg') with open(entry, "rb") as file: favicon_svg = io.BytesIO(file.read()) # test response vs expected assert response.get_data() == favicon_svg.read() assert response.status_code == 200
def test_route_index(): app = create_app(TestConfig) # setup client client = app.test_client() url = "/" response = client.get(url) # get expected file dist_dir = app.config['DIST_DIR'] entry = os.path.join(dist_dir, 'index.html') with open(entry, "rb") as file: index_html = io.BytesIO(file.read()) # test response vs expected assert response.get_data() == index_html.read() assert response.status_code == 200
async def test_image_submit(aiohttp_client, producer): mock_send_image_to_mq = MagicMock() producer.fut.set_result(mock_send_image_to_mq) client = await aiohttp_client(create_app(producer)) response = await client.post("/api/image_submit/", json={ "image": "001010101010", "lang": "eng" }) response.raise_for_status() json_data = await response.json() assert mock_send_image_to_mq.called args, kwargs = mock_send_image_to_mq.call_args assert args[0] == "001010101010" assert args[1] == json_data["request_id"] assert args[2] == "eng"
def app(): """Create and configure a new app instance for tests.""" # create a temp file to isolate the db for each test db_fd, db_path = tempfile.mkstemp() app = create_app() app.config["TESTING"] = True app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["DATABASE"] = db_path app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" # create the db and load test data with app.app_context(): db.init_app(app) db.create_all() yield app # close and remove the temporary db os.close(db_fd) os.unlink(db_path)
def test_route_assets(): app = create_app(TestConfig) # test assets assets = ["coach-category-fork.svg", "coach-category-shock.svg"] for asset in assets: # setup client client = app.test_client() url = "/assets/" + asset response = client.get(url) # get expected file dist_dir = app.config['DIST_DIR'] entry = os.path.join(dist_dir, 'assets', asset) with open(entry, "rb") as file: asset_file = io.BytesIO(file.read()) # test response vs expected assert response.get_data() == asset_file.read() assert response.status_code == 200 # test access to files from other asset = "../favicon.svg" # setup client client = app.test_client() url = "/assets/" + asset response = None try: response = client.get(url) # must throw an error! except (Exception, ): pass # get expected file dist_dir = app.config['DIST_DIR'] entry = os.path.join(dist_dir, 'assets', asset) with open(entry, "rb") as file: asset_file = io.BytesIO(file.read()) # test response vs expected assert response is None
def app(): """ Setup our Flask test app, this will only get executed once. return: Flask app """ params = { 'DEBUG': False, 'TESTING': True, } _app = create_app(settings_override=params) #Establish an application context before running the tests. ctx = _app.app_context() ctx.push() yield _app ctx.pop()
def app(): """ Setup our flask Test app. This will only be executed once return: Flask app """ db_uri = '{0}_test'.format(settings.SQLALCHEMY_DATABASE_URI) params = { 'DEBUG': False, 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': db_uri } _app = create_app(settings_override=params) # Establish an app context before running any tests ctx = _app.app_context() ctx.push() yield _app ctx.pop()
def setUp(self): self.app = app.create_app(debug=True) self.app.config['TESTING'] = True
from flask.helpers import get_debug_flag from backend.app import create_app from backend.settings import DevConfig, ProdConfig CONFIG = DevConfig if get_debug_flag() else ProdConfig app = create_app(CONFIG)