Python Classroom Series – 01/Aug/2021

How does pytest do it?

  • By default, pythons assert statement does not provide any details when it fails, but as we have seen pytest shows a lot of information about the variables and expressions involved in failed assertion. Preview Preview
  • Pytest is able to provide useful exceptions because it implements a mechanism called as assertion rewriting.
  • This works by installing a custom import hook that intercepts the standard python import mechanism. When pytest detects that a test file or plugin is about to be imported, instead of loading the module, it first compiles the source code into abstract syntax tree using the built-in ast module.
  • Then it searches for any assert statements and rewrites them so that variables used in the expression are kept so that they can be used to show more helpful messages if assertion fails and finally it saves the rewritten pyc file to disk for caching
  • Refer Here for more details on the article written by pytest developer of this feature
  • Refer Here for understanding rewriting process

Checking exceptions

  • Refer Here for the changeset containing the exception checking test

  • Exception messages can also be checked

  • Refer Here for the exception message mismatch Preview

  • Fixing the exception message error Preview

  • Refer Here for the changeset with exception message fixed

  • Exercise:

    • Create a python package called as euler
    • In this try to write programs to solve any project euler problems and ensure you have reusable methods or classes
    • Now try to write the tests to test the project euler

Useful Command-line options

  • Often we dont exactly remember the full path or name of a test that you want to execute. At other times, many tests in suite follow similar pattern and you wnat to execute all of them because you have changed some code
  • By using -k <Expression> we can run tests whose id loosely matches the given expression Preview
  • Last failed: Pytest alwasy remembers tests that failed in previous sessiona and can reuse that information to skip to the tests which have failed previously Preview
  • To capture the print statements output we can use -s Preview Preview

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin