模拟整个python类

AnaF:

我正在尝试在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.")

这是我对execute函数的测试:

@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上做过。

flazzarini:

首先,非常重要的一点是要了解,您总是需要在要模拟的东西用于unittest.mock文档说明的地方进行模拟

基本原理是,您可以在查找对象的位置打补丁,而该对象不一定与定义对象的位置相同。

接下来,您需要做的是从修补对象中返回一个MagicMock实例return_value因此,总结一下,您将需要使用以下顺序。

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

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

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

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

file.py(使用类的地方)

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    

测试/ 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) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章