Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生产代码中的模拟方法,而不是测试中的模拟方法_Python_Mocking - Fatal编程技术网

Python 生产代码中的模拟方法,而不是测试中的模拟方法

Python 生产代码中的模拟方法,而不是测试中的模拟方法,python,mocking,Python,Mocking,我的代码中有这样一个方法: def save(items): try: for item in items(): do_something(item) except Exception: my_logging.warning("error happened") def do_something(item): pass 我想从代码中的另一个位置调用此方法,但是,我想调用另一个方法,而不是do\u something(item):

我的代码中有这样一个方法:

def save(items):
   try:
       for item in items():
          do_something(item)
   except Exception:
      my_logging.warning("error happened")

def do_something(item):
   pass
我想从代码中的另一个位置调用此方法,但是,我想调用另一个方法,而不是
do\u something(item)

@transaction.atomic
def do_with_transaction(item)
   delete(item)
   do_something(item)

对生产代码使用带有副作用的mock可以吗?这样我就可以模拟
do\u something()
使用
do\u处理事务(项目)

在我看来,这是一个干净的解决方案。

如果您希望重用
保存(项)
但调用另一个函数(而不是
for
循环中的
do\u something()
,只需将所需函数作为参数传递即可:

def save(items, callback=do_something):
   for item in items():
       try:
          callback(item)
       except Exception as e:
          my_logging.exception("error %s happened on item %s", e, item)
然后:

save(items, do_something_with_transaction)

这不是一个很糟糕的实践和设计决策吗?这就是我想要找到的。你的代码应该很容易阅读,做这样的事情(特别是在产品源代码中)听起来你会让未来的代码读者/维护者感到困惑,但这只是我的2美分“对生产代码使用带有副作用的模拟可以吗?”:不,绝对可以。