无法修补功能的功能

时间:2015-08-05 21:55:41

标签: python mocking monkeypatching

我对修补很新,我遇到了一些我不知道如何修补的东西。基本上,在我想测试的文件中,有方法difficult_method()。它看起来有点像这样:

from import_location import User

def difficult_method():
  ids = list_of_ids
  for id in list_of_ids:
    try:
      user = User.query.filter(User.id == user_id).all()[0]
    except:
      continue
    #do lots of stuff

我想要模拟的代码是User.query.filter(User.id == user_id).all(),就我而言,它可以返回一个静态列表。我将如何在代码中替换该行:

from mock import patch

@patch(#what would go here?)
def test_difficult_method(): 
  from file_to_test import difficult_method
  assert difficult_method() returns ...

1 个答案:

答案 0 :(得分:0)

我明白了!关键是要创建一个MockUser类,如下所示:

user = #creating a user

class MockFilter(object):
  def all(self):
    return [user]


class MockQuery(object):

  def filter(self, match):
    return MockFilter()


class MockUser(object):
  query = MockQuery()
  id = '2'

然后我就这样打补丁:

from mock import patch

@patch('import_location.User', MockUser)
def test_difficult_method(): 
  from file_to_test import difficult_method
  assert difficult_method() returns ...