testutil

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package testutil provides testing utilities for the OCI bundle library. This file contains archive generation utilities for testing.

Package testutil provides testing utilities for the OCI bundle library. This file contains benchmark utilities for performance measurement.

Package testutil provides testing utilities for the OCI bundle library. This file contains coverage reporting utilities.

Package testutil provides testing utilities for the OCI bundle library. This file contains malicious archive generators for security testing.

Package testutil provides testing utilities for the OCI bundle library. It includes test registries, archive generators, and benchmark utilities.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrintIssues

func PrintIssues(issues []CoverageIssue)

PrintIssues prints coverage issues in a formatted way.

Types

type ArchiveGenerator

type ArchiveGenerator struct {
	// contains filtered or unexported fields
}

ArchiveGenerator creates test archives of various sizes and types for testing. It can generate archives with specific file counts, sizes, and content patterns.

func NewArchiveGenerator

func NewArchiveGenerator() (*ArchiveGenerator, error)

NewArchiveGenerator creates a new archive generator with a temporary directory.

func NewArchiveGeneratorWithFSTemp

func NewArchiveGeneratorWithFSTemp(root string) *ArchiveGenerator

NewArchiveGeneratorWithFSTemp creates a new archive generator using a provided filesystem root path. Tests can pass an in-memory root path when using a memfs implementation.

func (*ArchiveGenerator) Close

func (g *ArchiveGenerator) Close() error

Close cleans up the temporary directory used by the generator.

func (*ArchiveGenerator) GenerateEmptyArchive

func (g *ArchiveGenerator) GenerateEmptyArchive(outputPath string) error

GenerateEmptyArchive creates an empty tar.gz archive. This is useful for testing edge cases.

func (*ArchiveGenerator) GenerateLargeArchive

func (g *ArchiveGenerator) GenerateLargeArchive(ctx context.Context, size int64, outputPath string) (int64, error)

GenerateLargeArchive creates an archive with a single large file. This is useful for testing streaming and memory usage.

Parameters:

  • size: Size of the large file in bytes
  • outputPath: Path where the tar.gz file will be created

Returns the actual size of the generated archive.

func (*ArchiveGenerator) GenerateTestArchive

func (g *ArchiveGenerator) GenerateTestArchive(
	ctx context.Context,
	size int64,
	fileCount int,
	pattern, outputPath string,
) (int64, error)

GenerateTestArchive creates a test tar.gz archive with the specified parameters. It generates files with predictable or random content based on the options.

Parameters:

  • size: Approximate total size of the uncompressed archive in bytes
  • fileCount: Number of files to generate
  • pattern: Content pattern - "zeros", "random", "text", or "mixed"
  • outputPath: Path where the tar.gz file will be created

Returns the actual size of the generated archive and any error.

func (*ArchiveGenerator) GenerateTestDirectory

func (g *ArchiveGenerator) GenerateTestDirectory(
	baseDir string,
	depth, filesPerDir int,
	avgFileSize int64,
) (int64, error)

GenerateTestDirectory creates a directory structure with test files for archiving. This is useful for testing the archiving process with real directory structures.

Parameters:

  • baseDir: Base directory to create the structure in
  • depth: Directory depth (1 = flat, 2 = one level of subdirs, etc.)
  • filesPerDir: Number of files per directory
  • avgFileSize: Average file size in bytes

Returns the total size of all created files.

type BenchmarkOCIClient

type BenchmarkOCIClient struct {
	*BenchmarkRunner
	// contains filtered or unexported fields
}

BenchmarkOCIClient provides benchmark utilities specifically for OCI client operations.

func NewBenchmarkOCIClient

func NewBenchmarkOCIClient() (*BenchmarkOCIClient, error)

NewBenchmarkOCIClient creates a new OCI client benchmark runner.

func (*BenchmarkOCIClient) BenchmarkArchiveCreation

func (b *BenchmarkOCIClient) BenchmarkArchiveCreation(bench *testing.B)

BenchmarkArchiveCreation benchmarks archive creation performance.

func (*BenchmarkOCIClient) Close

func (b *BenchmarkOCIClient) Close() error

Close cleans up benchmark resources.

func (*BenchmarkOCIClient) SetupRegistry

func (b *BenchmarkOCIClient) SetupRegistry(ctx context.Context) error

SetupRegistry sets up a test registry for benchmarks.

type BenchmarkResult

type BenchmarkResult struct {
	Name            string
	Duration        time.Duration
	MemoryAllocated int64
	MemoryPeak      int64
	GCCycles        int32
	Operations      int64
	OpsPerSecond    float64
	MBPerSecond     float64
}

