Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()

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

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...