[英]How to test in FastAPI that client calls correct method of endpoint?
[英]How authentic JWS with test client Fastapi
我正在尝试测试一个依赖于 jwt 身份验证但不知道如何做到这一点的端点,尤其是发送身份验证或跳过,请一个建议将非常有用。
我的代码给了我这个错误:
AssertionError: {"detail":"Not authenticated"}
路由器:
@router.post(
path="/api/users",
response_model=UsersRespose,
status_code=status.HTTP_201_CREATED,
summary="Create a new Users Survey",
tags = ["Users"]
)
async def create_user_survey(
user:Users,
db: Session = Depends(get_db),
admin: Admins= Depends(get_curret_admin)
):
db_user = await get_users_by_email(db,email=user.users_email)
if db_user:
raise HTTPException(status_code=400, detail="El correo electronico ya existe")
return await create_users_survey(db=db, user=user)
依赖:
async def create_token(admin:Admin):
admin_obj = Admins.from_orm(admin)
token = encode(admin_obj.dict(), JWT_SECRET)
return dict(access_token=token, token_type="bearer")
async def get_curret_admin(db: Session=Depends(get_db), token: str = Depends(oauth2schema)):
try:
payload=decode(token, JWT_SECRET, algorithms=["HS256"])
admin= db.query(Admin).get(payload["id"])
except:
raise HTTPException(
status_code=401,
detail="Correo o password invalido"
)
return Admins.from_orm(admin)
并测试
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all(bind=engine)
def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_create_user():
mail=random_email_user()
name =random_name_user()
password = random_pasword_user()
id=random_int_user()
response=client.post("/api/users", json={"users_email":mail ,"id":id, "users_name": name},)
assert response.status_code == 201, response.text
data = response.json()
assert data["users_email"] == mail
感谢@MatsLindh,解决方案非常简单
def override_get_currrent_admin():
return {"email":"dummy@dummy.com", "name_admin":"dummy", "id":"5"}
app.dependency_overrides[get_curret_admin]= override_get_currrent_admin
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.