为 nbgrader 中的后续自动评分器测试捕获自动评分答案的输出

Capture output of autograded answer for subsequent autograder tests in nbgrader

我正在尝试使用 nbgrader 自动化 autograding。通常学生在教师使用的 autograded answer 单元格中编写一段代码(如 variablefunction)(通过参考 variablefunction) 写入 autograder tests.

但有时来自 autograded answer 单元格的输入代码可能只是一个 print(...) 输出到屏幕的东西(而不是 variablefunction) .在那种情况下,如何 捕获 打印输出,以便我们可以在下一个单元格上使用它来写入 autograder tests

nbgrader 文档 include an example 演示了如何修补内置函数 print 以便您可以捕获和测试打印输出:

Problem: verify that a function call results in the printing of a certain result

def foo()
    #...
    print('right result')

The test code for this can be written as

from unittest.mock import patch
with patch('__main__.print') as mock_print:
    foo()

mock_print.assert_called_once_with('right_result')

This test passes silently if the print is correct, but if the print is wrong:

def foo()
    #...
    print('wrong result')

an assertion error is raised with output of the form

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
...

AssertionError: Expected call: print('right result')
Actual call: print('wrong result')