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  for assertions, since I picked up Hamcrest recently while working a Java project. It is a great tool and I highly recommend it.
 PyHamcrest – https://pyhamcrest.readthedocs.org/en/latest/tutorial/
About the Author