简体   繁体   中英

How to mock client IP on fastapi.testclient.TestClient?

Say you are using fastapi.testclient.TestClient to perform a GET, for instance. Inside the API code that defines that GET method, if you get request.client.host, you will get the string "testclient".

Test, using pytest:

def test_success(self):
    client = TestClient(app)
    client.get('/my_ip')

Now, lets assume your API code is something like this:

@router.get('/my_ip')
def my_ip(request: Request):
    return request.client.host

The endpoit /my_ip is suppose to return the client IP, but when running pytest, it will return "testclient" string. Is there a way to change the client IP (host) on TestClient to something other than "testclient"?

You can mock the fastapi.Request.client property as,

# main.py

from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/")
def root(request: Request):
    return {"host": request.client.host}

# test_main.py

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def test_read_main():
    
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"host": "192.168.123.132"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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