各位大神好,小弟目前正在試著使用 FastAPI 的 TestClient 進行測試程式的撰寫,以下是我的程式碼
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)
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
...
...
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,想問問各位大神有沒有類似的經驗,或是我的寫法有哪些地方可以改正的?
-----------------更新----------------------
__________________ 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"}
gitlab/gitlab-runner:latest
404 status code
就是(url)Not Found
檢查看看你的 url 是否正確
找一下程式裡回覆以下訊息的原因即可{"detail":"Not Found"}