Flask unittesting API请求

时间:2017-12-01 10:17:49

标签: flask

我正在尝试为flash api服务器编写单元测试用例。 有人可以建议你去掉auth.login_required

试图嘲笑auth,但没有用。

test_client也没有打到代码块。

api.py

from flask import Flask
from flask.ext.httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

@app.route('/')
@auth.login_required
def index():
    print "In index"
    response.status_code = 200
    return response

尝试跟随http://flask.pocoo.org/docs/0.12/testing/

from src.api import app
from unittest import TestCase

class TestIntegrations(TestCase):
    def setUp(self):
        self.app = app.test_client()
    def test_thing(self):
        response = self.app.get('/')

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

有两种方法可以做到这一点 - 首先是在测试中禁用授权:

// in your test module 
from api import app, auth
import unittest

@auth.verify_password
def verify_password(user, password):
    """Overwrite password check to always pass.

    This works even if we send no auth data."""
    return True

另一种方法是从测试中实际发送auth标头(这样你也可以测试你的授权系统):

from api import app
from base64 import b64encode
import unittest


class ApiClient:
    """Performs API requests."""

    def __init__(self, app):
        self.client = app.test_client()

    def get(self, url, **kwargs):
        """Sends GET request and returns the response."""
        return self.client.get(url, headers=self.request_headers(), **kwargs)

    def request_headers(self):
        """Returns API request headers."""
        auth = '{0}:{1}'.format('user', 'secret')
        return {
            'Accept': 'application/json',
            'Authorization': 'Basic {encoded_login}'.format(
                encoded_login=b64encode(auth.encode('utf-8')).decode('utf-8')
            )
        }


class TestIntegrations(unittest.TestCase):

    def setUp(self):
        self.app = ApiClient(app)

    def test_thing(self):
        response = self.app.get('/')
        print(response.data)

ApiClient帮助程序还可以定义与post类似的deleteget方法。

包含示例的完整源代码为here