【问题标题】:Flask Unittest for Post MethodPost 方法的烧瓶单元测试
【发布时间】:2017-12-07 02:31:59
【问题描述】:

我正在为一个返回渲染模板的函数编写一个 Flask 单元测试。我尝试了几种方法,但似乎不起作用。 这是函数:

@app.route('/', methods=['POST'])
@lti(request='initial', error=error, app=app)
def chooser(lti=lti):
   return_url = request.form.get('launch_presentation_return_url', '#')
   return render_template(
       'chooser.html'
   )

我一直在尝试的几种方法:

# 1st way    
rv = self.app.post('/')
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
# Error
self.assertTrue('Choose an Icon to Insert' in rv.get_data(as_text=True))
AssertionError: False is not true


# 2nd way    
rv = self.app.post('/chooser.html')
assert '<h1>Choose an Icon to Insert</h1>' in rv.data
# Error
assert 'Choose an Icon to Insert' in rv.data
AssertionError

选择器.html

 <body>
    <h1>Choose an Icon to Insert</h1>
 </body>

感谢您的所有帮助。

【问题讨论】:

  • 你有什么错误吗?请编辑您的问题以包含尽可能多的详细信息,以便人们为您提供帮助。
  • 感谢您的提醒。我更新了问题,希望对您有所帮助。

标签: python unit-testing flask


【解决方案1】:

这里有一个例子可以帮助你理解。我们的申请 - app.py:

import httplib
import json

from flask import Flask, request, Response

app = Flask(__name__)


@app.route('/', methods=['POST'])
def main():
   url = request.form.get('return_url')
   # just example. will return value of sent return_url
   return Response(
      response=json.dumps({'return_url': url}),
      status=httplib.OK,
      mimetype='application/json'
   )

我们的测试 - test_api.py:

import json
import unittest

from app import app
# set our application to testing mode
app.testing = True


class TestApi(unittest.TestCase):

    def test_main(self):
        with app.test_client() as client:
            # send data as POST form to endpoint
            sent = {'return_url': 'my_test_url'}
            result = client.post(
                '/',
                data=sent
            )
            # check result from server with expected data
            self.assertEqual(
                result.data,
                json.dumps(sent)
            )

如何运行:

python -m unittest discover -p path_to_test_api.py

结果:

----------------------------------------------------------------------
Ran 1 test in 0.009s

OK

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-15
    • 2018-11-09
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多