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"
    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.

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

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

Prev: 19 : List … Next: 21 : Deleting …

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.



Refund Policy

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial