def client(): """ 返回 flask client """ from src.config.config import chaos_db, redis_url, log_db if ("sqlite" not in chaos_db or "127.0.0.1" not in redis_url or "sqlite" not in log_db): raise Exception("单元测试请配置环境变量") from src.main import app app.config.update({ "SQLALCHEMY_POOL_SIZE": None, "SQLALCHEMY_POOL_TIMEOUT": None }) from src import db app.config["TESTING"] = True app.config["SERVER_NAME"] = "127.0.0.1:5000" ctx = app.app_context() ctx.push() db.create_all() yield app.test_client() db.session.remove() db.drop_all() ctx.pop()
def client(): c = app.test_client() with app.app_context(): db.create_all() yield c db.session.close() db.drop_all()
def forge(): ''' Generate fake data ''' db.create_all() name = "Joe Bu" movies = [ {'title': '我不是药神', 'year': '2019'}, {'title': '流感', 'year': '2018'}, {'title': '铁线虫入侵', 'year': '2018'}, {'title': '哪吒', 'year': '2019'}, {'title': '神探狄仁杰', 'year': '2016'}, {'title': '为爱迫降', 'year': '2020'}, {'title': '战狼2', 'year': '2017'}, {'title': '亲爱的,新年好', 'year': '2020'}, ] user = User(name=name) db.session.add(user) for movie in movies: mv = Movie(title=movie['title'], year=movie['year']) db.session.add(mv) db.session.commit() click.echo("Insert Done!")
def db_init(): """Initialize the database.""" db.drop_all() db.create_all() db.session.commit() print("Database was successfully initialized...") return None
def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.client.testing = True with self.app.app_context(): db.create_all()
def test_database(): db.create_all() yield db # testing happens here # remove db after testing is done db.session.remove() db.drop_all()
def db_init(): """Initialize the database.""" db.drop_all() db.create_all() db.session.commit() print("Successfully (re)created all databases...") return None
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( basedir, TEST_DB) self.app = app.test_client() db.create_all()
def drop_db(): """After get address /drop-all DB will be erased from data""" if request.method == 'GET': db.drop_all() db.create_all() flash('DB successfully dropped', "success") return redirect(url_for('index'))
def setUp(self): app.config.from_object('tests.config') self.app = app.test_client() db.session.close() db.drop_all( ) # http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/basic_use.html db.create_all() seed_core(db) db.session.commit() self.payload = { 'payload': json.dumps({ 'salary': 50000, 'email': '*****@*****.**', 'years_experience': 1, 'years_with_current_employer': 1, 'number_of_employers': 1, 'employment_type': EmploymentType.query.first().id, 'location': EmploymentType.query.first().id, 'education': EmploymentType.query.first().id, 'perks': [], 'roles': [{ 'id': Tech.query.first().id }], 'techs': [{ 'name': 'Not already in DB' }], 'verification_request': { 'profile_url': 'https://www.linkedin.com/in/test', 'employer_name': 'Test Company', 'note': 'Test note' } }) }
def initdb(): print("Creating non-existing tables ...", end='') db.create_all(app=app) # SQLAlchemy: creates tables defined in `models.py` (only if do not exist) print("\t[SUCCESS]") initialize_database() import_my_data()
def db(app, request): """ Returns function initialized database so db is cleared after each test. """ with app.app_context(): _db.drop_all() _db.create_all()
def resetdatabase(): st = "using config settings: {}".format( os.getenv('FLASK_CONFIG') or 'default') click.echo(st) db.drop_all() db.create_all() click.echo("database was reset")
def test(): with app.app_context(): db.reflect() db.drop_all() db.create_all() os.system("pytest -x")
def auth_client(): c = app.test_client() with app.app_context(): db.create_all() c.token = os.getenv("TEST_TOKEN") yield c db.session.close() db.drop_all()
def setUp(self) -> None: app.config['TESTING'] = True app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.app = app.test_client() db.drop_all() db.create_all()
def fake_data(): with app.app_context(): db.drop_all() db.create_all() fakeUser() fakeCourse() fakeRecord()
def setUp(self): db.create_all() self.app = app.test_client() self.app_context = app.app_context() self.app_context.push() db_manage = DataManager() folder_path = os.path.dirname(os.path.abspath(__file__)) db_manage.load_data(folder_path)
def setUp(self): app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] = False app.config["DEBUG"] = False app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + TEST_DB self.app = app.test_client() db.drop_all() db.create_all()
def setUp(cls): cls.app = create_app() cls.app_context = cls.app.app_context() cls.app_context.push() cls.client = cls.app.test_client() db.create_all() runner = cls.app.test_cli_runner() runner.invoke(args=["db-custom", "seed"])
def init_db(): print("init database...") try: from src.models.IdeaModel import IdeaModel from src.models.PerfomanceModel import PerformanceModel db.create_all() except Exception as e: print(e)
def test_database(): # Before test, firstly prepare database. db.create_all() print("[fixture] In test_database(), before yield") yield db # testing happens here print("[fixture] In test_database(), after yield") db.session.remove() # After test, finally close the database. db.drop_all()
def setUp(self): db_engine = create_engine(Constant.DATABASE_BASE_URL + Constant.DATABASE_NAME + '_test') if not database_exists(db_engine.url): create_database(db_engine.url) from src.model.user_model import User db.create_all() db.session.commit()
def reset_db(): # delete meta = db.metadata for table in reversed(meta.sorted_tables): db.session.execute(table.delete()) db.session.commit() # create db.create_all() db.session.commit()
def database(test_app, request): """Test database to perform all ops on, cleaned after tests have been finished""" # create all tables db.create_all() return db # tear down all tables db.drop_all()
def test_admin_command(self): db.drop_all() db.create_all() result = self.runner.invoke( args=['admin', '--username', 'bzh', '--password', '123456']) self.assertIn('Creating user ...', result.output) self.assertIn('Done!', result.output) self.assertEqual(User.query.count(), 1) self.assertEqual(User.query.first().username, 'bzh') self.assertTrue(User.query.first().validate_password('123456'))
def regenerate_all(): # reset database db.drop_all() db.create_all() add_roles() add_users() add_projects() add_issues() add_messages() add_comments()
def app(): """Creates a new app instance.""" app = create_app(config_class=Testing) with app.app_context(): db.create_all() yield app with app.app_context(): db.session.remove() db.drop_all()
def setUp(self): app.config.from_object('tests.config') db.session.close() db.drop_all( ) # http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/basic_use.html db.create_all() self.perks = [ Perk('Yearly Bonus', listed=True), Perk('Food / Drinks', listed=True) ] for perk in self.perks: db.session.add(perk) self.locations = [ Location('London, Ontario'), Location('Near London, Ontario') ] for location in self.locations: db.session.add(location) self.employment_types = [ EmploymentType('Full-Time'), EmploymentType('Part-Time'), EmploymentType('Independent Contractor') ] for employment_type in self.employment_types: db.session.add(employment_type) self.roles = [ Role('Web: Backend', listed=True), Role('Web: Frontend', listed=True), Role('Web: Full-Stack', listed=True) ] for role in self.roles: db.session.add(role) self.education_levels = [ Education('High School'), Education('College / University') ] for education_level in self.education_levels: db.session.add(education_level) self.techs = [ Tech('Python', listed=True), Tech('PHP', listed=True), Tech('Java', listed=True) ] for tech in self.techs: db.session.add(tech) db.session.commit()
def setUp(cls): cls.app = create_app() cls.app_context = cls.app.app_context() cls.app_context.push() cls.client = cls.app.test_client() if os.environ.get("FLASK_ENV") != "testing": raise EnvironmentError("FLASK_ENV not equal to 'testing'") db.create_all() runner = cls.app.test_cli_runner() runner.invoke(args=["db-custom", "seed"])
def setUpHelper(self): """Configure test app and upload sample data""" app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/malb-test' self.app = app.test_client() self.TEST_USERNAME = TEST_USERNAME self.TEST_MALKEY = TEST_MALKEY self.TEST_MAL = TEST_MAL db.drop_all() db.create_all() MALB.synchronize_with_mal('quetzalcoatl384', 'cXVldHphbGNvYXRsMzg0OnBhc3N3b3Jk', 4448103) MALB.upload_aa_data('../data/aaresults0.txt')
#!flask/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from src import db import os.path db.create_all() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, "database repository") api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) else: api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
def setUp(self): db.create_all() # create all tables self.app = app self.client = self.app.test_client() # used to test client AJAX calls
def create_db_tables(): if db.create_all(): return 0 return 1
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()
def setUp(self): db.create_all() admin = User('admin', 'admin', True, 'ADMIN') db.session.add(admin) db.session.commit()