DEV Community

Avash Karn
Avash Karn

Posted on Edited on

Testing Your Flask App(Part 6): Debug Like a Pro

Introduction

Your app works on your machine. But does it work everywhere? Testing catches bugs before users do.

What You'll Learn

How to:

  • Write unit tests
  • Debug Flask errors
  • Use print statements effectively
  • Handle common bugs

Prerequisites

  • Flask basics
  • Part 1-5 knowledge
  • 20 minutes

Step 1: Unit Testing Basics

import unittest

class TestApp(unittest.TestCase):
    def test_homepage(self):
        response = app.test_client().get('/')
        self.assertEqual(response.status_code, 200)
Enter fullscreen mode Exit fullscreen mode

Step 2: Test Database

def test_create_entry(self):
    util.save_entry("Test", "Content")
    entry = util.get_entry("Test")
    self.assertEqual(entry, "Content")
Enter fullscreen mode Exit fullscreen mode

Step 3: Debug Mode

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Debug mode shows errors clearly and auto-reloads.

Step 4: Print Debugging

def new_page(request):
    print(f"Title: {title}")  # See value
    print(f"Content: {content}")
    util.save_entry(title, content)
Enter fullscreen mode Exit fullscreen mode

Common Bugs

  1. Not checking if entry exists
  2. Not validating input
  3. Database connection issues

Conclusion

Testing = fewer bugs. Debug mode = faster fixes. Print statements = your best friend.

sorry friends I couldn't upload posts recently as I was working on a personal project

Top comments (0)