Bird
Raised Fist0
Flaskframework~20 mins

Testing with database in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Database Testing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask test with database setup?
Consider this Flask test code snippet that uses a test database. What will be the output when running this test?
Flask
import unittest
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['TESTING'] = True

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class UserTestCase(unittest.TestCase):
    def setUp(self):
        db.create_all()
        user = User(name='Alice')
        db.session.add(user)
        db.session.commit()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_user_count(self):
        count = User.query.count()
        print(count)

if __name__ == '__main__':
    unittest.main()
ARaises an AttributeError
B0
C1
DRaises an OperationalError
Attempts:
2 left
💡 Hint
Think about what happens in setUp before the test runs.
🔧 Debug
intermediate
2:00remaining
Why does this Flask test raise an error when accessing the database?
This Flask test raises an error when trying to query the database. What is the cause?
Flask
import unittest
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['TESTING'] = True

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class UserTestCase(unittest.TestCase):
    def test_user_count(self):
        count = User.query.count()
        print(count)

if __name__ == '__main__':
    unittest.main()
AThe database tables were not created before the test ran
BThe User model is missing a primary key
CThe app config is missing the TESTING flag
DThe query syntax is incorrect
Attempts:
2 left
💡 Hint
Check if the database schema exists before querying.
📝 Syntax
advanced
2:00remaining
Which option correctly uses Flask's test client with database setup?
Select the code snippet that correctly sets up a Flask test client and database for testing a route that queries the database.
A
def setUp(self):
    self.app = app.test_client()
    db.create_all()
    user = User(name='Bob')
    db.session.add(user)
    db.session.commit()
B
def setUp(self):
    self.app = app.test_client()
    user = User(name='Bob')
    db.session.add(user)
    db.session.commit()
C
def setUp(self):
    self.app = app.test_client
    db.create_all()
    user = User(name='Bob')
    db.session.add(user)
    db.session.commit()
D
def setUp(self):
    self.app = app.test_client()
    db.drop_all()
    user = User(name='Bob')
    db.session.add(user)
    db.session.commit()
Attempts:
2 left
💡 Hint
Remember to call test_client as a function and create tables before adding data.
❓ state_output
advanced
2:00remaining
What is the value of 'user_count' after running this Flask test?
Given this test code, what will be the value of 'user_count' printed?
Flask
import unittest
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['TESTING'] = True

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class UserTestCase(unittest.TestCase):
    def setUp(self):
        db.create_all()
        user1 = User(name='Alice')
        db.session.add(user1)
        db.session.commit()

    def test_add_user(self):
        user2 = User(name='Bob')
        db.session.add(user2)
        db.session.commit()
        user_count = User.query.count()
        print(user_count)

    def tearDown(self):
        db.session.remove()
        db.drop_all()

if __name__ == '__main__':
    unittest.main()
ARaises an error
B1
C0
D2
Attempts:
2 left
💡 Hint
Consider the users added in setUp and test_add_user.
🧠 Conceptual
expert
2:00remaining
Which statement best explains why Flask tests use an in-memory SQLite database?
Why do Flask tests often configure the database URI as 'sqlite:///:memory:' during testing?
AIt stores the database in a file named ':memory:' on disk for persistence
BIt creates a temporary database in RAM that is fast and isolated for each test run
CIt connects to the production database but disables writes
DIt uses a remote database server optimized for testing
Attempts:
2 left
💡 Hint
Think about speed and isolation in tests.

Practice

(1/5)
1. What is the main purpose of using a test database in Flask testing?
easy
A. To store user sessions permanently
B. To isolate tests so they don't affect the real data
C. To speed up the app in production
D. To replace the main database in deployment

Solution

  1. Step 1: Understand test database role

    A test database is used to keep test data separate from real data to avoid unwanted changes.
  2. Step 2: Identify isolation benefit

    This isolation ensures tests do not affect the real app data or state.
  3. Final Answer:

    To isolate tests so they don't affect the real data -> Option B
  4. Quick Check:

    Test database isolates data = C [OK]
Hint: Test DB keeps test data separate from real data [OK]
Common Mistakes:
  • Thinking test DB speeds up production
  • Confusing test DB with session storage
  • Assuming test DB replaces main DB in deployment
2. Which Flask testing method is used to prepare the test database before each test runs?
easy
A. tearDown
B. initTest
C. setUp
D. runTest

Solution

  1. Step 1: Recall Flask test lifecycle methods

    In Flask testing, setUp runs before each test to prepare the environment.
  2. Step 2: Match method to database preparation

    Preparing the test database (like creating tables) happens in setUp.
  3. Final Answer:

    setUp -> Option C
  4. Quick Check:

    Prepare DB before test = setUp [OK]
Hint: Use setUp to prepare before each test [OK]
Common Mistakes:
  • Confusing tearDown with setup
  • Using runTest which is not for setup
  • Assuming initTest is a Flask method
3. Given this test code snippet, what will print(len(users)) output?
def test_user_creation(self):
    user = User(name='Anna')
    db.session.add(user)
    db.session.commit()
    users = User.query.all()
    print(len(users))
medium
A. 1
B. 0
C. Error: session not initialized
D. Multiple users depending on previous tests

Solution

  1. Step 1: Analyze user addition and commit

    The code adds one user and commits to the test database.
  2. Step 2: Query all users after commit

    Querying all users returns a list with the one added user.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    One user added and committed = 1 [OK]
Hint: Commit before query to see added users [OK]
Common Mistakes:
  • Forgetting to commit before query
  • Assuming previous tests add users
  • Thinking session is not initialized
4. What is wrong with this test code snippet?
def tearDown(self):
    db.session.remove()
    db.drop_all()
medium
A. Missing call to create_all() in tearDown
B. tearDown should not remove session
C. drop_all() should be in setUp, not tearDown
D. No call to rollback() before drop_all()

Solution

  1. Step 1: Understand tearDown purpose

    tearDown cleans up after tests by removing session and dropping tables.
  2. Step 2: Identify missing rollback before drop_all()

    Without rollback, pending changes may not be discarded, potentially causing errors or inconsistent state.
  3. Final Answer:

    No call to rollback() before drop_all() -> Option D
  4. Quick Check:

    Rollback before drop_all to discard changes [OK]
Hint: Always rollback before dropping tables in tearDown [OK]
Common Mistakes:
  • Thinking create_all belongs in tearDown
  • Believing session removal is wrong in tearDown
  • Ignoring rollback before drop_all
5. You want to test a Flask app that uses a database. Which sequence correctly sets up and cleans the test database for each test?
hard
A. Call db.create_all() in setUp, run test, then db.drop_all() in tearDown
B. Call db.drop_all() in setUp, run test, then db.create_all() in tearDown
C. Call db.session.commit() in setUp, then db.session.remove() in tearDown
D. Call db.create_all() and db.drop_all() both in setUp

Solution

  1. Step 1: Understand test setup and cleanup

    Creating tables before each test ensures a fresh database state.
  2. Step 2: Understand test teardown

    Dropping tables after each test cleans up to avoid data carryover.
  3. Step 3: Match correct sequence

    Calling create_all() in setUp and drop_all() in tearDown is the correct pattern.
  4. Final Answer:

    Call db.create_all() in setUp, run test, then db.drop_all() in tearDown -> Option A
  5. Quick Check:

    Create tables before, drop after test = A [OK]
Hint: Create tables before test, drop after test [OK]
Common Mistakes:
  • Dropping tables before test instead of after
  • Calling create_all and drop_all both in setUp
  • Confusing commit with setup/teardown
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard