繁体   English   中英

使用GET请求而不是POST的烧瓶测试客户端

[英]Flask test client using GET request instead of POST

我只有一个POST请求的路由,如果满足条件,它将返回json响应。 就像这样:

@app.route('/panel', methods=['POST'])
def post_panel():
    # Check for conditions and database operations
    return jsonify({"message": "Panel added to database!"
                    "success": 1})

我正在使用flask-sslify强制将HTTP请求发送到https。

我正在用Flask测试客户端和unittest测试此路由。 测试功能类似于以下内容:

class TestAPI2_0(unittest.TestCase):
    def setUp(self):
    self.app = create_app('testing')
    self.app_context = self.app.app_context()
    self.app_context.push()
    db.create_all()
    create_fake_data(db)
    self.client = self.app.test_client()

    def tearDown(self):
        ....

    def test_post_panel_with_good_data(self):    
        # data
        r = self.client.post('/panel',
                            data=json.dumps(data),
                            follow_redirects=True)  
        print(r.data)      
        self.assertEqual(r.status_code, 200)

输出正好在下面:

test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n'


======================================================================
FAIL: test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tanjibpa/work/craftr-master/tests/test_api_2_0.py", line 110, in test_post_panel_with_good_data
    self.assertEqual(r.status_code, 200)
AssertionError: 405 != 200

我收到一条错误消息,指出该路线不允许使用Method。 如果我将GET指定为方法( methods=['GET', 'POST'] ),则可以进行路由测试。 但是,为什么测试客户端正在发出GET请求? 有什么办法可以解决,而不是为路由指定GET请求吗?

更新:

如果这样做:

@app.route('/panel', methods=['GET', 'POST'])
def post_panel():
    if request.method == 'POST':
        # Check for conditions and database operations
        return jsonify({"message": "Panel added to database!"
                        "success": 1})
    return jsonify({"message": "GET request"})

我得到这样的输出:

test_post_panel_with_good_data (tests.test_api_2_0.TestAPI2_0) ... b'{\n  "message": "GET request"\n}\n'

我发现是什么导致了烧瓶测试客户端中的GET请求。 我正在使用flask-sslify强制将HTTP请求发送到https。 尽管通过其他类型的请求(POST,PUT,DELETE ...)指定了测试客户端,但是flask-sslify以某种方式强制执行GET请求。

因此,如果我在测试烧瓶期间禁用sslify,则测试客户端会正常工作。

暂无
暂无

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

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