Python中是否有首选的BDD风格单元测试框架?
我在想,Python有没有那种BDD风格的“描述-测试”单元测试框架,既能维护又能用于生产环境。我找到过一个叫describe的框架,但它似乎没有在维护,而且没有文档。我还发现了sure,它已经到了1.0版本,但看起来只是增加了一些语法糖,而不是在写断言。我真正想要的是类似于RSpec和Jasmine的东西,这样我就可以设置测试套件。描述-测试的语法可以让我测试一个函数的多个情况。而传统的断言结构是每个函数只测试一次,并且有多个断言来测试多个情况。这就打破了单元测试的独立性。如果有办法用断言风格的测试实现类似的效果,我会很感激任何建议。下面是这两种风格的简单示例:
foo.py
class Foo():
def bar(self, x):
return x + 1
BDD风格/描述-测试
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
单元测试/断言风格
test_foo.py
class Foo():
def test_bar(x):
x = 3
self.assertEqual(4)
x = None
self.assertRaises(Error)
2 个回答
1
如果你期待在Python中能找到和rspec/capybara完全一样的东西,那我得告诉你,可能会让你失望。问题在于,Ruby给你提供的自由度比Python要大得多(它对开放类和元编程的支持也更广泛)。我必须说,Python和Ruby在理念上有根本的区别。
不过,如果你在找纯Python的解决方案,还是有一些不错的测试框架,比如Cucumber(https://github.com/cucumber/cucumber/wiki/Python)和lettuce(http://lettuce.it/)。
2
我自己也在寻找这个,发现了 mamba。它和流畅的断言库 expects 结合使用,可以让你在Python中写出像BDD风格的单元测试,代码看起来像这样:
from mamba import describe, context, it
from expects import *
with describe("FrequentFlyer"):
with context("when the frequent flyer account is first created"):
with it("should initially have Bronze status"):
frequentFlyer = FrequentFlyer()
expect(frequentFlyer.status()).to(equal("BRONZE"))
用文档格式运行这些测试会给你一个类似Jasmine的测试报告:
> pipenv run mamba --format=documentation frequent_flyer_test.py
FrequentFlyer
when the frequent flyer account is first created
✓ it should initially have Bronze status
1 example ran in 0.0345 seconds