Reputation: 1511
I recently asked this question and realized that I'd also like to know if there's a way to achieve 'expectation' isolation with assertion-style tests. I've copy and pasted a simple example of what I mean by 'expectation' isolation.
I'm relatively new to Python, coming from Ruby/JavaScript and having testing libraries like Rspec and Jasmine has provided me with the ability to isolate 'expectations' when testing a single function. Since there doesnt seem to be an 'expectation'-style library for Python that is actively maintained, I was wondering if there's a way to achieve an equivalent testing style with either unittest or pytest (the 2 most popular Python testing libraries from what I understand).
foo.py
class Foo():
def bar(self, x):
return x + 1
Expectation-Style/Describe-It
test_foo.py
describe Foo:
describe self.bar:
before_each:
f = Foo()
it 'returns 1 more than its arguments value':
expect f.bar(3) == 4
it 'raises an error if no argument is passed in':
expect f.bar() raiseError
Unittest/assertion-style
test_foo.py
class Foo():
def test_bar(x):
x = 3
self.assertEqual(4)
x = None
self.assertRaises(Error)
Upvotes: 4
Views: 1485
Reputation: 531075
The unittest
module is part of the standard library.
class TestFoo(unittest.TestCase):
def setUp(self):
self.f = Foo()
def test_bar(self):
self.assertEqual(self.f.bar(3), 4)
def test_missing_argument(self):
self.assertRaises(TypeError, self.f.bar())
Upvotes: 1