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を探しますことが表示されますベースクラスではなく、サブクラス上にあります。したがって、このようなテストクラスを定義するか、テストが実行されません。

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

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

これは少し面倒です。これを回避する方法は? 1つの基本クラスを扱っていただけの場合は、メタクラスを使用して各クラスの属性を定義します。しかし、テストクラスのメタクラス、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__'属性があるとは思わない。 getattr(cls、 '__mro__'、[])のclass_のために 'for class_ ...' 〜' –

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" 

とあなただけ試してみることができますので、あなたが別の変数を定義する2つの異なるクラスを持っているようなあなたの場合にはそれが見えます:キャッチ:あなたのテスト機能の上部にはまたは初期化プログラムの中で

と言う

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

あなたの親クラスのいずれかがある場合

関連する問題