如何使用行为测试标准输出



我想使用 python3 创建一个带有 BDD 的 Hello World 命令行应用程序并表现良好。我以这种方式设置了我的功能文件:

Feature: Hello World
  Scenario: the program greets us
    When I start the program
    Then it prints "Hello World!"

在我的features/steps/hello.py中,我的@Then步骤的轮廓是这样的:

from behave import *
@then('it prints "{text}"')
def step_impl(context, text):
    # what goes here???

如何测试程序的输出?如何捕获此测试的标准输出?

检查print输出的典型方法之一是劫持sys.stdout并对其进行分析:

from StringIO import StringIO
import sys
real_stdout = sys.stdout
try:
  mock_stdout = StringIO()
  sys.stdout = mock_stdout
  print "Hi there"
  assert mock_stdout.getvalue() == "Hi there"
finally:
  sys.stdout = real_stdout

当然,try/finally 逻辑可能隐含在您使用的测试框架中。在unittest,它将是setUp/tearDown;我不知道behave但它的文档可能涵盖了它。

这是 9000 用于行为的想法:

我将标准输出重定向到名为 features/environment.py 的文件中的模拟:

import sys
import io
def before_all(context):
    context.real_stdout = sys.stdout
    context.stdout_mock = io.StringIO()
    sys.stdout = context.stdout_mock
def after_all(context):
    sys.stdout = context.real_stdout

然后在features/steps/hello.py中,我断言模拟标准的内容:

@then('it prints "{text}"')
    def step_impl(context, text):
    output = context.stdout_mock.getvalue()
    assertEqual( "Hello World!n", output )

最新更新