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

但是,nose 似乎只会在子类上查找属性,而不是在基类上。因此我必须像这样定义测试类,否则测试将无法运行:

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

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

维护起来有点繁琐。任何想法如何解决这个问题?如果我只是处理一个基类,我只需使用一个元类并定义每个类的属性。但是对于测试类的元类、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"

在您的情况下,您似乎有两个不同的类,它们定义了不同的变量,因此您可以尝试一下: catch: 在测试函数的顶部或在初始化程序中

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

(尽管实际上它们应该定义相同的变量,以便测试类不必知道有关子类的任何信息)

于 2009-07-27T22:11:54.433 回答