4

我越來越對數據庫運行的一些集成測試,我想有一個看起來像這樣的結構:我怎樣才能找到鼻子來找到在基礎測試類上定義的類屬性?

class OracleMixin(object): 
    oracle = True 
    # ... set up the oracle connection 

class SqlServerMixin(object): 
    sql_server = True 
    # ... set up the sql server connection 

class SomeTests(object): 
    integration = True 
    # ... define test methods here 

class test_OracleSomeTests(SomeTests, OracleMixin): 
    pass 

class test_SqlServerSomeTests(SomeTests, SqlServerMixin): 
    pass 

這樣一來,我可以運行SQL Server的測試和Oracle分別測試,如這樣的:

nosetests -a oracle 
nosetests -a sql_server 

或者全部集成測試是這樣的:

nosetests -a integration 

然而,似乎鼻子只會尋找ATTRIB utes在子類上,而不在基類上。因此,我必須定義的測試類這樣或測試將不會運行:

class test_OracleSomeTests(SomeTests, OracleMixin): 
    oracle = True 
    integration = True 

class test_SqlServerSomeTests(SomeTests, SqlServerMixin): 
    sql_server = True 
    integration = True 

這是一個有點乏味維護。任何想法如何解決這個問題?如果我只是在處理一個基類,那麼我只需使用一個元類並在每個類上定義屬性。但是我對測試類的元類,Oracle的元類和SQL Server的元類感到不安。

回答

4

我不認爲你可以沒有自己的插件。 attrib插件中的代碼僅查看類__dict__。這裏是code

def wantClass(self, cls): 
    """Accept the class if the class or any method is wanted. 
    """ 
    cls_attr = cls.__dict__ 
    if self.validateAttrib(cls_attr) is not False: 
     return None 
    ... 

你可以破解插件做類似(未測試)。

def wantClass(self, cls): 
    """Accept the class if the class or any method is wanted. 
    """ 
    for class_ in cls.__mro__: 
     cls_attr = class_.__dict__ 
     if self.validateAttrib(cls_attr) is not False: 
      return None 
    cls_attr = cls.__dict__ 
    ... 

但是,我不確定這是好還是差的元類選項。

+0

如果您的父類是不是「新風格」類(即它們不擴展「對象」),我不認爲會有`__mro__`屬性。 只是一個小小的調整,但改變了行 'class_ ...' 到 `在class getattr(cls,'__mro__',[]):``` – 2009-11-12 16:50:33

0

如果你想找到一個父類中定義的屬性,你必須在子類中相同名稱的屬性,你將需要添加父類的名稱來訪問你想要

範圍我相信這是你想要什麼:

class Parent: 
    prop = 'a property' 

    def self_prop(self): 
     print self.prop 

    # will always print 'a property' 
    def parent_prop(self): 
     print Parent.prop 

class Child(Parent): 
    prop = 'child property' 

    def access_eclipsed(self): 
     print Parent.prop 

class Other(Child): 
    pass 

>>> Parent().self_prop() 
"a property" 
>>> Parent().parent_prop() 
"a property" 
>>> Child().self_prop() 
"child property" 
>>> Child().parent_prop() 
"a property" 
>>> Child().access_eclipsed() 
"a property" 
>>> Other().self_prop() 
"child property" 
>>> Other().parent_prop() 
"a property" 
>>> Other().access_eclipsed() 
"a property" 

,並在你的情況下,它看起來像你有定義不同變量的兩個不同的類,所以你可以試試:捕捉:在您的測試功能頂部或者可能在初始化程序中

try: 
    isSQLServer = self.sql_server 
except AttributeError: 
    isSQLServer = False 

(但實際上它們應該被定義相同的變量,以便測試類不知道子類的任何東西)

相關問題