PHPackages                             open-telemetry/test-utils - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. open-telemetry/test-utils

ActiveLibrary[Testing &amp; Quality](/categories/testing)

open-telemetry/test-utils
=========================

Testing utilities for OpenTelemetry PHP instrumentations

0.2.1(1y ago)03.5k↓34.8%1Apache-2.0PHP

Since Apr 8Pushed 1y ago4 watchersCompare

[ Source](https://github.com/opentelemetry-php/contrib-utils-test)[ Packagist](https://packagist.org/packages/open-telemetry/test-utils)[ RSS](/packages/open-telemetry-test-utils/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (9)Versions (4)Used By (1)

[![Releases](https://camo.githubusercontent.com/46e38a504120203bf7615645011bcf2bb834e03e8eb0bc8e0f4864c729fd5baf/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f72656c65617365732d707572706c65)](https://github.com/opentelemetry-php/contrib-test-utils/releases)[![Issues](https://camo.githubusercontent.com/b9b31135f113cdb6e2b662b4040276044ee0803567bc17688eaf4386f797ea50/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6973737565732d70696e6b)](https://github.com/open-telemetry/opentelemetry-php/issues)[![Source](https://camo.githubusercontent.com/e27dd1126a60abf1c26521d893d9f235ef342a76231c2428ddbc4651185bd626/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f736f757263652d636f6e747269622d677265656e)](https://github.com/open-telemetry/opentelemetry-php-contrib/tree/main/src/Utils/Test)[![Mirror](https://camo.githubusercontent.com/2f9050293ab0c0d9471e618215bc7417a63b6873c960e1605bddb69b1911fa4c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d6972726f722d6f70656e74656c656d657472792d2d7068702d2d636f6e747269622d626c7565)](https://github.com/opentelemetry-php/contrib-test-utils)[![Latest Version](https://camo.githubusercontent.com/56c626d6b63be63762aebdcf6aa3213f6433e4dbcf4204bd8cb72bb361e703e0/687474703a2f2f706f7365722e707567782e6f72672f6f70656e2d74656c656d657472792f746573742d7574696c732f762f756e737461626c65)](https://packagist.org/packages/open-telemetry/test-utils/)[![Stable](https://camo.githubusercontent.com/0a126d08d6e3bfb42a4a48a9f6470cd0013012b73f326fa9100fd2daee1c96d9/687474703a2f2f706f7365722e707567782e6f72672f6f70656e2d74656c656d657472792f746573742d7574696c732f762f737461626c65)](https://packagist.org/packages/open-telemetry/test-utils/)

This is a read-only subtree split of .

OpenTelemetry Test Utilities
============================

[](#opentelemetry-test-utilities)

This package provides testing utilities for OpenTelemetry PHP instrumentations. It includes tools to help test and validate trace structures, span relationships, and other OpenTelemetry-specific functionality.

Features
--------

[](#features)

### TraceStructureAssertionTrait

[](#tracestructureassertiontrait)

The `TraceStructureAssertionTrait` provides methods to assess if spans match an expected trace structure. It's particularly useful for testing complex trace hierarchies and relationships between spans.

Key features:

- Support for hierarchical span relationships
- Verification of span names, kinds, attributes, events, and status
- Flexible matching with strict and non-strict modes
- Support for PHPUnit matchers/constraints for more flexible assertions
- Detailed error messages for failed assertions
- Two interfaces: array-based and fluent

Requirements
------------

[](#requirements)

- PHP 7.4 or higher
- OpenTelemetry SDK and API (for testing)
- PHPUnit 9.5 or higher

Usage
-----

[](#usage)

### TraceStructureAssertionTrait

[](#tracestructureassertiontrait-1)

Add the trait to your test class:

```
use OpenTelemetry\TestUtils\TraceStructureAssertionTrait;
use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    use TraceStructureAssertionTrait;

    // Your test methods...
}
```

#### Array-Based Interface

[](#array-based-interface)

Use the `assertTraceStructure` method to verify trace structures using an array-based approach:

```
public function testTraceStructure(): void
{
    // Create spans using the OpenTelemetry SDK
    // ...

    // Define the expected structure
    $expectedStructure = [
        [
            'name' => 'root-span',
            'kind' => SpanKind::KIND_SERVER,
            'children' => [
                [
                    'name' => 'child-span',
                    'kind' => SpanKind::KIND_INTERNAL,
                    'attributes' => [
                        'attribute.one' => 'value1',
                        'attribute.two' => 42,
                    ],
                    'events' => [
                        [
                            'name' => 'event.processed',
                            'attributes' => [
                                'processed.id' => 'abc123',
                            ],
                        ],
                    ],
                ],
                [
                    'name' => 'another-child-span',
                    'kind' => SpanKind::KIND_CLIENT,
                    'status' => [
                        'code' => StatusCode::STATUS_ERROR,
                        'description' => 'Something went wrong',
                    ],
                ],
            ],
        ],
    ];

    // Assert the trace structure
    $this->assertTraceStructure($spans, $expectedStructure);
}
```

The `assertTraceStructure` method takes the following parameters:

- `$spans`: An array or ArrayObject of spans (typically from an InMemoryExporter)
- `$expectedStructure`: An array defining the expected structure of the trace
- `$strict` (optional): Whether to perform strict matching (all attributes must match)

#### Fluent Interface

[](#fluent-interface)

Use the `assertTrace` method to verify trace structures using a fluent, chainable interface:

```
public function testTraceStructure(): void
{
    // Create spans using the OpenTelemetry SDK
    // ...

    // Assert the trace structure using the fluent interface
    $this->assertTrace($spans)
        ->hasRootSpan('root-span')
            ->withKind(SpanKind::KIND_SERVER)
            ->hasChild('child-span')
                ->withKind(SpanKind::KIND_INTERNAL)
                ->withAttribute('attribute.one', 'value1')
                ->withAttribute('attribute.two', 42)
                ->hasEvent('event.processed')
                    ->withAttribute('processed.id', 'abc123')
                ->end()
            ->end()
            ->hasChild('another-child-span')
                ->withKind(SpanKind::KIND_CLIENT)
                ->withStatus(StatusCode::STATUS_ERROR, 'Something went wrong')
            ->end()
        ->end();
}
```

The fluent interface provides the following methods:

**TraceAssertion:**

- `hasRootSpan(string|Constraint $name)`: Assert that the trace has a root span with the given name
- `hasRootSpans(int $count)`: Assert that the trace has the expected number of root spans
- `inStrictMode()`: Enable strict mode for all assertions

**SpanAssertion:**

- `withKind(int|Constraint $kind)`: Assert that the span has the expected kind
- `withAttribute(string $key, mixed|Constraint $value)`: Assert that the span has an attribute with the expected key and value
- `withAttributes(array $attributes)`: Assert that the span has the expected attributes
- `withStatus(int|Constraint $code, string|Constraint|null $description = null)`: Assert that the span has the expected status
- `hasEvent(string|Constraint $name)`: Assert that the span has an event with the expected name
- `hasChild(string|Constraint $name)`: Assert that the span has a child span with the expected name
- `hasChildren(int $count)`: Assert that the span has the expected number of children
- `end()`: Return to the parent assertion

**SpanEventAssertion:**

- `withAttribute(string $key, mixed|Constraint $value)`: Assert that the event has an attribute with the expected key and value
- `withAttributes(array $attributes)`: Assert that the event has the expected attributes
- `end()`: Return to the parent span assertion

### Using PHPUnit Matchers

[](#using-phpunit-matchers)

You can use PHPUnit constraints/matchers for more flexible assertions with both interfaces:

#### Array-Based Interface with Matchers

[](#array-based-interface-with-matchers)

```
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\IsIdentical;
use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\StringContains;

// Define the expected structure with matchers
$expectedStructure = [
    [
        'name' => 'root-span',
        'kind' => new IsIdentical(SpanKind::KIND_SERVER),
        'attributes' => [
            'string.attribute' => new StringContains('World'),
            'numeric.attribute' => new Callback(function ($value) {
                return $value > 40 || $value === 42;
            }),
            'boolean.attribute' => new IsType('boolean'),
            'array.attribute' => new Callback(function ($value) {
                return is_array($value) && count($value) === 3 && in_array('b', $value);
            }),
        ],
        'children' => [
            [
                'name' => new RegularExpression('/child-span-\d+/'),
                'kind' => SpanKind::KIND_INTERNAL,
                'attributes' => [
                    'timestamp' => new IsType('integer'),
                ],
                'events' => [
                    [
                        'name' => 'process.start',
                        'attributes' => [
                            'process.id' => new IsType('integer'),
                            'process.name' => new StringContains('process'),
                        ],
                    ],
                ],
            ],
        ],
    ],
];

// Assert the trace structure with matchers
$this->assertTraceStructure($spans, $expectedStructure);
```

#### Fluent Interface with Matchers

[](#fluent-interface-with-matchers)

```
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\IsIdentical;
use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\Constraint\RegularExpression;
use PHPUnit\Framework\Constraint\StringContains;

// Assert the trace structure using the fluent interface with matchers
$this->assertTrace($spans)
    ->hasRootSpan('root-span')
        ->withKind(new IsIdentical(SpanKind::KIND_SERVER))
        ->withAttribute('string.attribute', new StringContains('World'))
        ->withAttribute('numeric.attribute', new Callback(function ($value) {
            return $value > 40 || $value === 42;
        }))
        ->withAttribute('boolean.attribute', new IsType('boolean'))
        ->withAttribute('array.attribute', new Callback(function ($value) {
            return is_array($value) && count($value) === 3 && in_array('b', $value);
        }))
        ->hasChild(new RegularExpression('/child-span-\d+/'))
            ->withKind(SpanKind::KIND_INTERNAL)
            ->withAttribute('timestamp', new IsType('integer'))
            ->hasEvent('process.start')
                ->withAttribute('process.id', new IsType('integer'))
                ->withAttribute('process.name', new StringContains('process'))
            ->end()
        ->end()
    ->end();
```

Supported PHPUnit matchers include:

- `StringContains` for partial string matching
- `RegularExpression` for pattern matching
- `IsIdentical` for strict equality
- `IsEqual` for loose equality
- `IsType` for type checking
- `Callback` for custom validation logic

Installation via composer
-------------------------

[](#installation-via-composer)

```
$ composer require --dev open-telemetry/test-utils
```

Installing dependencies and executing tests
-------------------------------------------

[](#installing-dependencies-and-executing-tests)

From the Test Utils subdirectory:

```
$ composer install
$ ./vendor/bin/phpunit tests
```

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance48

Moderate activity, may be stable

Popularity22

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity29

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

3

Last Release

392d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4978962?v=4)[Brett McBride](/maintainers/brettmc)[@brettmc](https://github.com/brettmc)

---

Top Contributors

[![cedricziel](https://avatars.githubusercontent.com/u/418970?v=4)](https://github.com/cedricziel "cedricziel (3 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/open-telemetry-test-utils/health.svg)

```
[![Health](https://phpackages.com/badges/open-telemetry-test-utils/health.svg)](https://phpackages.com/packages/open-telemetry-test-utils)
```

###  Alternatives

[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k551.7M682](/packages/phpspec-prophecy)[brianium/paratest

Parallel testing for PHP

2.5k118.8M754](/packages/brianium-paratest)[beberlei/assert

Thin assertion library for input validation in business models.

2.4k96.9M570](/packages/beberlei-assert)[mikey179/vfsstream

Virtual file system to mock the real file system in unit tests.

1.4k108.0M2.7k](/packages/mikey179-vfsstream)[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[phpspec/phpspec

Specification-oriented BDD framework for PHP 7.1+

1.9k36.7M3.1k](/packages/phpspec-phpspec)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
