Welcome back to CodeYourCraft! Today, we're diving into Coverage Reports in our Flask Tutorials series. Coverage reports help us understand how much of our code is actually being executed during testing. Let's get started!
Coverage reports in Flask are a way to measure the effectiveness of our tests. They show us which parts of our code are being tested and which parts are missing. This helps us write better tests and improve the quality of our code.
Coverage reports help us ensure that our tests cover all the necessary parts of our code. If we find that some parts of our code are not being tested, we can write additional tests to cover them. This helps us catch bugs and make our code more reliable.
To set up coverage reports in Flask, we'll use a library called coverage.
coverage ✅First, let's install coverage using pip:
pip install coveragecoverage ✅Next, we'll add a .coveragerc file to our project root. This file will configure coverage for our project. Here's an example:
[run]
branch = true
source = .
[report]
exclude_lines = re.escape("pragma: no cover")Now, let's modify our test script to run with coverage. Replace your current test script with this:
#!/usr/bin/env python3
import unittest
import coverage
cov = coverage.coverage(branch=True, source='.')
cov.start()
unittest.main()
cov.stop()
cov.save()Now, run your tests with ./test.sh (or whatever you named your test script).
After running your tests, you can analyze the coverage report with this command:
coverage reportThis will show you a summary of the coverage for each file in your project.
For more detailed coverage reports, you can generate HTML reports:
coverage htmlOpen the generated htmlcov/index.html file in your browser to view the detailed coverage report.
What does `coverage` help us with in Flask?
Stay tuned for more Flask Tutorials! Next, we'll cover testing in Flask. Until then, happy coding! 😄