20 : Updating a Job

  

Trust me I am not a GP3 bot typing this post 😁. I am assuming you too are not a scrapping bot !. Then it's common for us to make mistakes and even if it's not a mistake to keep up with the new information we need to update. So, do job posts. So, In this post, we are going to see how we can update our database records. Time for a failing test. I told an that this time we are going to follow TDD.Here is a  test case that I designed to test if an update is successful. Put this test in tests > test_routes > test_jobs.py

def test_update_a_job(client):
    data = {
        "title": "New Job super",
        "company": "doogle",
        "company_url": "www.doogle.com",
        "location": "USA,NY",
        "description": "fastapi",
        "date_posted": "2022-03-20"
        }
    client.post("/jobs/create-job/",json.dumps(data))
    data["title"] = "test new title"
    response = client.put("/jobs/update/1",json.dumps(data))
    assert response.json()["msg"] == "Successfully updated data."

Obviously, this test is bound to fail because we have not even implemented the route. Then how does these failing test makes any sense, idiotic no? Actually no, These tests help us design our route.

  • We have to design a route that will accept an id.
  • our route will work with put HTTP verbs.
  • Once updating is successful, It should return a dictionary with a key of "msg" and value as a success message.

By the way, this is not a good unit test. Think why?? Think think 🤔, because this is the most crucial thing, we have to prepare our brain to fight even if the battle is hard. The reason that I can think of is that our test is not testing if the job-post is updated or not, It is just checking that we should receive a message "Successfully updated data."! These kinds of tests are bad tests, they increase the test-coverage but aren't much help. Just wanted to bring it to your notice. You may try fixing the test. Now, let's keep moving.

Lets implement this route at apis > version1 > route_jobs.py
 

from db.repository.jobs import create_new_job
from db.repository.jobs import retreive_job, list_jobs,update_job_by_id   #new

router = APIRouter()
... 

@router.get("/all",response_model=List[ShowJob])
def read_jobs(db:Session = Depends(get_db)):
    ...

 
@router.put("/update/{id}")   #new
def update_job(id: int,job: JobCreate,db: Session = Depends(get_db)):
    current_user = 1
    message = update_job_by_id(id=id,job=job,db=db,owner_id=current_user)
    if not message:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Job with id {id} not found")
    return {"msg":"Successfully updated data."}

This route is depending on a repository at db > repository > jobs.py

def update_job_by_id(id:int, job: JobCreate,db: Session,owner_id):
    existing_job = db.query(Job).filter(Job.id == id)
    if not existing_job.first():
        return 0
    job.__dict__.update(owner_id=owner_id)  #update dictionary with new key value of owner_id
    existing_job.update(job.__dict__)
    db.commit()
    return 1

I believe the logic is self-explanatory, please try reading the code. Time to test our work:

Ok, let's meet in the next post, In the next part, we will be doing our final exercise of CRUD i.e. Delete.

Final git commit: Implement updatetion route · nofoobar/JobBoard-Fastapi@c27c506 (github.com)

FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial