代码之家  ›  专栏  ›  技术社区  ›  Blinxen Robᵩ

从另一个类获取方法的输出,并在unittest中进行测试

  •  0
  • Blinxen Robᵩ  · 技术社区  · 7 年前

    def foo():
         print "hello"
    

    现在我转到我的unittest类,在unittest中像这样运行代码。

    def test_code():
         firstClass.foo()
    

    我想测试从控制台获得的输出。我看到一些人使用 subprocess 但在那里,我只能提出论点。所以我的问题是如何从控制台获得输出,以便在unittest类中测试它。

    1 回复  |  直到 7 年前
        1
  •  1
  •   S. Whittaker    7 年前

    一个简单的解决方案是 remap stdout to a file 并在单元测试类中处理方法执行后的文件。

    import sys
    sys.stdout = open('result', 'w')
    
    test_code()
    # read 'result'
    

    或者,您可以使用 StringIO 单元

    import StringIO
    output = StringIO.StringIO()
    sys.stdout = output
    

    例子:

    #!remap.py
    import sys
    import StringIO
    
    backup_sys = sys.stdout # backup our standard out
    output = StringIO.StringIO() # creates file stream for monitoring test result
    sys.stdout = output
    print 'test' # prints to our IO stream
    
    sys.stdout = backup_sys # remap back to console
    print output.getvalue() # prints the entire contents of the IO stream
    

    输出

    test
    

    More details on the module can be found here.