BenchmarkResult holds the results of a benchmark measurement.

type BenchmarkRunner

type BenchmarkRunner struct {
	// contains filtered or unexported fields
}

BenchmarkRunner provides utilities for running performance benchmarks.

func NewBenchmarkRunner

func NewBenchmarkRunner() *BenchmarkRunner

NewBenchmarkRunner creates a new benchmark runner.

func (*BenchmarkRunner) GetResults

func (r *BenchmarkRunner) GetResults() []BenchmarkResult

GetResults returns all benchmark results.

func (*BenchmarkRunner) PrintResults

func (r *BenchmarkRunner) PrintResults()

PrintResults prints benchmark results in a formatted way.

func (*BenchmarkRunner) RunBenchmark

func (r *BenchmarkRunner) RunBenchmark(name string, b *testing.B, benchmarkFunc func() error)

RunBenchmark executes a benchmark function and measures its performance.

type CoverageIssue

type CoverageIssue struct {
	Package  string
	Coverage float64
	Severity string
	Message  string
}

CoverageIssue represents a coverage validation issue.

func ValidateCoverage

func ValidateCoverage(results map[string]float64, thresholds CoverageThreshold) []CoverageIssue

ValidateCoverage checks if coverage meets the specified thresholds.

type CoverageReporter

type CoverageReporter struct {
	// contains filtered or unexported fields
}

CoverageReporter provides utilities for generating and managing test coverage reports.

func NewCoverageReporter

func NewCoverageReporter(outputDir string) (*CoverageReporter, error)

NewCoverageReporter creates a new coverage reporter with the specified output directory.

func (*CoverageReporter) Close

func (r *CoverageReporter) Close() error

Close cleans up temporary files.

func (*CoverageReporter) GenerateCombinedCoverage

func (r *CoverageReporter) GenerateCombinedCoverage(
	ctx context.Context,
	packagePaths []string,
) (map[string]float64, error)

GenerateCombinedCoverage generates coverage reports for multiple packages.

func (*CoverageReporter) GenerateCoverage

func (r *CoverageReporter) GenerateCoverage(ctx context.Context, packagePath string) (float64, error)

GenerateCoverage runs tests with coverage and generates reports. It returns the coverage percentage and any error.

func (*CoverageReporter) GetCoverageFiles

func (r *CoverageReporter) GetCoverageFiles() map[string]string

GetCoverageFiles returns the paths to generated coverage files.

func (*CoverageReporter) PrintCoverageSummary

func (r *CoverageReporter) PrintCoverageSummary(results map[string]float64)

PrintCoverageSummary prints a formatted coverage summary to stdout.

type CoverageThreshold

type CoverageThreshold struct {
	Excellent float64 // >= 80%
	Good      float64 // >= 60%
	Minimum   float64 // >= 40%
}

CoverageThreshold represents coverage thresholds for different quality levels.

func DefaultCoverageThresholds

func DefaultCoverageThresholds() CoverageThreshold

DefaultCoverageThresholds returns the default coverage thresholds.

type MaliciousArchiveGenerator

type MaliciousArchiveGenerator struct {
	// contains filtered or unexported fields
}

MaliciousArchiveGenerator creates archives that exploit common vulnerabilities in archive processing, based on OWASP Top 10 for file processing.

func NewMaliciousArchiveGenerator

func NewMaliciousArchiveGenerator() (*MaliciousArchiveGenerator, error)

NewMaliciousArchiveGenerator creates a new malicious archive generator.

func (*MaliciousArchiveGenerator) Close

func (g *MaliciousArchiveGenerator) Close() error

Close cleans up the temporary directory.

func (*MaliciousArchiveGenerator) GenerateFileCountBomb

func (g *MaliciousArchiveGenerator) GenerateFileCountBomb(outputPath string, fileCount int) error

GenerateFileCountBomb creates an archive with too many files. This tests for file count limits and resource exhaustion.

OWASP Risk: Resource Exhaustion via File Count

func (*MaliciousArchiveGenerator) GenerateLargeFileArchive

func (g *MaliciousArchiveGenerator) GenerateLargeFileArchive(outputPath string, size int64) error

GenerateLargeFileArchive creates an archive with a single very large file. This tests for memory exhaustion with individual large files.

OWASP Risk: Resource Exhaustion / Memory Exhaustion

func (*MaliciousArchiveGenerator) GenerateMalformedArchive

func (g *MaliciousArchiveGenerator) GenerateMalformedArchive(outputPath string) error

GenerateMalformedArchive creates an archive with structural issues. This tests for robustness against corrupted or malformed archives.

