如何让nose查找在基测试类上定义的类属性?

2024-10-01 17:42:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在对数据库运行一些集成测试,我希望有一个类似这样的结构:

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测试:

^{pr2}$

或者像这样的所有集成测试:

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的元类,我有一种不安的感觉。在


Tags: thetesttruesql属性objectserverintegration
2条回答

如果您想找到在父类上定义的属性,并且在子类中有一个同名的属性,则需要添加父类的名称才能访问所需的范围

我相信这就是你想要的:

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:在测试函数的顶部,或者在初始化器中

然后说

^{pr2}$

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

我不认为你可以不做自己的插件。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
    ...

你可以通过破解插件来做类似(未测试)的事情。在

^{pr2}$

然而,我不确定这是好是坏的元类选项。在

相关问题 更多 >

    热门问题