iT邦幫忙

0

FastAPI TestClient return 404

  • 分享至 

  • xImage

各位大神好,小弟目前正在試著使用 FastAPI 的 TestClient 進行測試程式的撰寫,以下是我的程式碼

  • base_test_case
class APIBaseTestCase(unittest.TestCase):
    @staticmethod
    def _session_override():
        with Session(test_db_engine) as session:
            yield session

    def setUp(self):
        app = FastAPI()
        app.include_router(router=router)
        SQLModel.metadata.create_all(test_db_engine)
        app.dependency_overrides[get_session] = self._session_override
        self.test_client: TestClient = TestClient(app=app)

        ...

    def tearDown(self):
        SQLModel.metadata.drop_all(test_db_engine)
  • test_case.py
class TestDemo(APIBaseTestCase):
    def test_demo(self):
        response = self.test_client.get("<url>")
        print(response.status_code)
        print(response.json())

        assert response.status_code == 200
        ...
        ...
  • .gitlab-ci.yml
stages:
    - backend-api-test

backend-api-test:
    stage: backend-api-test
    script:
        - pip3 install -r ./backend/requirements.txt
        - pytest -v ./backend/test/api/endpoints/test_case.py
    tags:
        - demo-runner

目前我碰到的問題是,上面的寫法在本地端使用 IDE or CMD 執行的時候都沒有問題,但是將程式 push 上 gitlab 後,利用 cicd container (python 環境) 進行測試時,test_case.py 內的測試項目會回傳 404 status code,想問問各位大神有沒有類似的經驗,或是我的寫法有哪些地方可以改正的?

-----------------更新----------------------

  • 補上其中一個 test case 的錯誤 log
__________________ TestAPIClient.test_get_total_client_count ___________________
self = <test.api.endpoints.test_client.TestAPIClient testMethod=test_get_total_client_count>
    def test_get_total_client_count(self):
        with Session(db_engine) as session:
            create_client(session=session)
            response = self.test_client.get("/api/client/count", headers=self.headers)
            print(response.status_code)
            print(response.text)
    
>           assert response.status_code == 200
E           assert 404 == 200
E            +  where 404 = <Response [404]>.status_code
backend/test/api/endpoints/test_client.py:56: AssertionError
----------------------------- Captured stdout call -----------------------------
404
{"detail":"Not Found"}
  • runner 類型
    1. runner 為使用 docker 部屬,使用的 img 為 gitlab/gitlab-runner:latest
    2. 使用的環境為 python:latest
墨嗓 iT邦研究生 4 級 ‧ 2022-09-16 00:39:46 檢舉
因為發生問題的位置在 GitLab 上,所以需要更完整的 .gitlab-ci.yml 資訊。例如使用的 GitLab runner 的類型、使用的 docker image 為何、Runner 執行的完整錯誤訊息等。
感謝回復!! 已經有試著補上相關訊息,希望可以協助解答,或是還需要其他訊息也可以再留言告訴我,非常感謝!!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2022-09-16 09:06:28
最佳解答

404 status code就是(url)Not Found
檢查看看你的 url 是否正確

找一下程式裡回覆以下訊息的原因即可
{"detail":"Not Found"}

好的 我會朝這個方向看看 感謝!!

後來有發現原來是自己在 mount router 的時候沒有把路由掛上去 (環境變數沒設好) 難怪 Testclient 找不到路由,設定完成之後就解決了,感謝

我要發表回答

立即登入回答