【问题标题】:Python Mocking - How to patch a variable inside a functionPython Mocking - 如何修补函数内的变量
【发布时间】:2018-11-08 18:05:42
【问题描述】:

我以前从未修补过变量,这有可能吗?代码如下:

脚本.py

import win32gui

def code():
"""
Fetch Window handles by name and set the "test" handle to the foreground
"""

    open_window = False
    top_windows = []

    while open_window == False:

        # Iterate through Window handles and add them into the "top_windows" list
        win32gui.EnumWindows(windowEnumerationHandler, top_windows)

        # Find "test" handle and set it to the foreground then break loop
        for window in top_windows:

            if "test" in window[1]:
                win32gui.ShowWindow(window[0],5)
                win32gui.SetForegroundWindow(window[0])
                open_window = True
                break

            else:     # Keeping looping until "test" handle has loaded and
                pass  # switch to it in the event it hasn't loaded up yet

test_script.py

import code

from unittest.mock import patch

def test_code():

  # Question pertains to this line of code. How would I write it? If possible?
  with patch(~~~ patch top_windows and give it a value of [("dummy","test")]
             so code doesn't loop forever ~~~),\

       patch('code.win32gui.SetForegroundWindow') as patch_1,\
       patch('code.win32gui.ShowWindow) as patch_2,\
       patch('code.win32gui.EnumWindows)as patch_3:

           code()

   assert patch_1.call_count == 1
   assert patch_2.call_count == 2
   assert patch_3.call_count == 3

如果不修补变量“top_windows”,此代码将无限循环。无论如何我可以修补它或某种解决方法?

【问题讨论】:

  • 你不能模拟函数的局部变量。
  • 谢谢!很高兴清楚地知道这是不可能的。

标签: python mocking pytest patch


【解决方案1】:

古怪的修复,但我通过将变量转换为函数来使其工作。

【讨论】:

    猜你喜欢
    • 2022-11-18
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多