Searching for BDD patterns in Python

March 3, 2015 Adam Berlin

I’ve been writing automated tests in a Test Driven Development style for about 6 years now. Much of my experience comes from working in frameworks like rspec in Ruby, mocha in Node.js, or jasmine for client-side Javascript. These frameworks have methods to provide context for a test.

    describe "some instance" do
      context "when the the instance is in this state" do
        it "behaves like this" do

For the last six months, I’ve been working with Python. My team has a pre-existing codebase with established testing tools. We’re using Python’s standard unittest library as well as Nosetests, which sets up test suites easily and has many useful plugins. While these are great tools, I’ve found myself missing ‘describe’, ‘context’, and ‘it’. The unittest library is a standard xUnit-style testing tool.

After plenty of experimentation, I’ve settled on this pattern:

    from unittest import TestCase

    from mypackage import MyClass

    class TestWhenAnInstanceIsInThisState(TestCase):
        def setUp(self):
            self._my_instance = MyClass(

        def test_it_behaves_like_this(self):
            # some assertions

I’ve explored other styles and frameworks, but this is where I’ve landed. I’d love to be told that there is a better way to do this style of BDD in Python. So, if you have opinions, please share. Are there other patterns from other languages that use xUnit style testing that help with these BDD style tests?

Note: I’ve been using pyhamcrest [1] for assertions, since I picked up Hamcrest recently while working a Java project. It is a great tool and I highly recommend it.

[1] PyHamcrest –

About the Author


Pivotal’s Big €100M Investment In Ireland
Pivotal’s Big €100M Investment In Ireland

Today, alongside Ireland’s prime minister, the Taoiseach, Enda Kenny TD, and the Minister for Jobs, Enterpr...

How To Build a Hardware Cluster for Pivotal Greenplum Database
How To Build a Hardware Cluster for Pivotal Greenplum Database

In this post, R&D Platform Engineer, Scott Kahler, explains the ins and outs of selecting hardware to build...

SpringOne 2021

Register Now