烧瓶测试:preprocess_request(),dispatch_request()

时间:2019-06-29 06:30:21

标签: python-3.x unit-testing flask

我的环境:

  

Python3.7
  烧瓶== 1.0.2
  pytest == 4.3.1

我正在寻找一种在pytest函数中同时检索请求对象和响应对象的方法。然后我遇到了这个单元测试片段。

http://flask.pocoo.org/snippets/58/

下面是我的工作。

def test_busking(session, monkeypatch, report=Report()):

    with app.test_request_context('/busking/zones'):
        # call the before funcs
        rv = app.preprocess_request()
        if rv != None:
            response = app.make_response(rv)
        else:
            # do the main dispatch
            rv = app.dispatch_request()
            response = app.make_response(rv)

            # now do the after funcs
            response = app.process_response(response)

        assert flask.request
        assert response

在我的环境中效果很好。我能够同时获得两个对象。我的问题是什么...

    仅在rv is None时调用
  • dispatch_request()。为什么当rv还有别的东西时?

  • process_response()也为什么在rv is None时被调用?

  • 它接缝像preprocess_request()调用before_request_funcs,并且rv是最后一个before_request_function的返回值...看起来rv与派遣请求无关,但是我知道一定是...告诉我我的错。

在preprocess_request(),make_response(),dispatch_request(),process_response()中,还有很多我不了解的东西。我认为rv和process_request()发挥了重要作用,但我不确定。如果您还说明背景情况,那将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不是Flask的专家,所以这个答案可能会遗漏一些要点,但我认为足以澄清您的情况:

  • 如果before_request函数返回的值不是None,它将被视为视图的响应,因此不再进行任何处理,请参见preprocess_request's doc
  • process_response调用after_request方法,无论响应内容(AFAIK)如何都被调用
  • 根据上面链接的同一文档,我想说rv是从None收到的第一个非before_request结果,而不是最后一个, None返回,处理停止。

乍一看,我会说这是事物的顺序:

  1. preprocess_request:依次调用before_request函数
  2. 其中一个返回的值与None不同,请立即停止调用其余的并跳至(4)
  3. dispatch_request:调用与路由规则关联的方法
  4. make_response:根据先前的结果(此处为Response)准备rv对象
  5. process_response:使用after_request对象调用Response函数
相关问题