2012-02-08 45 views
17

我有沿的線條抽象基類:排除abstractproperties報告

class MyAbstractClass(object): 
    __metaclass__ = ABCMeta 

    @abstractproperty 
    def myproperty(self): pass 

但是當我運行nosetests(該報道)在我的項目,它抱怨該財產的防線是未經測試。它不能實際上進行測試(據我所知)爲抽象類會導致被引發異常的實例..

有什麼解決方法嗎,或者我只是不得不接受< 100%的測試覆蓋率?

當然,我可以刪除ABCMeta使用和簡單的讓基類提高NotImpementedError,但我更喜歡前一種方法。

回答

21

沒有辦法精確排除抽象屬性,但如果稍作改動,您可以。讓您的抽象屬性產生錯誤:

@abstractproperty 
def myproperty(self): 
    raise NotImplementedError 

然後,您可以指示coverage.py忽略引發NotImplementedError的行。創建一個.coveragerc文件,並在其中提出:

[report] 
exclude_lines = 
    # Have to re-enable the standard pragma 
    pragma: no cover 

    # Don't complain if tests don't hit defensive assertion code: 
    raise NotImplementedError 

有關種你可能要經常忽略的行更多的想法,請參見:http://nedbatchelder.com/code/coverage/config.html

+0

我最終發現了關於IRC上的#pragma:no cover的問題,並在內聯中進行了討論。我不喜歡在抽象屬性中實現一個實現(即使它只是'提升NotImplementedError',因爲它似乎擊敗了目的)。 – 2012-02-09 20:50:32

+3

等待:您可以在每個抽象屬性上放置「#pragma:no cover」評論,但是您將身體從pass改爲「raise NotImplementedError」還不行嗎?對於他自己,我猜...很高興你找到了你喜歡的解決方案。 – 2012-02-09 21:06:46

+0

我絕對同意這不是一個最佳的解決方案,但我更喜歡使用這樣的內聯指令來改變抽象基類模塊的預期用途和好處。 – 2012-02-09 21:53:00

22

對我來說,最好的解決辦法是什麼@Wesley提到在他的接受的答案評論,特別是更換與抽象屬性文檔字符串「通行證」,如:

class MyAbstractClass(object): 
    __metaclass__ = ABCMeta 

    @abstractproperty 
    def myproperty(self): 
     """ this property is too abstract to understand. """ 
1

我有自定義的邏輯跳躍在我.coveragerc

[report] 
exclude_lines = 
    pragma: no cover 
    @abstract 

這樣所有的abstractmethods和abstractproperties被標記爲跳過。