Skip to content

Api test toolbox

Achievements

  • DRY asserts on a vareity of tests.
  • Improved output when receiving an error.

Description

Technologies used

  • Python

Responsibilities

  • Product owner
  • Developer

The main goal of this library is to validate results in FastAPI projects without repeating boilerplate logic. When running tests against an API, you almost always need to verify the HTTP status code and the length of the response. A secondary goal is to raise detailed exceptions that include the request data and status code; this eliminates the need to manually debug tests to identify the root cause of a failure.

# We perform a request and get a result
from api_test_toolbox.result_toolbox import ResultToolbox

response = test_client.client.post(
    "/warehouse_movement/add_multiple_internal",
    headers={"Authorization": f'Bearer {test_client.token}'},
    json={
        "warehouse_movement_ext_id": "string",
        "obs": "",
        "reference": "string",
        "priority": 'priority_3',
        "wac_content": [
            {
                "origin_warehouse_area_uuid": reception_add['content'][0]['destination_warehouse_area_uuid'],
                "origin_rack_uuid": reception_add['content'][0]['destination_rack_uuid']
            }
        ]
    }
)

# Create the result toolbox
result_toolbox = ResultToolbox(response)

# Validate the status and length
result_toolbox.validate_response(expected_result=[(ResultStatusCodeOperator.Equal, 200)], expected_list_length=1)

# Validate some enum (by default searches the 'status' but it could be any dict key
result_toolbox.validate_status(status_value=WarehouseMovementStatusEnum.COMPLETED)

# Return a value by zero index.
return result_toolbox.get_response_item_dict(0)

If a problem is found... The pytest log will show the following

E       AssertionError: ⛔ Result Status code error ⛔
E       
E       Response Status is NOT in the expected list.
E       Expected IN: 420
E       Received: 200
E       
E       Endpoint: http://testserver/warehouse_movement/add_multiple_internal
E       Content: [{"priority":"priority_3",.....}]

Learned

  1. Validating coverage during CI using uv in GitLab

Components

coverage.png

Main advantages

The main advantage is receiving a printout of the result data when the most repeated assert checks fails. With this when running all the tests we can deduce the reason for the failure without having to run the test again, saving time.