如何对流生成器进行单元测试

时间:2018-12-11 18:36:01

标签: python unit-testing flask generator

我正在为我的烧瓶应用程序设置单元测试。我的很多函数都像这样将输出流传输到gui:

def stream():
    def generate():
        if request.method == "POST":
            hostname = request.data.decode('utf-8')
            hostname_dn = "{}.{}".format(hostname, DOMAIN)

            logging.info("Connecting to: {}".format(hostname_dn))

            # Connect to hostname and execute create reports
            client = set_up_client()
            client.connect(hostname_dn,
                           username=USERNAME,
                           password=PASSWORD)

            cmd = ('tail -f -n0 /home/server.log')

            stdin, stdout, stderr = client.exec_command(cmd)

            for line in iter(lambda: stdout.readline(2048), ""):
                logging.info(line, end="")
                yield line
                if re.search(r'keyword', line):
                    yield 'keyword detected\n'
                    break

    return Response(stream_with_context(generate()), mimetype='text/html')

我的问题是如何使用assert语句来验证这些功能?由于它们返回流响应。有没有办法让我在return语句中添加一个额外的参数(例如200),或者使用assert来验证流是否成功?

1 个答案:

答案 0 :(得分:1)

对于您而言,您应该测试stream函数的工作方式。因此,我建议隔离(模拟)与它无关的所有内容并测试其行为。因此,模拟Response对象并遍历一个生成器:

@patch("Response")
def test_stream(self, response_mock):
    # this should return invoked Response mock, 
    # so you need to retrieve a first argument
    res = stream()
    args, _ = res.call_args
    stream_gen = args[0]
    n_runs = 0
    for i in stream_gen:
        self.assertEqual(i, expected_value)
        n_runs += 1
    self.assertEqual(n_runs, expected_runs_count)