Long Nguyen
Long Nguyen

Reputation: 1

Create two types of session to the database. One for testing and one for other use

I just have a question that how can I create 2 type of session fixture to connect to the database using SQLAlchemy.

@pytest.fixture
def session_function_scope():
    engine = create_engine('sqlite:///:memory:'
    Session = sessionmaker(bind=engine)
    session = Session
    yield session
    session.close()

@pytest.fixture(scope='session')
def session_session_scope():
    engine = create_engine('sqlite:///:memory:'
    Session = sessionmaker(bind=engine)
    session = Session
    yield session
    session.close()

Here is my approach to the solution. under functional and unit test for the database, we will use the function scope and for other use, we will use the session scope. But if I use this approach, we will have duplicate code. Do you have any approach to solve this?

Thank you

Upvotes: 0

Views: 21

Answers (1)

ViAchKoN
ViAchKoN

Reputation: 724

Why not use a single session? It's better to use function scope to ensure that each test case uses a new session. This way, there is a lower chance that different tests will affect each other. I haven't seen any case where you might need to create a single session for a test run.

Upvotes: 0

Related Questions