Stephen K
Stephen K

Reputation: 737

How to test a variable assignment within a method?

Say I have method that just appends a string to an input string..

def request(
    url: str,
    headers: dict = None
):
    default_headers = {
        "user-agent": "some user agent"
    }
    
    if isinstance(headers, dict):
        default_headers.update(headers)

When I run a coverage report for this method, it says that default_headers.update(headers) needs coverage. How do I add coverage for this statement?

Upvotes: 0

Views: 301

Answers (1)

Michael Delgado
Michael Delgado

Reputation: 15442

Coverage counts lines which are actually encountered during execution in tests. So in your case, if that line is not being covered, it is because the conditional:

if isinstance(headers, dict):

must never evaluate to true in your test cases. To gain coverage for this line, pass a keyword argument headers as a dict.

A good discussion of statement coverage testing and its limitations can be found in this post: https://nedbatchelder.com/blog/200710/flaws_in_coverage_measurement.html

Upvotes: 1

Related Questions