0
0
Testing Fundamentalstesting~10 mins

Test coverage metrics in Testing Fundamentals - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the test coverage tool correctly measures the percentage of code lines executed during testing. It verifies that the coverage report matches the expected coverage value.

Test Code - unittest with coverage.py
Testing Fundamentals
import unittest
import coverage

class Calculator:
    def add(self, a, b):
        return a + b
    def subtract(self, a, b):
        return a - b

class TestCalculator(unittest.TestCase):
    def test_add(self):
        calc = Calculator()
        self.assertEqual(calc.add(2, 3), 5)

if __name__ == '__main__':
    cov = coverage.Coverage()
    cov.start()
    unittest.main(exit=False)
    cov.stop()
    cov.save()
    analysis = cov.analysis('test_coverage_metrics.py')
    coverage_percent = analysis[4]
    print(f"Coverage: {coverage_percent:.2f}%")
    assert coverage_percent >= 50, "Coverage is less than 50%"
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test starts and coverage measurement beginsCoverage tool initialized, test runner ready-PASS
2Test runner executes test_add method of TestCalculatorCalculator instance created, add method called with (2,3)Check if add(2,3) returns 5PASS
3Coverage measurement stops and data savedCoverage data collected for executed lines-PASS
4Coverage report generated and coverage percentage calculatedCoverage report shows lines executed vs total linesAssert coverage_percent >= 50PASS
Failure Scenario
Failing Condition: Test coverage is below 50% because some code lines are not executed
Execution Trace Quiz - 3 Questions
Test your understanding
What does the coverage tool measure in this test?
AThe time taken to run the tests
BThe percentage of code lines executed during the test
CThe number of tests passed
DThe number of errors in the code
Key Result
Always write tests that cover important code paths to ensure high test coverage and catch potential bugs early.