python > pytest, ptw (watch mode) and setting up unit testing for python

abstract

The concern is documenting finding the unit test framework similar to jest for javascript.

1. pytest

  • install
pip install -U pytest
pytest --version
pytest 6.0.1

2. pytest-watch

  • install pytest-watch to enable tehe watch mode for pytest, i.e. make pytest run each time you save the file in the watched folder
pip install pytest-watch
ptw --version
pytest-watch 4.2.0

3. test1: code & test in the same file

  • create a file *_test.py and write a first function & corresponding test
  • run ptw to run pytest in a watch mode
def func(x):
return x + 1

def test_answer():
assert func(3) == 4
Image for post
Image for post

4. test2: import sourcefile into testfile

import addition

def test_answer1():
input = 4 # arrange
result = addition.func(input) # act
assert result == 8 # assert

debug: use vscode

  • python extension needs to be activated
  • run Python > configure tests to select testing framework and folder with files (no drill-down here)
  • open the file (here both source and test in a single file)
  • set a breakpoint and click on Debug test in the file → do not run debugger with f5 or from the sidebar
Image for post
Image for post

Written by

today I learnt… | as a support eng of the wonderful Snowplow Analytics, expect everything around modern (postmodern?) business intelligence

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store