Skip to content

zoobz-io/clockz

Repository files navigation

clockz

CI Status codecov Go Report Card CodeQL Go Reference License Go Version Release

Type-safe clock abstractions for Go with zero dependencies.

Build time-dependent code that's deterministic to test and simple to reason about.

Deterministic Time

func TestRetryBackoff(t *testing.T) {
    // Create a clock frozen at a specific moment
    clock := clockz.NewFakeClockAt(time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC))
    service := NewService(clock)

    go service.RetryWithBackoff()

    // Advance through retry delays instantly
    clock.Advance(1 * time.Second)  // First retry
    clock.Advance(2 * time.Second)  // Second retry
    clock.Advance(4 * time.Second)  // Third retry

    // Test completes in milliseconds, not seconds
}

No sleeps. No flaky timeouts. Time moves when you say so.

Installation

go get github.com/zoobz-io/clockz

Requires Go 1.24+

Quick Start

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/zoobz-io/clockz"
)

type Service struct {
    clock clockz.Clock
}

func (s *Service) ProcessWithTimeout(ctx context.Context) error {
    ctx, cancel := s.clock.WithTimeout(ctx, 30*time.Second)
    defer cancel()

    timer := s.clock.NewTimer(5 * time.Second)
    defer timer.Stop()

    select {
    case t := <-timer.C():
        fmt.Printf("Processing at %v\n", t)
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

func main() {
    // Production: real time
    service := &Service{clock: clockz.RealClock}
    if err := service.ProcessWithTimeout(context.Background()); err != nil {
        fmt.Printf("Error: %v\n", err)
    }
}

Capabilities

Feature Description Docs
RealClock Production clock wrapping time package API Reference
FakeClock Test clock with manual time control API Reference
Timers & Tickers Create, stop, reset timing primitives Concepts
Context Integration WithTimeout and WithDeadline support Concepts
Time Advancement Advance() and SetTime() for tests Testing Guide

Why clockz?

  • Deterministic tests — Eliminate time-based flakiness entirely
  • Zero dependencies — Only the standard library
  • Thread-safe — All operations safe for concurrent use
  • Familiar API — Mirrors the time package interface
  • Context-aware — Built-in timeout and deadline support

Documentation

Learn

Guides

Cookbook

Reference

Contributing

Contributions welcome. See CONTRIBUTING.md for guidelines.

make help      # Available commands
make check     # Run tests and lint

License

MIT — see LICENSE