访问使用上下文管理器打开的模拟的属性

2024-09-20 04:07:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图模拟一些东西,但一旦用上下文打开模拟,我就无法获得它的属性

# create mocks
mock_1 = MagicMock()
mock_2 = MagicMock()

# set a nested property
type(mock_1.bounds).left = PropertyMock(return_value=-10)
type(mock_2.bounds).left = PropertyMock(return_value= 50)

# at this point I can do less than on the property and it works
mock_1.bounds.left < 50

# setup rasterio mock  open
rasterio_mock = mock_open()
rasterio_mock.side_effect = [mock_1, mock_2]

tiles = []

# add our opened  mocks to list
with patch('rasterio.open', rasterio_mock):
    with ExitStack() as stack:
        tiles.append(stack.enter_context(rasterio.open(f"/vsis3/thing", 'r', driver='GTiff')))
        tiles.append(stack.enter_context(rasterio.open(f"/vsis3/thing", 'r', driver='GTiff')))

        for tile in tiles:
            # same attempt to access the property now  fails :(
            if tile.bounds.left < 50:
                pass
TypeError: '<' not supported between instances of 'MagicMock' and 'int'

我不确定当前如何解决此问题,如何执行<;当模拟的属性像这样打开时,对它的操作是什么?为什么上面的方法不起作用


Tags: return属性valuestacktypepropertyopenleft
1条回答
网友
1楼 · 发布于 2024-09-20 04:07:48

我让它像这样工作,但不确定这是最好的方式,我肯定一定有更好的方式

# create mocks
mock_1 = MagicMock()
mock_2 = MagicMock()

# set a nested property
type(mock_1.bounds).left = PropertyMock(return_value=-10)
type(mock_2.bounds).left = PropertyMock(return_value= 50)

# at this point I can do less than on the property and it works
mock_1.bounds.left < 50

mock_01 = MagicMock()
mock_02 = MagicMock()
mock_01.__enter__.return_value = mock_1
mock_02.__enter__.return_value = mock_2


# setup rasterio mock 
rasterio_mock = mock_open()
rasterio_mock.side_effect = [mock_01, mock_02]

tiles = []

# add our opened  mocks to list
with patch('rasterio.open', rasterio_mock):
    with ExitStack() as stack:
        tiles.append(stack.enter_context(rasterio.open(f"/vsis3/thing", 'r', driver='GTiff')))
        tiles.append(stack.enter_context(rasterio.open(f"/vsis3/thing", 'r', driver='GTiff')))

        for tile in tiles:
            # same attempt to access the property fails
            print(tile.bounds.left)
            if tile.bounds.left > 10:
                pass

相关问题 更多 >