Skip to content

serhiismetanskyi/restfulbooker-api-tests

Repository files navigation

RestfulBooker API Test Automation

API test suite for Restful-Booker - a free RESTful API by Mark Winteringham for practicing API test automation.

Quick Start

# Install dependencies
make install

# Run tests in headless mode
make test

# Run tests with HTML report
make test-html

Releases

See detailed release notes in RELEASE.md.
Current version: 0.1.0.

Tech Stack

Core packages:

  • pytest - testing framework
  • requests - HTTP client library
  • pytest-html - HTML reports with logs
  • pytest-dependency - test dependency management
  • faker - test data generation
  • python-dotenv - environment configuration
  • uv - Python package manager

Development tools:

  • ruff - linter and formatter (replaces flake8 + black + isort)

Project Structure

Utils Modules (utils/)

  • api.py - high-level API client with all endpoint methods
  • http_methods.py - HTTP method wrappers (GET, POST, PUT, PATCH, DELETE) with logging
  • checking.py - response validation utilities (status codes, JSON structure, field values)
  • data.py - test data generation factory
  • generator.py - Faker wrapper for random data
  • config.py - environment configuration loader
  • logger.py - custom logger for test execution (saves to files + outputs to HTML report)

Tests (tests/)

  • test_booking.py - complete booking lifecycle test suite

Implementation Details

Dependency-based Test Orchestration

Uses pytest-dependency markers to enforce test execution order:

  • auth - user authentication (must run first)
  • create_booking - creates booking and stores ID
  • get_booking - retrieves booking by ID
  • update_booking - full booking update
  • partial_update_booking - partial booking update
  • get_bookingids - search bookings by name and dates
  • delete_booking - deletes booking
  • get_booking_after_delete - verifies deletion (404 check)

API Client Pattern

Clean separation of API logic from test code:

  • All endpoints wrapped in RestfulBookerAPI class
  • HTTP methods abstracted in HTTPMethods with automatic logging
  • Request/response logging integrated into HTML reports

Dual Logging

  • File logging: detailed HTTP requests/responses in logs/log_*.log for debugging
  • HTML reports: test logs displayed in pytest-html reports with structured formatting

Logging is integrated at the HTTP client level - all requests are automatically logged.

Error Handling

All HTTP wrappers and validation helpers include:

  • Try-except blocks with descriptive error messages
  • Automatic error logging to files and reports
  • Timeout handling (30 seconds for all requests)
  • JSON parsing error handling with response preview

Dynamic Test Data

Faker-based data generation for realistic test scenarios:

  • Random first/last names
  • Random prices (1000-2000)
  • Random booking dates (checkin today, checkout +10 days)
  • Random additional needs (Breakfast, WiFi, Parking, etc.)
  • Random deposit paid status

Linting and Formatting

Project uses Ruff - a fast Rust-based linter that replaces flake8, black, isort and other tools.

# Check code
make lint

# Auto-fix issues
make fix

# Format code
make format

# Check formatting
make format-check

Ruff is configured with rules:

  • pycodestyle (E, W)
  • pyflakes (F)
  • isort (I)
  • flake8-bugbear (B)
  • flake8-comprehensions (C4)
  • pyupgrade (UP)

Docker

Project is containerized for consistent test execution:

# Build image
make docker-build

# Run tests in Docker (headless)
make docker-test

# Run tests in Docker with HTML report
make docker-test-html

# Open shell in container
make docker-shell

# Clean up Docker resources
make docker-clean

Dockerfile uses Python 3.11 slim image and uv for fast dependency installation.

Reports and Logs

HTML Reports (reports/test_report.html):

  • Detailed information about each test
  • Execution logs (logger.info)
  • HTTP requests and responses with structured formatting
  • Request/response bodies with JSON formatting
  • Filter by test status
  • Environment metadata
  • reports/ is created automatically only when running report-generating targets (make test-html, make docker-test-html)

File Logs (logs/log_*.log):

  • Complete HTTP interaction information
  • Timestamp for each request
  • Headers, cookies, request/response bodies
  • Test name and execution phase
  • logs/ is created on demand by any CLI or Docker test target and removed by make clean

Logging is integrated at the HTTP client level - all requests are automatically logged.

Test Execution Examples

HTML Report Example

Generated HTML report (reports/test_report.html) provides a comprehensive view of test execution:

Test Report Example

The report includes:

  • Test execution summary with pass/fail statistics
  • Environment details (Python version, platform, packages)
  • Detailed logs for each test with timestamps
  • HTTP request/response details with structured formatting
  • JSON-formatted request/response bodies
  • Expandable test details for troubleshooting

Log File Example

Each HTTP request and response is logged with detailed information in logs/log_*.log:

-----
Test: tests/test_booking.py::TestRestfulBookerAPI::test_create_booking (call)
Time: 2025-11-18 18:29:47.617468
Request method: POST
Request URL: https://restful-booker.herokuapp.com/booking
Request headers: {
  "Content-type": "application/json",
  "Accept": "application/json"
}
Request body: {
  "firstname": "Antonio",
  "lastname": "Simpson",
  "totalprice": 1500,
  "depositpaid": true,
  "bookingdates": {
    "checkin": "2025-11-18",
    "checkout": "2025-11-28"
  },
  "additionalneeds": "Breakfast"
}

Response code: 200
Response text: {
  "bookingid": 1234,
  "booking": {
    "firstname": "Antonio",
    "lastname": "Simpson",
    ...
  }
}
Response headers: {'Content-Type': 'application/json; charset=utf-8', ...}
Response cookies: {}

-----

Each log entry includes:

  • Test name and execution phase (setup/call/teardown)
  • Timestamp for precise tracking
  • Complete HTTP request details (method, URL, headers, body)
  • Complete HTTP response details (status code, headers, body, cookies)
  • Request/response separation for easy navigation

Configuration

Configuration via environment variables in .env:

  • BASE_URL - API base URL (default: https://restful-booker.herokuapp.com)
  • API_USERNAME - authentication username (default: admin)
  • API_PASSWORD - authentication password (default: password123)

Test Coverage

  • Health Check: 1 test (ping endpoint)
  • Authentication: 1 test (token creation)
  • Create Booking: 1 test (create new booking)
  • Get Booking: 1 test (retrieve by ID)
  • Update Booking: 1 test (full update)
  • Partial Update: 1 test (partial update)
  • Search Bookings: 1 test (search by name and dates)
  • Delete Booking: 1 test (delete booking)
  • Negative Test: 1 test (verify 404 after deletion)

Total: 9 tests covering complete booking lifecycle from creation to deletion.

Available Commands

Setup

make install       # Sync dependencies with uv (including dev tools)

Testing

make test          # Run test suite
make test-html      # Run tests and generate HTML report
make all            # Install, format, lint, and test (full workflow)

Code Quality

make lint          # Run Ruff lint checks
make format        # Format code with Ruff
make format-check  # Check formatting without modifying files
make fix           # Auto-fix lint issues and format code

Docker

make docker-build   # Build Docker image
make docker-test    # Run tests in Docker (headless)
make docker-test-html # Run tests in Docker with HTML report
make docker-shell   # Open shell in Docker container
make docker-clean   # Remove Docker containers and images

Maintenance

make clean         # Remove cache artifacts, reports, and logs
make help          # Show all available commands

API Under Test: https://restful-booker.herokuapp.com/

About

API tests for Restful-Booker

Topics

Resources

Stars

Watchers

Forks

Contributors