def test_csrf_setting(): """ Tests whether CSRF enabled config is set properly """ key = "WTF_CSRF_ENABLED" assert key not in create_app().config app = create_app({key: False}) assert app.config[key] is False
def test_config(): """ Tests whether `testing` attribute is not set by default and is enabled with a custom configuration """ assert not create_app().testing assert create_app({"TESTING": True}).testing
def setUp(self): self.config = Config() self.app = create_app(self.config) self.test_client = self.app.test_client() with self.app.app_context(): db.create_all()
def setUp(self): super(TestBook, self).setUp() self.maxDiff = None self.app = create_app() self.session = session user_obj = User( username="******", email="*****@*****.**", password=pbkdf2_sha256.hash("pass") ) self.session.add(user_obj) self.session.flush() self.user_id = int(user_obj.id) book_type = BookType( book_type="normal", charge="1.5" ) self.session.add(book_type) self.session.flush() self.book_type_id = int(book_type.id) book_obj = Book( book_name="python", book_type_id=self.book_type_id ) self.session.add(book_obj) self.session.flush() self.book_id = int(book_obj.id)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Role.insert_roles() self.client = self.app.test_client()
def setUp(self): """Set up for tests""" test_config = { 'TEST_DB_URI': 'postgresql://*****:*****@db:5432/testdb' } self.app = create_app(test_config) self.client = self.app.test_client self.db = db self.db.create_all()
def user_client(): app = create_app(test=True) client = app.test_client() create = {'name': 'test', 'password': '', 'create_account': ''} login = {'name': 'test', 'password': '', 'login': ''} with app.app_context(): client.post('/admin/process_user', data=create) client.post('/admin/login', data=login) yield client remove(join(path_source, 'database.db'))
def setUp(self): super(TestUsers, self).setUp() self.maxDiff = None self.app = create_app() self.session = session user_obj = User(username="******", email="*****@*****.**", password=pbkdf2_sha256.hash("pass")) self.session.add(user_obj) self.session.flush() self.user_id = int(user_obj.id)
def client(): flask_app = create_app() # 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 setUp(self): self.app = create_app() self.client = self.app.test_client self.database_name = "trivia_test" self.database_path = "postgresql://{}/{}".format( 'localhost:5432', self.database_name) setup_db(self.app, self.database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all()
def run_proxy_server_with_web(host, port, name, web_port, start_proxy=True): """ 运行带web管理功能的代理服务端。 :param host: 代理服务器地址(本机) :param port: 代理服务端口(TCP和UDP同时开启,共用同一个端口号) :param name: 代理服务器名称 :param web_port: Web管理服务端口 :param start_proxy: 是否直接启动代理服务 :return: """ from threading import Thread from flask_app import create_app def thread_proxy_server(loop): asyncio.set_event_loop(loop) loop.run_forever() def proxy_server_api(api_name, *args, timeout=None): result = None try: result = proxy_server.execute(proxy_loop, api_name, *args, timeout=timeout) except (asyncio.TimeoutError, ProtocolError, ProxyError, Exception) as e: log.error(f'Call of Proxy Server: {e}') finally: return result flask_app = create_app() proxy_server = ProxyServer(host, port, None, name) proxy_loop = asyncio.new_event_loop() thread_proxy = Thread(target=thread_proxy_server, args=(proxy_loop,)) # flask_app.proxy_server = proxy_server flask_app.proxy_api = ProxyServer.AsyncApi flask_app.proxy_execute = proxy_server_api flask_app.proxy_is_running = proxy_server.is_running flask_app.proxy_reset_statistic = proxy_server.reset_statistic flask_app.proxy_server_info = proxy_server._get_server_info flask_app.proxy_clients_info = proxy_server._get_clients_info thread_proxy.setDaemon(True) thread_proxy.start() if start_proxy: flask_app.proxy_execute(ProxyServer.AsyncApi.STARTUP_SERVER) try: flask_app.run(host=host, port=web_port, debug=False) except KeyboardInterrupt: flask_app.execute(ProxyServer.AsyncApi.SHUTDOWN_SERVER) finally: proxy_loop.stop()
def app(): db_fd, db_path = tempfile.mkstemp() app = create_app({ 'TESTING': True, 'DATABASE': db_path, }) with app.app_context(): db.init_db() yield app os.close(db_fd) os.unlink(db_path)
def setUpClass(cls): # start Chrome options = webdriver.ChromeOptions() options.add_argument('headless') try: """ cls.client = webdriver.Chrome(chrome_options=options) DeprecationWarning: use options instead of chrome_options cls.client = webdriver.Chrome(chrome_options=options) """ cls.client = webdriver.Chrome(options=options) except: pass # skip these tests if the browser could not be started if cls.client: # create the application cls.app = create_app('testing') cls.app_context = cls.app.app_context() cls.app_context.push() # suppress logging to keep unittest output clean import logging logger = logging.getLogger('werkzeug') logger.setLevel("ERROR") # create the database and populate with some fake data db.create_all() Role.insert_roles() fake.users(10) fake.posts(10) # add an administrator user admin_role = Role.query.filter_by(name='Administrator').first() admin = User(email='*****@*****.**', username='******', password='******', role=admin_role, confirmed=True) db.session.add(admin) db.session.commit() # start the Flask server in a thread cls.server_thread = threading.Thread(target=cls.app.run, kwargs={'debug': False}) cls.server_thread.start() # give the server a second to ensure it is up time.sleep(1)
def app(request): db_name = "p5_test_db" test_config = { "TESTING": True, "MONGODB_HOST": f"mongodb://localhost:27017/{db_name}", "WTF_CSRF_ENABLED": False, } disconnect() app = create_app(test_config) User.drop_collection() Review.drop_collection() ctx = app.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def create_app(self): return create_app('testing', testing=True)
# -*- coding: utf-8 -*- """ """ import flask_app from flask_app.helpers.app import simple_exception_handler APP = flask_app.create_app(flask_app.from_module_name(__name__)) with APP.app_context(): from . import routes def serve(app_env=None): flask_app.serve(APP, app_env) @APP.errorhandler(Exception) def handler(*args, **kwargs): return simple_exception_handler(*args, **kwargs)
class StandaloneApplication(gunicorn.app.base.BaseApplication): def __init__(self, app, options=None): self.options = options or {} self.application = app super(StandaloneApplication, self).__init__() def load_config(self): config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value) def load(self): return self.application if __name__ == '__main__': options = { 'bind': '%s:%s' % ('127.0.0.1', '8080'), 'workers': number_of_workers(), 'threads': 5, 'keepalive' : 2, 'worker_class' : 'gevent', } app = create_app('config.Config') StandaloneApplication(app, options).run()
from flask_app import create_app, db from flask_app.models import Client, Product def populate_tables(db_session): if len(Client.query.all()) == 0: cs = [Client('Client%s' % x) for x in ['A', 'B', 'C']] for c in cs: db_session.session.add(c) p = Product('Policies'); db_session.session.add(p) p = Product('Billing'); db_session.session.add(p) p = Product('Claims'); db_session.session.add(p) p = Product('Reports'); db_session.session.add(p) db_session.session.commit() if __name__ == '__main__': app = create_app() with app.app_context(): db.create_all() populate_tables(db)
def app(): _app = create_app(TEST_DB) return _app
#!/usr/bin/python import sys import logging from flask_app import create_app logging.basicConfig(stream=sys.stderr) application = create_app()
def create_app(self): return create_app()
#!/usr/bin/python # -*- coding: utf -*- import flask_app application = flask_app.create_app()
def __init__(self, *args, **kwargs): self.app = create_app(api=False) super(AdvancedWorker, self).__init__(*args, **kwargs)
def create_app(self): app = create_app() app.config.from_object(self) return app
def setUp(self): self.app = create_app(TestConfig) self.app_context = self.app.app_context() self.app_context.push() db.create_all()
def setUp(self): self.app = create_app("testing") self.app_ctx = self.app.app_context() self.app_ctx.push() self.client = self.app.test_client()
if os.path.exists(dotenv_path): load_dotenv(dotenv_path) COV = None if os.environ.get('FLASK_COVERAGE'): import coverage COV = coverage.coverage(branch=True, include='app/*') COV.start() import sys import click from flask_migrate import Migrate, upgrade from flask_app import create_app, db from flask_app.models import User, Follow, Role, Permission, Post, Comment app = create_app(os.getenv('FLASK_CONFIG') or 'default') migrate = Migrate(app, db) @app.shell_context_processor def make_shell_context(): return dict(db=db, User=User, Follow=Follow, Role=Role, Permission=Permission, Post=Post, Comment=Comment) @app.cli.command()
def setUp(self, _): """Runs before each test method.""" self.client = flask_app.create_app(test_env="test").test_client()
def create_app(self): app = create_app() app.config['LIVESERVER_PORT'] = 8943 return app
import os from flask_app import create_app app = create_app(os.getenv("FLASK_ENV"))
def test_create_app(): """Basic testing if factory function of creating Flask app works""" assert not create_app().testing assert create_app({"TESTING": True}).testing
#!/usr/bin/python # -*- coding: utf -*- import flask_app, config application = flask_app.create_app(database=config.MONGODB_DB)
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse: return func.WsgiMiddleware(create_app()).handle(req, context)
import unittest import utility as util from flask_app import create_test_app as create_app # Dont Use PyCharm does not find tests app = create_app() class TestModelFlaskUnit(unittest.TestCase): client = app.test_client() def test_add_store_and_delete_again(self): util.log("test_add_store_and_delete_again") rv = TestModelFlaskUnit.client.post('/store/StoreToADD', json={'name': 'doesnotmatter'}) ''' { "id": ?, "name": "StoreToADD", "email": null, "type": null, "item_count": null } ''' rv_jason = rv.get_json() print("result as json: {}".format( rv_jason)) # 'A store with name \'StoreToADD\' already exists.' print(b"result: " + rv.data) assert b"\"name\": \"StoreToADD\"" in rv.data # "name": "StoreToADD"
import os from flask_app import create_app from config.development import Development as Config from flask_app import db # if os.environ["FLASK_ENV_TYPE"] == "Development": # from config.development import Development as Config # elif os.environ["FLASK_ENV_TYPE"] == "Production": # from config.production import Production as Config # else: # raise Exception("Not proper Flask_ENV_TYPE set") app = create_app(Config) @app.route("/") def hello(): return "Hello world" if __name__ == "__main__": app.run()