python - 模拟整个 python 类

标签 python unit-testing magicmock

我想在 python 中做一个简单的测试,但我无法弄清楚如何完成模拟过程。

这是类和 def 代码:

class FileRemoveOp(...)
    @apply_defaults
    def __init__(
            self,
            source_conn_keys,
            source_conn_id='conn_default',
            *args, **kwargs):
        super(v4FileRemoveOperator, self).__init__(*args, **kwargs)
        self.source_conn_keys = source_conn_keys
        self.source_conn_id = source_conn_id


    def execute (self, context)
          source_conn = Connection(conn_id)
          try:
              for source_conn_key in self.source_keys:
                  if not source_conn.check_for_key(source_conn_key):    
                      logging.info("The source key does not exist")  
                  source_conn.remove_file(source_conn_key,'')
          finally:
              logging.info("Remove operation successful.")

这是我对执行函数的测试:

@mock.patch('main.Connection')
def test_remove_execute(self,MockConn):
    mock_coon = MockConn.return_value
    mock_coon.value = #I'm not sure what to put here#
    remove_operator = FileRemoveOp(...)
    remove_operator.execute(self)

由于 execute 方法尝试建立连接,我需要模拟它,我不想建立真正的连接,只是返回一些模拟的东西。我该怎么做?我习惯用 Java 做测试,但我从来没有在 python 上做过。

最佳答案

首先,了解您始终需要在您尝试模拟的地方按照 unittest.mock 文档中的说明进行模拟,这一点非常重要。

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.

接下来您需要做的是返回一个 MagicMock 实例作为修补对象的 return_value。因此,为了总结这一点,您需要使用以下序列。

  • 补丁对象
  • 准备要使用的MagicMock
  • 将我们刚刚创建的 MagicMock 返回为 return_value

这里是一个项目的简单示例。

connection.py(我们想要模拟的类)

class Connection(object):                                                        
    def execute(self):                                                           
        return "Connection to server made"

file.py(使用Class的地方)

from project.connection import Connection                                        


class FileRemoveOp(object):                                                      
    def __init__(self, foo):                                                     
        self.foo = foo                                                           

    def execute(self):                                                           
        conn = Connection()                                                      
        result = conn.execute()                                                  
        return result    

tests/test_file.py

import unittest                                                                  
from unittest.mock import patch, MagicMock                                       
from project.file import FileRemoveOp                                            

class TestFileRemoveOp(unittest.TestCase):                                       
    def setUp(self):                                                             
        self.fileremoveop = FileRemoveOp('foobar')                               

    @patch('project.file.Connection')                                            
    def test_execute(self, connection_mock):
        # Create a new MagickMock instance which will be the
        # `return_value` of our patched object                                     
        connection_instance = MagicMock()                                        
        connection_instance.execute.return_value = "testing"

        # Return the above created `connection_instance`                     
        connection_mock.return_value = connection_instance                       

        result = self.fileremoveop.execute()                                     
        expected = "testing"                                                     
        self.assertEqual(result, expected)                                       

    def test_not_mocked(self):
        # No mocking involved will execute the `Connection.execute` method                                                   
        result = self.fileremoveop.execute()                                     
        expected = "Connection to server made"                                   
        self.assertEqual(result, expected) 

关于python - 模拟整个 python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004540/

相关文章:

python - 嵌套列表 Python 3 中的数字平方

python - 有什么区别? (由于多字符串中的前导空格,Python 单元测试失败(?))

javascript - 如何在 Angular 单元测试中模拟警报

javascript - 在 if 语句中调用函数时的 Jasmine 测试用例

python - Unresolved reference MagicMock

Python MagicMock assert_used_once_with 不考虑参数?

python - 如何从 jquery ajax 调用 python 处理程序?

c - 如何使用 FILE* 参数对 C 函数进行单元测试

python - MagicMock 和包装

python - 使用Python ftplib.all_errors处理错误