简体   繁体   English

后置方法的烧瓶单元测试

[英]Flask Unittest for Post Method

I am writing a Flask unit test for a function that would return a render template. 我正在为返回返回模板的函数编写Flask单元测试。 I tried few ways but it seems not working. 我尝试了几种方法,但似乎不起作用。 Here is the function: 这是函数:

@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'
   )

Few ways that I have been trying: 我一直在尝试的几种方法:

# 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

chooser.html chooser.html

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

Thanks for all your helps. 感谢您的所有帮助。

Here an example which can help you to understand. 这里有一个例子,可以帮助您理解。 Our application - app.py : 我们的应用程序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'
   )

Our tests - test_api.py : 我们的测试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)
            )

How to run: 如何运行:

python -m unittest discover -p path_to_test_api.py

Result: 结果:

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

OK

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM