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

ただし、鼻は基本クラスではなく、サブクラスの属性のみを検索するようです。したがって、次のようにテスト クラスを定義する必要があります。そうしないと、テストが実行されません。

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

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

これを維持するのは少し面倒です。これを回避する方法はありますか?1 つの基本クラスだけを扱う場合は、メタクラスを使用して、各クラスの属性を定義します。しかし、テスト クラス用のメタクラス、Oracle 用のメタクラス、SQL Server 用のメタクラスがあることに不安を覚えます。

4

2 に答える 2

4

独自のプラグインを作成せずにできるとは思いません。attribプラグインのコードは、クラスのみを調べます__dict__。これがコードです

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__
    ...

ただし、これがメタクラスオプションよりも優れているか悪いかはわかりません。

于 2009-07-27T17:30:59.057 に答える
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: catch: を実行するだけです

そして、言います

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

(実際には、テストクラスがサブクラスについて何も知る必要がないように、同じ変数を定義する必要があります)

于 2009-07-27T22:11:54.433 に答える