OWASP Risk: Input Validation / Malformed Input

func (*MaliciousArchiveGenerator) GenerateNestedArchive

func (g *MaliciousArchiveGenerator) GenerateNestedArchive(outputPath string, depth int) error

GenerateNestedArchive creates deeply nested directory structures. This tests for path length limits and deep recursion.

OWASP Risk: Resource Exhaustion / Deep Recursion

func (*MaliciousArchiveGenerator) GeneratePathTraversalArchive

func (g *MaliciousArchiveGenerator) GeneratePathTraversalArchive(outputPath string) error

GeneratePathTraversalArchive creates an archive with path traversal attempts. This tests for "../" and absolute path vulnerabilities.

OWASP Risk: Path Traversal Common patterns: ../../../etc/passwd, /etc/passwd, ..\\..\\windows\\system32

func (*MaliciousArchiveGenerator) GenerateSymlinkBomb

func (g *MaliciousArchiveGenerator) GenerateSymlinkBomb(outputPath string) error

GenerateSymlinkBomb creates an archive with dangerous symlinks. This tests for symlink-based path traversal and directory traversal.

OWASP Risk: Symlink Traversal / Directory Traversal

func (*MaliciousArchiveGenerator) GenerateZipBomb

func (g *MaliciousArchiveGenerator) GenerateZipBomb(outputPath string) error

GenerateZipBomb creates a zip bomb - a small archive that expands to a huge size. This tests for decompression bombs and resource exhaustion.

OWASP Risk: Decompression Bomb / Resource Exhaustion Strategy: Create many small files that expand to consume memory/disk

type MemoryProfileResult

type MemoryProfileResult struct {
	Allocated     uint64
	Freed         uint64
	HeapAlloc     uint64
	HeapSys       uint64
	StackSys      uint64
	GCCycles      uint32
	PauseTotalNs  uint64
	NumGoroutines int
}

MemoryProfileResult contains detailed memory profiling results.

func (MemoryProfileResult) Print

func (r MemoryProfileResult) Print()

Print prints memory profile results.

type MemoryProfiler

type MemoryProfiler struct {
	// contains filtered or unexported fields
}

MemoryProfiler provides detailed memory profiling utilities.

func (*MemoryProfiler) Start

func (p *MemoryProfiler) Start()

Start begins memory profiling.

func (*MemoryProfiler) Stop

Stop ends memory profiling and returns the results.

type PerformanceMetrics

type PerformanceMetrics struct {
	Duration    time.Duration
	MemoryDelta uint64
	GCCycles    uint32
	HeapObjects uint64
}

PerformanceMetrics contains performance measurement results.

func (PerformanceMetrics) Print

func (m PerformanceMetrics) Print()

Print prints performance metrics.

type PerformanceMonitor

type PerformanceMonitor struct {
	// contains filtered or unexported fields
}

PerformanceMonitor monitors system performance during operations.

func (*PerformanceMonitor) Start

func (p *PerformanceMonitor) Start()

Start begins performance monitoring.

func (*PerformanceMonitor) Stop

Stop ends performance monitoring and returns metrics.

type TestRegistry

type TestRegistry struct {
	// contains filtered or unexported fields
}

TestRegistry provides a Docker registry running in a test container. It automatically handles startup, shutdown, and cleanup.

func NewTestRegistry

func NewTestRegistry(ctx context.Context) (*TestRegistry, error)

NewTestRegistry creates and starts a new test registry container. It returns a TestRegistry that can be used to get the registry reference.

The registry is configured with: - Anonymous access (no authentication required) - Storage driver: filesystem (in-memory for testing)

Example usage:

registry, err := NewTestRegistry(ctx)
if err != nil {
    t.Fatal(err)
}
defer registry.Close(ctx)

ref := registry.Reference()
// Use ref like "localhost:5000/test-repo:latest"

func (*TestRegistry) Close

func (r *TestRegistry) Close(ctx context.Context) error

Close terminates the registry container and cleans up resources. It should be called in test cleanup (defer statement).

func (*TestRegistry) Reference

func (r *TestRegistry) Reference() string

Reference returns the full registry reference that can be used with the Client. The reference includes the host and port, e.g., "localhost:5000".

func (*TestRegistry) URL

func (r *TestRegistry) URL() string

URL returns the full registry URL including protocol.

func (*TestRegistry) WaitForReady

func (r *TestRegistry) WaitForReady(ctx context.Context, timeout time.Duration) error

WaitForReady waits for the registry to be ready to accept connections. It performs a health check by attempting to connect to the registry port.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL