将 Behave 或 Lettuce 与 Python unittest 集成

Integrating Behave or Lettuce with Python unittest

我正在使用 Python 研究 BDD。验证结果是一个拖累,因为正在验证的结果不会在失败时打印出来。

比较行为输出:

AssertionError: 
  File "C:\Python27\lib\site-packages\behave\model.py", line 1456, in run
    match.run(runner.context)
  File "C:\Python27\lib\site-packages\behave\model.py", line 1903, in run
    self.func(context, *args, **kwargs)
  File "steps\EcuProperties.py", line 28, in step_impl
    assert vin == context.driver.find_element_by_xpath("//table[@id='infoTable']/tbody/tr[4]/td[2]").text

到 SpecFlow+NUnit 输出:

Scenario: Verify VIN in Retrieve ECU properties -> Failed on thread #0
    [ERROR]   String lengths are both 16. Strings differ at index 15.
  Expected: "ABCDEFGH12345679"
  But was:  "ABCDEFGH12345678"
  --------------------------^

使用 SpecFlow 输出可以更快地查找故障原因。要获取错误的变量内容,必须手动将它们放入字符串中。

来自Lettuce tutorial

assert world.number == expected, \
    "Got %d" % world.number

来自Behave tutorial

if text not in context.response:
    fail('%r not in %r' % (text, context.response))

将此与 Python unittest 进行比较:

self.assertEqual('foo2'.upper(), 'FOO')

导致:

Failure
Expected :'FOO2'
Actual   :'FOO'
 <Click to see difference>

Traceback (most recent call last):
  File "test.py", line 6, in test_upper
    self.assertEqual('foo2'.upper(), 'FOO')
AssertionError: 'FOO2' != 'FOO'

但是,Python unittest 中的方法不能在 TestCase 实例之外使用。

是否有一种好的方法可以将 Python unittest 的所有优点集成到 Behave 或 Lettuce 中?

nose includes a package that takes all the class-based asserts that unittest provides and turns them into plain functions, the module's documentation states:

The nose.tools module provides [...] all of the same assertX methods found in unittest.TestCase (only spelled in PEP 8#function-names fashion, so assert_equal rather than assertEqual).

例如:

from nose.tools import assert_equal

@given("foo is 'blah'")
def step_impl(context):
    assert_equal(context.foo, "blah")

您可以将自定义消息添加到断言中,就像使用 unittest.assertX 方法一样。

这就是我 运行 使用 Behave 的测试套件所使用的。