Fake It Til You Make It: Unit Testing Patterns With Mocks and Fakes

Type:
Talk
Audience level:
Intermediate
Category:
Best Practices/Patterns
March 9th 3:20 p.m. – 4:05 p.m.

Description

In this talk, aimed at intermediate Pythonistas, we'll have a look at some common, simple patterns in code, and the testing patterns that go with them. We'll also discover what makes some code more testable than others, and how mocks and fakes can help isolate the code to be tested (and why you want to do that). Finally, we'll touch on some tools to help make writing and running tests easier.

Abstract

Overview

You've heard the gospel of 'test, test, test!' over and over again, and may have even felt some jealousy or guilt because you're not using Test-Driven Development. Maybe you've even seen talks or read blog posts about writing 'testable code', but it just hasn't sunk in.

The reality is that writing effective unit tests can be somewhat difficult to wrap your head around. What's a unit test? When is a unit test not a unit test? What's a functional test? When is a Mock really a fake or stub? There's a good bit of lingo, a fair amount of religion, but not enough instruction on effective testing patterns and idiomatic, Pythonic testing practices.

As programming and application architecture is heavily influenced by the use of patterns, it's only logical that those patterns produce the side effect of making the way they'll be tested more predictable, and yet discussions of patterns regularly leave out coverage of testing, and most testing talks fail to link a methodology to patterns in the code. This changes now.

In this talk, aimed at intermediate Pythonistas, we'll have a look at some common, simple patterns in code, and then have a look at the testing patterns that go with them. We'll also discover what makes some code more testable than others, and how mocks and fakes can help truly isolate the code to be tested (and why you really want to do that). Finally, we'll touch on some tools to help make writing and running tests easier.

Outline

What is a unit test? (3 minutes)

  • Unit Test definition
  • Unit tests vs. functional, integration, and acceptance tests

Why Unit Tests? (3 minutes)

  • "Why isolate the code?" (I get this question a lot)
  • "But, I use functional tests & have 100% coverage!"

Three pieces of code, and how to make it more testable. (8 minutes)

Patterns in code, patterns in tests (15 minutes)

  • A Simple datetime abstraction library, its patterns and tests.
  • A REST Client Module, its patterns and tests
  • A cmd-module-based command shell, its patterns and tests
  • A microframework-based service, its patterns and tests

Tools You Want to Use (5 minutes)

  • Mock
  • Nose
  • Coverage
  • Tox
  • TBD (Possibly PyCharm's test support, which is getting good w/ 2.0, but there are many candidates)