2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python+FastAPIのAPIテストをPytestで実行してみる

Last updated at Posted at 2022-11-02

PythonでFastAPIを使ったAPIをテストしてみる

※FastAPIで別APIを呼び出す記事はこちら
Python+FastAPIからRequestsにより別APIを呼び出してみる。uvicornでホスティング
https://qiita.com/thithi7110/items/c1b01798e69ddc31206b

1.適当なAPIを用意

main.py
import requests,json
from fastapi import FastAPI
app = FastAPI()

#単純なメッセージ返却
@app.get("/")
async def Hello():
    return {"message":"Hello"}

#クエリパラメータ
@app.get("/zipcode")
async def ZipCode(zipcode:int = 0):
    url = f'https://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}'
    r = requests.get(url)
    print(r.text)
    return json.loads(r.text)

2.テスト記述

tests/test_main.py

from fastapi.testclient import TestClient
from main import app
import json

client = TestClient(app)

def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    print("")
    print(response.json())
    print(response.json()['message'])
    print("★★")
    assert response.json() == {"message":"Hello"}
    
def test_read_zipcode():
    response = client.get(f'/zipcode?zipcode=9012303')
    print("test_read_zipcode")
    assert response.status_code == 200
    print(response.json()['results'])
    
    assert response.json()['results'][0]['address1'] == '沖縄県'
   

3.testpyを実施(エラーになる)
ImportError while importing test module 'C:\work\prod\sample-app-cicd\sample-app-backend\tests\test_main.py'.
Hint: make sure your test modules/packages have valid Python names.

image.png

どうもルート直下にconftest.pyを配置しないといけないらしい。

4.ルート直下にconftest.pyの空ファイルを配置
image.png

5.再度実行

pytest

image.png

※pytestでテスト内部のprintを出力する場合は -s オプションをつける

pytest -s

image.png

以上

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?