【问题标题】:Is it possible to get access to class-level attributes from a nose plugin?是否可以从鼻子插件访问类级属性?
【发布时间】:2013-09-24 18:10:54
【问题描述】:

假设我有以下测试类:

# file tests.py
class MyTests(object):
    nose_use_this = True

    def test_something(self):
        assert 1

我可以轻松编写一个在该测试之前运行的插件:

class HelloWorld(Plugin):
    # snip
    def startTest(self, test):
        import ipdb; ipdb.set_trace()

测试是我想要的,但是test的类型是nose.case.Test

ipdb> str(test)
'tests.MyTests.test_something'
ipdb> type(test)
<class 'nose.case.Test'>

而且我看不到任何可以让我获得在我的 TestCase-ish 类中定义的 nose_use_this 属性的东西。

【问题讨论】:

    标签: python testing plugins nose


    【解决方案1】:

    编辑:

    我认为最好的方法可能是使用 startContext/stopContext 方法对访问上下文,并在那里设置实例的属性:

    class MyPlugin(Plugin):
        def __init__(self, *args, **kwargs):
            super(MyPlugin, self).__init__(self, *args, **kwargs)
            self.using_this = None
    
        def startContext(self, context):
            if hasattr(context, 'nose_use_this'):
                self.using_this = context.nose_use_this
    
        def stopContext(self, context):
            self.using_this = None
    
        def startTest(self, test):
            if self.using_this is not None:
                do_something()
    

    要真正健壮,您可能需要实现一堆东西,因为(至少)模块和类调用了“startContext”,但是如果可以设置属性的唯一位置是在类上,那么我认为这个简单的事情应该有效。它似乎对我有用。 (鼻子 1.3.0 和插件 api 版本 0.10)


    原文:

    哦,这是test 实例上的_context() 函数:

    ipdb> test._context()
    <class 'tests.MyTests'>
    

    而且它确实具有预期的类级属性。我仍然对更好的方法持开放态度,_ 让我觉得鼻子不希望我将其视为 API 的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 2014-07-21
      • 2021-11-05
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多