Home > Enterprise >  Error when using test_client (Flask) - raise ValueError("unknown url type: %r" % self.full
Error when using test_client (Flask) - raise ValueError("unknown url type: %r" % self.full

Time:12-30

flask application code:

# main.py 
from flask import Flask, Response
app = Flask(__name__)


@app.route("/", methods=["POST"])
def post_example():
    return Response("aaa")

and this is my testing code:

# e2e.py
from main import app

test_client = app.test_client()


def test_flask_api_call():
    response = test_client.post("/", {"a": "b"})
    pass

I keep receiving:

raise ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: '://{'a': 'b'}/'
   

CodePudding user response:

The problem is on the post method call. You have to name your data arguments client.post("/", data={"a": "b"}), if it's not the case it is considered as a part of the URL.

>>> urllib.parse.quote("/"   str({"a": "b"}))
'/{'a': 'b'}'

Here is the test code rewritten to define a fixture for the client initialization. More info on testing flask application on the official doc.

import pytest

from main import app


@pytest.fixture(scope="module")
def client():
    with app.test_client() as client:
        yield client


def test_flask_api_call(client):
    response = client.post("/", data={"a": "b"})
    assert response.status_code == 200, f"Got bad status code {response.status_code}"
  • Related