1 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個贊
在 python 中沒有“開箱即用”的解決方案,盡管我堅信在開發(fā)更高級的測試時能夠模擬和檢查局部變量發(fā)生的情況非常重要。我已經(jīng)用一個新類來模擬一個函數(shù)并獲取本地值,我希望它對你有所幫助。
import inspect
from textwrap import dedent
import re
class MockFunction:
""" Defines a Mock for functions to explore the details on their execution.
"""
def __init__(self, func):
self.func = func
def __call__(mock_instance, *args, **kwargs):
# Add locals() to function's return
code = re.sub('[\\s]return\\b', ' return locals(), ', dedent(
inspect.getsource(mock_instance.func)))
code = code + f'\nloc, ret = {mock_instance.func.__name__}(*args, **kwargs)'
loc = {'args': args, 'kwargs': kwargs}
exec(code, mock_instance.func.__globals__, loc)
# Put execution locals into mock instance
for l,v in loc['loc'].items():
setattr(mock_instance, l, v)
return loc['ret']
要使用它:
import unittest
from unittest import mock
# This is the function you would like to test. It can be defined somewhere else
def foo(param_a, param_b=10):
param_a = f'Hey {param_a}' # Local only
param_b += 20 # Local only
return 'bar'
# Define a test to validate what happens to local variables when you call that function
class SimpleTest(unittest.TestCase):
@mock.patch(f'{__name__}.foo', autospec=True, side_effect=MockFunction(foo))
def test_foo_return_and_local_params_values(self, mocked):
ret = foo('A')
self.assertEqual('Hey A', mocked.side_effect.param_a)
self.assertEqual(30, mocked.side_effect.param_b)
self.assertEqual('bar', ret)
正如我們所見,您可以使用模擬函數(shù)中的 side_effect 檢查局部變量發(fā)生了什么。
添加回答
舉報