Guest User

Untitled

a guest
Sep 30th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import os
  2. import pytest
  3.  
  4. from alembic.command import upgrade
  5. from alembic.config import Config
  6.  
  7. from project.factory import create_app
  8. from project.database import db as _db
  9.  
  10.  
  11. TESTDB = 'test_project.db'
  12. TESTDB_PATH = "/opt/project/data/{}".format(TESTDB)
  13. TEST_DATABASE_URI = 'sqlite:///' + TESTDB_PATH
  14.  
  15.  
  16. ALEMBIC_CONFIG = '/opt/project/alembic.ini'
  17.  
  18.  
  19. @pytest.fixture(scope='session')
  20. def app(request):
  21. """Session-wide test `Flask` application."""
  22. settings_override = {
  23. 'TESTING': True,
  24. 'SQLALCHEMY_DATABASE_URI': TEST_DATABASE_URI
  25. }
  26. app = create_app(__name__, settings_override)
  27.  
  28. # Establish an application context before running the tests.
  29. ctx = app.app_context()
  30. ctx.push()
  31.  
  32. def teardown():
  33. ctx.pop()
  34.  
  35. request.addfinalizer(teardown)
  36. return app
  37.  
  38.  
  39. def apply_migrations():
  40. """Applies all alembic migrations."""
  41. config = Config(ALEMBIC_CONFIG)
  42. upgrade(config, 'head')
  43.  
  44.  
  45. @pytest.fixture(scope='session')
  46. def db(app, request):
  47. """Session-wide test database."""
  48. if os.path.exists(TESTDB_PATH):
  49. os.unlink(TESTDB_PATH)
  50.  
  51. def teardown():
  52. _db.drop_all()
  53. os.unlink(TESTDB_PATH)
  54.  
  55. _db.app = app
  56. apply_migrations()
  57.  
  58. request.addfinalizer(teardown)
  59. return _db
  60.  
  61.  
  62. @pytest.fixture(scope='function')
  63. def session(db, request):
  64. """Creates a new database session for a test."""
  65. connection = db.engine.connect()
  66. transaction = connection.begin()
  67.  
  68. options = dict(bind=connection, binds={})
  69. session = db.create_scoped_session(options=options)
  70.  
  71. db.session = session
  72.  
  73. def teardown():
  74. transaction.rollback()
  75. connection.close()
  76. session.remove()
  77.  
  78. request.addfinalizer(teardown)
  79. return session
Add Comment
Please, Sign In to add comment