简体   繁体   English

使用python装饰器装饰功能的一部分

[英]Using python decorator to decorate a part of function

I am trying to mock our git wrapper, so that we can test it. 我正在尝试模拟git包装器,以便我们对其进行测试。 I plan to use mockproc python library which provides the functionality to mock any process name, with a provided script. 我计划使用mockproc python库,该库通过提供的脚本提供模拟任何进程名称的功能。 It works something like this - 它的工作原理如下:

self.scripts.append( 'process-name', returncode=0, stdout="output to process" )
with self.scripts:
        run_and_handle_result()

I need to add a decorator layer over this so that I can do some extra things like handle retries. 我需要在此之上添加一个装饰器层,以便可以做一些额外的事情,例如重试句柄。 What I want is something like this - 我想要的是这样的-

@mockproc('git') # tells that we are mocking git
def test_something(mock_proc):
    mock_proc.set_script("sleep (60)")
    # Run some git command
    mockproc.check_exit_signal()

The problem is I want my decorator to handle the with self.scripts part. 问题是我希望我的装饰器处理with self.scripts部分。 So what I want is that the decorator runs the function, setting the process name as git, which is simple. 所以我想要的是装饰器运行该函数,将进程名称设置为git,这很简单。 Then run the test function, which adds the script and add with self.script around the git command and then resumes the function. 然后运行测试函数,该函数将添加脚本并在git命令周围添加with self.script ,然后恢复该函数。

Is there anyway to do it ? 反正有做吗? is a decorator bad way to implement it ? 装饰器是实现它的坏方法吗? This is not a cosmetic requirement. 这不是化妆品要求。 I need this because in some of my commands there is retry logic, for which I need to provide more than one script to mockproc and run multiple times. 我需要这样做,因为在某些命令中有重试逻辑,为此我需要提供多个脚本来模拟进程并运行多次。

If I understood you correctly, you want to override a named free variable of a function. 如果我对您的理解正确,则希望覆盖函数的命名自由变量。 You can use fun.func_globals[some_name] = some_value . 您可以使用fun.func_globals[some_name] = some_value Eg 例如

def x(a):
    pow2(a)

 x.func_globals['pow2'] = lambda y: y*y

 x(3) == 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM