模拟整个python类

Ana*_*naF 13 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.")
Run Code Online (Sandbox Code Playgroud)

这是我对执行功能的测试:

@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)
Run Code Online (Sandbox Code Playgroud)

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

fla*_*ini 19

首先,非常重要的是要理解你总是需要模拟你正在尝试模拟的东西,如unittest.mock文档中所述.

基本原则是修改查找对象的位置,该位置不一定与定义对象的位置相同.

接下来,您需要做的是从修补对象返回MagicMock实例return_value.总而言之,您需要使用以下序列.

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

这是一个项目的快速示例.

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

class Connection(object):                                                        
    def execute(self):                                                           
        return "Connection to server made"
Run Code Online (Sandbox Code Playgroud)

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    
Run Code Online (Sandbox Code Playgroud)

测试/ 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) 
Run Code Online (Sandbox Code Playgroud)

  • 这个例子是黄金 (3认同)