2

我使用一个简单的命令用鼻子运行我的测试:

@manager.command
def test():
    """Run unit tests."""
    import nose
    nose.main(argv=[''])

但是,nose 支持许多现在我无法通过的有用论点。

有没有办法使用管理器命令运行鼻子(类似于上面的调用)并且仍然能够将参数传递给鼻子?例如:

python manage.py test --nose-arg1 --nose-arg2

现在我会得到一个错误,Manager--nose-arg1 --nose-arg2不被识别为有效参数。我想将这些参数传递为nose.main(argv= <<< args comming after python manage.py test ... >>>)

4

3 回答 3

4

在您的来源中flask_script可以看到,"too many arguments"当执行Command的属性capture_all_args设置True为未在任何地方记录的属性时,可以防止错误。

您可以在运行管理器之前在类上设置该属性

if __name__ == "__main__":
    from flask.ext.script import Command
    Command.capture_all_args = True
    manager.run()

像这样向经理提供的额外参数总是被接受的。

此快速修复的缺点是您无法再以正常方式向命令注册选项或参数。

如果您仍然需要该功能,您可以像这样子类化Manager并覆盖command装饰器

class MyManager(Manager):
    def command(self, capture_all=False):
        def decorator(func):
            command = Command(func)
            command.capture_all_args = capture_all
            self.add_command(func.__name__, command)

            return func
        return decorator

然后你可以command像这样使用装饰器

@manager.command(True)  # capture all arguments
def use_all(*args):
    print("args:", args[0])

@manager.command()  # normal way of registering arguments
def normal(name):
    print("name", name)

请注意,由于某种原因flask_script需要use_all接受可变参数,但会存储参数列表,args[0]其中有点奇怪。def use_all(args):不起作用并且失败TypeError "got multiple values for argument 'args'"

于 2016-02-10T14:51:52.803 回答
4

Flask-Script 有一个未记录的capture_all_flags标志,它将把剩余的参数传递给Command.run方法。这在测试中得到证明。

@manager.add_command
class NoseCommand(Command):
    name = 'test'
    capture_all_args = True

    def run(self, remaining):
        nose.main(argv=remaining)
python manage.py test --nose-arg1 --nose-arg2
# will call nose.main(argv=['--nose-arg1', '--nose-arg2'])
于 2016-02-10T14:56:17.180 回答
0

遇到了 davidism 的问题,只收到了一些 args

再看一下文档,据记载,nose.main 会自动获取标准输入

http://nose.readthedocs.io/en/latest/api/core.html

所以我们现在只使用:

@manager.add_command
class NoseCommand(Command):
    name = 'nose'
    capture_all_args = True

    def run(self, remaining):
        nose.main()
于 2016-11-22T21:11:23.153 回答