147: Testing Single File Python Applications/Scripts with pytest and coverage - podcast episode cover

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

Mar 06, 202112 minSeason 1Ep. 147
--:--
--:--
Download Metacast podcast app
Listen to this episode in Metacast mobile app
Don't just listen to podcasts. Learn from them with transcripts, summaries, and chapters for every episode. Skim, search, and bookmark insights. Learn more

Episode description

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"

Suggestion by @cfbolz if you need to import pytest:

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



Help support the show AND learn pytest: 

  • The Complete pytest course is now a bundle, with each part available separately.
  • Whether you need to get started with pytest today, or want to power up your pytest skills, PythonTest has a course for you.

★ Support this podcast on Patreon ★
For the best experience, listen in Metacast app for iOS or Android
Open in Metacast
147: Testing Single File Python Applications/Scripts with pytest and coverage | Test & Code podcast - Listen or read transcript on Metacast