Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

python - Unit Tests for FLASK API

I have a basic flask API running :

u/app.route('/helloworld', methods = ['GET'])
def first_api():
    hname = "hello"
    lhname = "world"
    print(hname+lhanme)

Now I need to add some unit tests to it, and here is my unit test file:

import json
def test_index(app, client):
    res = client.get('/helloworld')
    assert res.status_code == 200
    assert "hello" in res.data

How can I pass value for variables hname and lhname from this unit test?

Here is my conf file for pytest:

import pytest
from app import app as flask_app
u/pytest.fixture
def app():
    return flask_app

u/pytest.fixture

def client(app):
    return app.test_client()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a little mistake in your endpoint. You want it to return the string instead of printing it. Please consider the following example:

from flask import Flask, request

flask_app = Flask(__name__)
app = flask_app

@app.route('/helloworld', methods = ['GET'])
def first_api():
    hname = request.args.get("hname")
    lhname = request.args.get("lname")
    print(hname)
    return hname + lhname



def test_index(app):
    client = app.test_client()
    hname = "hello"
    lname = "world"
    res = client.get('/helloworld?hname={}&lname={}'.format(hname, lname))
    assert res.status_code == 200
    assert "hello" in res.data.decode("UTF-8")

if __name__ == "__main__":
    test_index(app)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...