🧪 Testing in Python 🐍

May 17, 2022

Joe Riddle

What is "testing"?

Testing is the act of verifying that the code you write runs the way you expect it to.

Code without tests is bad code. It doesn’t matter how well-written it is; it doesn’t matter how pretty or object-oriented or well-encapsulated it is. With tests, we can change the behavior of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse.

- Working Effectively with Legacy Code by Michael Feathers.

Code without tests is bad code. It doesn’t matter how well-written it is; it doesn’t matter how pretty or object-oriented or well-encapsulated it is. With tests, we can change the behavior of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse.

- Working Effectively with Legacy Code by Michael Feathers.

https://spokanepython.com/

The Kevin Bost Slide

  • Think about what you're testing and why
  • Naming, Naming, Naming

Thinking about Testing

Questions to ask yourself:

  • Am I testing boiler-plate code (the framework, stdlib, etc.)?
  • Am I testing implementation logic?

Naming, Naming, Naming

  • UnitOfWork_StateUnderTest_ExpectedBehavior
  • sut = ...
  • actual = ...
  • Arrange, Act, Assert

unittest

  • Class style tests
  • Writing a unit test using unittest:
import unittest

class TestAdd(unittest.TestCase):
  def test_add():
    self.assertEqual(2 + 2, 4)

$ python -m unittest

pytest

  • Function style tests
  • fixtures
  • plugins
  • marks
  • CLI options
  • debugging with VS Code

pytest

  • writing a unit test using pytest:
import pytest

def test_add():
    assert 2 + 2 == 4

$ python -m pytest

Thanks for coming 👋

Ask audience "What does 'testing' mean to you?"

Ask, "What are some other questions to ask yourself when writing tests?"