Friday, March 5, 2021

Test and Code: 147: Testing Single File Python Applications/Scripts with pytest and coverage

Have you ever written a single file Python application or script?
Have you written tests for it?
Do you check code coverage?

This is the topic of this weeks episode, spurred on by a listener question.

The questions:

  • For single file scripts, I'd like to have the test code included right there in the file. Can I do that with pytest?
  • If I can, can I use code coverage on it?

The example code discussed in the episode: script.py

def foo():
    return 5


def main():
    x = foo()
    print(x)


if __name__ == '__main__': # pragma: no cover
    main()

## test code

# To test:
# pip install pytest
# pytest script.py

# To test with coverage:
# put this file (script.py) in a directory by itself, say foo
# then from the parent directory of foo:
# pip install pytest-cov
# pytest --cov=foo foo/script.py

# To show missing lines
# pytest --cov=foo --cov-report=term-missing foo/script.py


def test_foo():
    assert foo() == 5


def test_main(capsys):
    main()
    captured = capsys.readouterr()
    assert captured.out == "5\n"

Sponsored By:

Support Test & Code : Python Testing

<p>Have you ever written a single file Python application or script?<br> Have you written tests for it?<br> Do you check code coverage?</p> <p>This is the topic of this weeks episode, spurred on by a listener question.</p> <p>The questions:</p> <ul> <li>For single file scripts, I&#39;d like to have the test code included right there in the file. Can I do that with pytest?</li> <li>If I can, can I use code coverage on it?</li> </ul> <p>The example code discussed in the episode: script.py</p> <pre><code>def foo(): return 5 def main(): x = foo() print(x) if __name__ == &#39;__main__&#39;: # pragma: no cover main() ## test code # To test: # pip install pytest # pytest script.py # To test with coverage: # put this file (script.py) in a directory by itself, say foo # then from the parent directory of foo: # pip install pytest-cov # pytest --cov=foo foo/script.py # To show missing lines # pytest --cov=foo --cov-report=term-missing foo/script.py def test_foo(): assert foo() == 5 def test_main(capsys): main() captured = capsys.readouterr() assert captured.out == &quot;5\n&quot; </code></pre><p>Sponsored By:</p><ul><li><a href="https://ift.tt/2JDHRTz" rel="nofollow">PyCharm Professional</a>: <a href="https://ift.tt/2JDHRTz" rel="nofollow">Try PyCharm Pro for 4 months and learn how PyCharm will save you time.</a> Promo Code: TESTANDCODE21</li></ul><p><a href="https://ift.tt/2tzXV5e" rel="payment">Support Test & Code : Python Testing</a></p>

from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...