【问题标题】:Integrating Behave or Lettuce with Python unittest将 Behave 或 Lettuce 与 Python 单元测试集成
【发布时间】:2016-02-09 07:42:20
【问题描述】:

我正在用 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 单元测试的所有优点集成到 Behave 或 Lettuce 中?

【问题讨论】:

  • 我正在使用pytest,它似乎提供了失败时所需的所有上下文信息。无需编写代码打印出来,只需做出断言并让pytest 打印它。我会尝试将 letuce 与 pytest 一起使用,但我没有任何 letuce 或行为测试用例。您能提供一些简短的自包含示例吗?
  • 一个简短的自包含示例可以在 Behave 教程的开头找到:pythonhosted.org/behave/tutorial.html

标签: python lettuce python-behave


【解决方案1】:

nose 包含一个包,该包接受unittest 提供的所有基于类的断言并将它们转换为普通函数,即模块的documentation states

nose.tools 模块提供了 [...] 所有与 unittest.TestCase 相同的 assertX 方法(仅以 PEP 8#function-names 的方式拼写,因此 assert_equal 而不是 assertEqual)。

例如:

from nose.tools import assert_equal

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

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

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

【讨论】:

  • 谢谢。 nose.tools 相当于 unittestself.fail() 是什么?
  • 我不认为nose.tools 直接等同于self.fail()self.fail() 有什么是普通的 assert False, "message" 没有的吗?很明显,self.assertX 方法比普通的assert 更好,因为它们无需编写自定义错误消息即可提供智能诊断信息。我没有看到 self.fail() 的相同优势。
  • fail() 与 assert_x 方法更一致。 fail() 也明确地向维护程序员发出意图。还是谢谢!
猜你喜欢
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
  • 2010-09-21
相关资源
最近更新 更多