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
        end
      end
    end


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(
                setup='some-state',
            )

        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 – https://pyhamcrest.readthedocs.org/en/latest/tutorial/

About the Author

Biography

More Content by Adam Berlin
Previous
All Things Pivotal Podcast Episode #18: An Introduction to HAWQ
All Things Pivotal Podcast Episode #18: An Introduction to HAWQ

What if you could have the efficiency and scale of HDFS with the mature ecosystem of SQL? What if you could...

Next
Visualizing project metadata
Visualizing project metadata

I recently prepared an experience report which included some graphs illustrating key points about the engag...

Enter curious. Exit smarter.

Learn More