# How to Run a Method Before All Tests in All Classes?


In pytest, fixtures run setup code before tests across multiple classes or the entire test suite. They help provide reusable test data, manage resources like database connections, and set up test environments.

Fixtures can be scoped to different levels:

- `function`: Run once per test function (default)
- `class`: Run once per test class
- `module`: Run once per module
- `package`: Run once per package
- `session`: Run once per test session

To run a method before all tests in all classes across the entire test suite, use a `session` scoped fixture.

Here's an example using SQLite with a session-scoped fixture for database connection:

```python
import sqlite3
import pytest


@pytest.fixture(scope="session")
def db_connection():
    # Connect to an in-memory SQLite database
    conn = sqlite3.connect(":memory:")

    # Create a test table
    conn.execute(
        """CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"""
    )

    # Yield the connection for tests to use
    yield conn

    # Close the connection after all tests are done
    conn.close()


@pytest.fixture(autouse=True)
def reset_table(db_connection):
    # This fixture runs automatically before each test
    db_connection.execute("DELETE FROM users")
    db_connection.commit()


def test_insert_user(db_connection):
    ...

def test_insert_multiple_users(db_connection):
    ...

def test_update_user(db_connection):
    ...
```

This code uses pytest fixtures to manage an SQLite database connection for testing. The `db_connection` fixture, scoped to the entire test session, sets up an in-memory database, creates a `users` table, and then tears it down after all tests are complete. 

The `reset_table` fixture, with `autouse=True`, runs automatically before each test to ensure a clean state by deleting all entries in the `users` table. The test functions (`test_insert_user`, `test_insert_multiple_users`, and `test_update_user`) demonstrate basic database operations such as inserting and updating user records and verifying the results.

For a more thorough guide on using fixtures, see the [fixtures guide](https://betterstack.com/community/guides/testing/pytest-fixtures-guide/).