是否可以在Django Behave测试中进行模拟?

时间:2016-07-20 12:53:06

标签: python django mocking python-mock python-behave

我看过很多关于单元测试的文章。

我有一个简单的结帐表单,可以将卡详细信息提交给付款网关。是否可以在Behave tests中模拟支付网关响应?

@then(u'I submitted checkout form')
def submit_checkout_form(context):
    "Mock your response Do not send/post request to payment gateway, but create order"

@then(u'I see my order successfully created')
def inspect_order_page(context):
    "Thank you page: check product & price"

我想知道,是否有可能在Behave测试中进行模拟?

2 个答案:

答案 0 :(得分:1)

确定是!

如果您只需要在该步骤的过程中模拟某些东西,则可以 使用mock.patch

# features/steps/step_submit_form.py
from mock import patch

@when(u'I submitted checkout form')
def submit_checkout_form(context):
    with patch('payment.gateway.pay', return_value={'success': True}, spec=True):
        form.submit(fake_form_data)

如果您需要为每种情况模拟某些东西,则可以在 environment.py,使用生命周期功能:

# features/environment.py
from mock import Mock, patch

def before_scenario(context, scenario):
    mock_payment_gateway = Mock()
    mock_payment_gateway.pay.return_value = {'success': True}
    patcher = patch('payment.gateway', mock_payment_gateway)
    patcher.start()
    context.payment_patcher = patcher

def after_scenario(context, scenario):
    context.payment_patcher.stop()

如果您只想针对特定情况进行模拟,则可以创建一个 设置模拟的特殊步骤,然后在生命周期中删除 功能:

# features/steps/step_submit_form.py
from behave import given, when, then
from mock import patch, Mock

@given(u'the payment is successful')
def successful_payment_gateway(context):
    mock_payment_gateway = Mock()
    mock_payment_gateway.pay.return_value = {'success': True}
    patcher = patch('payment.gateway', mock_payment_gateway)
    patcher.start()
    context.patchers.append(patcher)

@when(u'I submitted checkout form')
def submit_checkout_form(context):
    form.submit(fake_form_data, payment.gateway)

@then(u'I see my order successfully created')
def inspect_order_page(context):
    check_product()

environment.py中的每个方案之后都删除补丁:

# features/environment.py

def before_scenario(context, scenario):
    context.patchers = []

def after_scenario(context, scenario):
    for patcher in context.patchers:
        patcher.stop()

答案 1 :(得分:0)

您可以尝试:

@then(u'I submitted checkout form')
def submit_checkout_form(context):
    with mock.patch('path.module', mock.Mock(return_value=None)):
        **type here**