【问题标题】:Python 3.2: Run python programs and create user inputPython 3.2:运行 python 程序并创建用户输入
【发布时间】:2012-08-13 15:01:27
【问题描述】:

好的,所以我想做的是我有一堆只是测试的 python 程序(使用 unittest 库)。我想创建一个 python 程序,它可以背靠背运行每个 python 程序,并在最后给我一份报告(这将是最好的情况),或者如果一个失败就停止运行。

这方面的难点在于每个程序都需要用户输入(简单的 Y 表示是)。如何运行每个 python 程序(我已经运行了executefile("script.py") 命令但尚未对其进行测试),然后插入来自用户的输入(简单的 Y),或者在测试失败时让它停止(更容易)或者最好能够判断哪些失败并在它们全部运行后打印失败的结果和通过的结果。

我还在学习python(自学)很抱歉!

【问题讨论】:

    标签: python python-3.x python-3.2


    【解决方案1】:

    您是否尝试过使用unittest 模块来运行您的所有测试?

    % python -m unittest -h
    Usage: python -m unittest [options] [tests]
    
    Options:
      -h, --help       Show this message
      -v, --verbose    Verbose output
      -q, --quiet      Minimal output
      -f, --failfast   Stop on first failure
      -c, --catch      Catch control-C and display results
      -b, --buffer     Buffer stdout and stderr during test runs
    
    Examples:
      python -m unittest test_module               - run tests from test_module
      python -m unittest module.TestClass          - run tests from module.TestClass
      python -m unittest module.Class.test_method  - run specified test method
    
    [tests] can be a list of any number of test modules, classes and test
    methods.
    
    Alternative Usage: python -m unittest discover [options]
    
    Options:
      -v, --verbose    Verbose output
      -f, --failfast   Stop on first failure
      -c, --catch      Catch control-C and display results
      -b, --buffer     Buffer stdout and stderr during test runs
      -s directory     Directory to start discovery ('.' default)
      -p pattern       Pattern to match test files ('test*.py' default)
      -t directory     Top level directory of project (default to
                       start directory)
    
    For test discovery all test modules must be importable from the top
    level directory of the project.
    

    文档:

    【讨论】:

    • 这会很好,除了每个测试的用户输入部分。我真的在寻找一种方法,这样我就不必通过每个测试(其中有很多)并摆脱那部分。我希望能够运行命令并去做其他事情,而不是必须坐在那里为每个测试插入 y
    • 如果您想对所有脚本回答 yes,可以尝试使用 yes(1) 实用程序:yes | python -m unittest [options]yes Y | python -m unittest [options] ...
    【解决方案2】:

    您可以测试脚本中的函数并绕过需要人工干预的“raw_input”部分。例子:

    你好.py:

    def main():
        print "hello world"
    
    if __name__ == "__main__":
        test = True
        while test:
           test = raw_input() != 'Y'
        main()
    

    test_hello.py:

    import hello
    
    if __name__ == "__main__":
        hello.main()
    

    为了测试python代码,你可以考虑Nose作为单元测试的替代品。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多