Python Computer Science
Beginner
80 mins
Teacher/Student led
What you need:
Chromebook/Laptop/PC

Advanced Debugging and Testing

In this lesson, you'll explore advanced debugging and testing techniques for software development. Learn the key stages of testingโ€”unit, integration, and systemโ€”and apply them to debug and test a Flask web app with SQLite in VS Code.
Learning Goals Learning Outcomes Teacher Notes

Teacher Class Feed

Load previous activity

    1 - Introduction

    In this lesson, you will explore advanced debugging and testing techniques in software engineering. You will learn about the stages of testing: unit testing, integration testing, and system testing. Then, you will apply these concepts by debugging and testing a Flask web application that uses SQLite for data storage. Finally, you will reflect on the code's limitations and suggest improvements.

    By the end, you will be able to:

    • Explain the stages of testing.
    • Debug a Flask app with SQLite in VS Code.
    • Perform unit, integration, and system tests.
    You will work in VS Code. Ensure you have Python, Flask, and SQLite installed from previous lessons. Create a new folder called 'DebugFlaskApp' for this lesson.

    2 - Understanding Testing Stages

    Before debugging, let's review the key stages of software testing:

    • Unit Testing: Tests individual components or functions in isolation to ensure they work as expected. For example, testing a single function that adds data to a database.
    • Integration Testing: Tests how different components work together, such as how a Flask route interacts with a database query.
    • System Testing: Tests the entire application as a whole to verify it meets requirements, including user interfaces and end-to-end functionality.

    Debugging involves identifying and fixing errors (bugs) in the code, often using tools like print statements, breakpoints in VS Code, or error messages.

    In the next steps, you will debug a provided Flask app that has intentional bugs, then apply these testing stages.

    3 - Create your environment and install Flask

    Create a virtual environment to manage your project's dependencies separately.

    1. Open the Command Palette: View > Command Palette.
    2. Type 'Python: Create Environment' and select it.
    3. Choose 'Venv' as the type.
    4. Select your installed Python version.
    5. VS Code will create a '.venv' folder in 'DebugFlaskApp'.

    Now, open a terminal in VS Code to install Flask if it's not already installed.

    1. Go to the menu: View > Terminal
    2. This opens the Terminal panel at the bottom of VS Code.
    3. In the terminal, run: pip install flask
    4. Wait for the installation to complete.

    4 - Set Up the Buggy Flask App

    Create the initial structure for a simple Flask app that manages a user database with SQLite. This code has bugs that you will fix later.

    First, in your 'DebugFlaskApp' folder, create a file called 'app.py' and add this complete code:

    from flask import Flask, render_template, request
    import sqlite3
    
    app = Flask(__name__)
    
    def init_db():
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS users
            (id INTEGER PRIMARY KEY, name TEXT, age INTEGER CHECK(age = CAST(age AS INTEGER)))''')
        conn.commit()
        conn.close()
    
    init_db()
    
    @app.route('/')
    def home():
        return render_template('index.html')
    
    @app.route('/add', methods=['POST'])
    def add_user():
        name = request.form['name']
        age = request.form['age']  # Bug: Not converting to int
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        c.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
        conn.commit()
        conn.close()
        return 'User added!'
    
    @app.route('/users')
    def list_users():
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        c.execute("SELECT * FROM userss")  # Bug: Table name misspelled
        users = c.fetchall()
        conn.close()
        return render_template('users.html', users=users)
    
    if __name__ == '__main__':
        app.run(debug=True)

    Create a 'templates' folder inside 'DebugFlaskApp'. Inside 'templates', create 'index.html':

    <!DOCTYPE html>
    <html>
    <head><title>Add User</title></head>
    <body>
    <h1>Add User</h1>
    <form method="post" action="/add">
        <label>Name:</label><input type="text" name="name"><br>
        <label>Age:</label><input type="text" name="age"><br>
        <button type="submit">Add</button>
    </form>
    <a href="/users">View Users</a>
    </body>
    </html>

    And 'users.html' file in the 'templates':

    <!DOCTYPE html>
    <html>
    <head><title>Users</title></head>
    <body>
    <h1>Users</h1>
    <ul>
    {% for user in users %}
        <li>{{ user[1] }} (Age: {{ user[2] }})</li>
    {% endfor %}
    </ul>
    <a href="/">Back</a>
    </body>
    </html>
    Run the app by opening a terminal in VS Code and typing: python app.py. Visit http://127.0.0.1:5000/. Try adding a user and viewing the list โ€“ you will encounter errors. These are the bugs to fix next.

    5 - Identify the Bugs

    Now, lets debug the app.

    There are 2 bugs in the code:

    • In add_user: Age is not converted to int, causing a type error.
    • In list_users: Table name is misspelled as 'userss' instead of 'users'.

    Use VS Code's debugger:

    1. Set breakpoints by clicking in the gutter next to line numbers
    2. Run with debugging (F5 or Run > Start Debugging)
    3. Try adding a user with 'fifteen' as the age
    4. Try navigating to the View Users screen

    Using the debugger, step through the code line by line until it throws an error. Do this for both bugs.

    Debugging the code

    Unlock the Full Learning Experience

    Get ready to embark on an incredible learning journey! Get access to this lesson and hundreds more in our Digital Skills Curriculum.

    Copyright Notice
    This lesson is copyright of DigitalSkills.org 2017 - 2025. Unauthorised use, copying or distribution is not allowed.
    ๐Ÿช Our website uses cookies to make your browsing experience better. By using our website you agree to our use of cookies. Learn more