簡體   English   中英

如何在python中的方法內部模擬導入

[英]How to mock import inside a method in python

這是一個非常簡單的問題。 如果我在方法中有導入,如何模擬該特定導入? 例如:

def myFunction(self):
    auth_token_path = self.authTokenPath()
    import json

    if os.path.exists(auth_token_path):
      auth_token = json.load(open(auth_token_path, 'r'))
      return auth_token

我該如何模擬這個“導入json”? 有什么辦法可以解決這個問題? 我試圖將其導入測試函數中,但我認為這不是正確的方法(並且也不起作用)。

模擬此功能

def myFunction(self):
auth_token_path = self.authTokenPath()
import json

if os.path.exists(auth_token_path):
  auth_token = json.load(open(auth_token_path, 'r'))
  return auth_token

我們需要做的就是添加與需要模擬的導入功能相關的裝飾器PATCH():

@patch('json.load')
def myFunction(self,json):
auth_token_path = self.authTokenPath()
import json

if os.path.exists(auth_token_path):
  auth_token = json.load(open(auth_token_path, 'r'))
  return auth_token

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM