0Pricing
Flask Academy · Lezione

Isolare i test con un database di test

Utilizzi un database temporaneo per ogni esecuzione dei test.

Isolare i test con un database di test è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why Isolate the Database

Tests must never touch your real data. A test database keeps every run clean, so one test can never corrupt another or your production rows.

Use a Throwaway SQLite DB

The easy choice is an in-memory SQLite database. It lives only in RAM and vanishes the moment the test process ends.

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'

Flip on Testing Config

Set TESTING to True before tests run. It turns off error catching so exceptions surface clearly in your output.

app.config['TESTING'] = True

Build a Fresh Schema

Inside an app context, call db.create_all(). It builds every table from your models so each test run starts from an empty schema.

with app.app_context():
    db.create_all()

Tear Down After Tests

After the test, call db.drop_all() to remove every table. This guarantees the next run cannot inherit leftover rows.

with app.app_context():
    db.drop_all()

Put It in a Fixture

Wrap setup and teardown in one fixture. The code before yield creates the schema; the code after it drops everything cleanly.

@pytest.fixture
def app_db():
    db.create_all()
    yield
    db.drop_all()

Seed Sample Data

Many tests need a known row to read. Add a record in the fixture, then commit it so the test starts from a predictable state.

db.session.add(User(name='Ada'))
db.session.commit()

Why Fresh State Matters

Tests should pass in any order. Isolation means each test sees the same starting data, so results never depend on what ran before.

Roll Back Between Tests

An alternative to recreating tables is a rollback. Wrap each test in a transaction and undo it afterward for a fast, clean slate.

db.session.rollback()

Keep Test Config Separate

Store test settings in a dedicated TestConfig class. Your factory loads it only during tests, never in development or production.

class TestConfig:
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'

Never Test Against Prod

Always double-check the URI points at a test database. Pointing tests at production data is the fastest way to lose real records.

Quick Check

You want tests that never harm real data. What database do you use?

Recap: Test Database

You spin up a clean test database, seed known data, and tear it down after. Now your tests are fast, repeatable, and safe. 🗄️

Domande Frequenti

La lezione «Isolare i test con un database di test» è gratuita?

Sì — il testo completo di «Isolare i test con un database di test» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.

Cosa imparerò in «Isolare i test con un database di test»?

Utilizzi un database temporaneo per ogni esecuzione dei test. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Flask Academy?

Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Isolare i test con un database di test»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Flask Academy?

Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Test client e fixture
  2. Verificare route e JSON
  3. Isolare i test con un database di test
  4. Testare gli endpoint autenticati
← Torna a Flask Academy