2016-07-14 54 views
0

我觉得这应该是一个简单的模拟,但我还没有得到它的工作。功能补丁不被进口模块拾取

我工作过以下目录结构:

module 
├── utilities.py 
├── order.py 
├── test 
│ ├── test_order.py 

相关的代码如下:

- utilities.py -

def get_file_path(order_number, file_extension): 
    # this is what I want to mock out 

- 秩序。 py -

from module.utilities import get_file_path 

class Order(): 
    # ... 

    @classmethod 
    def load_order(order_number, extension): 
     file_path = get_file_path(order_number, extension) 

- test_order.py -

import unittest 
from unittest.mock import patch 
from module.order import order 

@patch('order.get_file_path') 
def mock_file(_, extension): 
    if extension == 'json': 
     return static_file_path 

class TestOrder(unittest.TestCase): 
    def test_load_order_by_number(self): 
     my_order = order.load_order(number, extension) 

这是我第一次尝试在Python中进行模拟。据我所知,我有什么应该工作,但每当Order调用get_file_path时,它总是使用utilities.py中的那个。

我曾尝试:

  • 装饰test_load_order_by_number
  • module.order.get_file_path

修补我那么看好,但没有我发现帮助解决的,所以我想我只是做一些明显错误的事情,有人可以指出。

回答

0

它看起来不像是在课堂外创建补丁正在被拾起。当我将修补程序作为特定测试的修饰器运行时,它开始工作。

class TestOrder(unittest.TestCase): 

    @patch('utilities.order.get_file_path') 
    def test_load_order_by_number(self, file_mock): 

     def mock_get_file_path(*args, **kwargs): 
      if kwargs.get('extension', None) == 'json': 
       return static_file_path 
      return None 

     file_mock.side_effect = mock_get_file_path 

     my_order = order.load_order(number, extension)