2016-11-24 94 views
0

請原諒我的noob地位,但我遇到了一個我不太瞭解的構造,希望有人能爲我解釋。嘲諷繼承方法

class Base(object): 
    def mogrify(self, column): 
     return self.mogrifiers.get(column.lower().strip()) or (lambda x: x) 

...

class MyClass(some.package.Base): 
    def mogrifiers(self): 
     return { 
      'column1': (lambda x: datetime.datetime.fromtimestamp(int(x))) 
     } 

...

class MyOtherClass(object): 
    def convert_columns: 
     ... 
     new_row[colkey] = self.myclass.mogrify(colkey)(value) 

這一切工作,但我試圖寫一個單元測試,並模擬出MyClass

據我所知,mogrifiers返回所有列和任何所需的轉換字典。

我正在測試的代碼調用mogrify(從Base類繼承)與字符串中的特定列名稱。

這試圖從字典中提取列並返回lambda函數?或者如果它不存在於字典中,它會返回一個只給出字符串的lambda表達式?

所以,我只是在我試圖測試的代碼中留下了(值)位。目前尚不清楚它的功能。

如果我不想測試底層的轉換/轉換,我的模擬可能會返回簡單的lambda。

所以我這樣做,但將在電話會議上的例外mogrify說:

E TypeError: 'str' object is not callable

任何人都可以提供一些線索什麼,我在這裏失蹤?

回答

0

As far as I can tell, mogrifiers returns a dictionary of all the columns and any transformations that are required.

這是正確的,但正如你已經表明它會創建一個新的字典,每次看起來沒有必要。

The code I am testing calls mogrify (inherited from the Base class) with a specific column name in a string.

This tries to extract the column from the dictionary and returns the lambda function ? or if it doesn't exist in the dictionary, it returns a lambada that just gives the string back ?

是的,這也是正確的(除了拉姆達達是一個舞蹈,但我認爲你的意思是再次拉姆達)。

So that just leaves me with the (value) bit in the code I'm trying to test. It's no clear what it does.

呼叫self.myclass.mogrify(colkey)返回Callable的(value)簡單地調用它。

fn = self.myclass.mogrify(colkey) 
new_row[colkey] = fn(value) 

拆分成兩行也將使其更清晰的問題是否與呼叫self.myclass.mogrify(colkey)fn(value):如果我重寫這樣可能更清晰。如果看起來很可能是fn(value)這意味着你的模擬mogrify返回str而不是返回一個可調用的;但它可能是,你得到了模擬錯誤和嘲笑mogrify方法實際上是一個字符串。

我建議你重寫如圖所示,並在兩行之間插入一個print,看看實際返回的是什麼。