简体   繁体   中英

How authentic JWS with test client Fastapi

I'm trying to test a endpoint that depends a jwt authentication but don't know how make this, especially send the authentication or skip, please an advice will be very useful.

My code give me that error :

AssertionError: {"detail":"Not authenticated"}

router:

@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)

dependency:

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)

and test

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

Thanks to @MatsLindh the solution was quite simple

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

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