簡體   English   中英

如何用測試函數內的任意函數替換方法(不使用patch.object)?

[英]How to replace a method with an arbitrary function inside test function (not using patch.object)?

我的嘗試是在具有預定義值的函數中模擬數據庫操作。

我修補了mongo集合實例的find方法,並設置了一個字典列表作為演示返回值(在類似的數據結構中, find return或多或少)。 但是問題是, find返回的內容具有count()方法,該方法不帶任何參數,而我設置的返回值( list )也具有count()方法,但是它帶有參數,其目的也是也不同。

因此,我的目標是更改count()的行為,以使其返回我已硬編碼的列表的len find方法的返回值的len

下面是代碼:

在some_module.py中,

def somefunc():
    items = mongo_collection.find({"some_field": True}).batch_size(50)

    if items.count() > 0:
        counter += 1

在test_some_module.py中,

@patch.object(some_module, 'mongo_collection')
def test_some_func(patched_collection):
    patched_collection.find.return_value.batch_size.return_value = \
                                              [{'id': 1}, {'id': 2}]
    patched_collection.find.return_value.batch_size.return_value.count = ?

尚不清楚您要測試什么。

如果出於某種原因您想要具有類似列表的“ response”並且應將其用作響應(即具有count方法),則應創建此類對象並將其設置為返回值。

現在,您設置[{'id': 1}, {'id': 2}] 通過mongo_collection.find().batch_size()返回此列表后,結果實際上是一個列表,而不是模擬列表。 因此,沒有更多的東西,例如.count = ...

因此,有一些方法可以配合使用:

  1. 測試響應主體和您在不同測試中的數量,對連接器進行修補的方式也不同
  2. 創建更好的響應模擬,即

     class Response(list): def count(self): return len(self) ... patched_collection.find.return_value.batch_size.return_value = Response([{'id': 1}, {'id': 2}]) 
  3. 根據模擬庫的響應將響應模擬創建為實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM