or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

assertions.mdexporters.mdindex.mdjunit-integration.mdtest-builders.mdutilities.md

test-builders.mddocs/

0

# Test Data Builders

1

2

Builder classes for creating test instances of OpenTelemetry telemetry data with full control over all properties and metadata. These builders enable creation of SpanData, MetricData, and LogRecordData objects for use in unit tests and test fixtures.

3

4

## Capabilities

5

6

### Span Data Builder

7

8

Builder for creating test SpanData instances with complete control over all span properties.

9

10

```java { .api }

11

abstract class TestSpanData implements SpanData {

12

// Factory method

13

static Builder builder();

14

15

static class Builder {

16

// Identity and context

17

Builder setSpanContext(SpanContext context);

18

Builder setParentSpanContext(SpanContext parentContext);

19

Builder setResource(Resource resource);

20

Builder setInstrumentationScopeInfo(InstrumentationScopeInfo instrumentationScopeInfo);

21

22

// Basic properties

23

Builder setName(String name);

24

Builder setKind(SpanKind kind);

25

Builder setStartEpochNanos(long startEpochNanos);

26

Builder setEndEpochNanos(long endEpochNanos);

27

28

// Data and metadata

29

Builder setAttributes(Attributes attributes);

30

Builder setEvents(List<EventData> events);

31

Builder setLinks(List<LinkData> links);

32

Builder setStatus(StatusData status);

33

34

// State and counts

35

Builder setHasEnded(boolean hasEnded);

36

Builder setTotalRecordedEvents(int totalRecordedEvents);

37

Builder setTotalRecordedLinks(int totalRecordedLinks);

38

Builder setTotalAttributeCount(int totalAttributeCount);

39

40

// Build method

41

TestSpanData build();

42

}

43

}

44

```

45

46

Usage examples:

47

48

```java

49

// Create a basic test span

50

TestSpanData span = TestSpanData.builder()

51

.setName("test-operation")

52

.setKind(SpanKind.INTERNAL)

53

.setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()))

54

.setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis() + 100))

55

.setAttributes(Attributes.of(

56

AttributeKey.stringKey("service.name"), "test-service",

57

AttributeKey.longKey("operation.id"), 12345L

58

))

59

.setHasEnded(true)

60

.build();

61

62

// Create a span with custom context

63

SpanContext spanContext = SpanContext.create(

64

"12345678901234567890123456789012",

65

"1234567890123456",

66

TraceFlags.getSampled(),

67

TraceState.getDefault()

68

);

69

70

TestSpanData spanWithContext = TestSpanData.builder()

71

.setSpanContext(spanContext)

72

.setName("custom-context-span")

73

.setStartEpochNanos(1000000000L)

74

.setEndEpochNanos(2000000000L)

75

.build();

76

77

// Create a span with events and links

78

List<EventData> events = Arrays.asList(

79

EventData.create(1500000000L, "request.start"),

80

EventData.create(1800000000L, "request.end",

81

Attributes.of(AttributeKey.longKey("response.size"), 1024L))

82

);

83

84

List<LinkData> links = Arrays.asList(

85

LinkData.create(SpanContext.create("other-trace-id", "other-span-id",

86

TraceFlags.getDefault(), TraceState.getDefault()))

87

);

88

89

TestSpanData complexSpan = TestSpanData.builder()

90

.setName("complex-operation")

91

.setEvents(events)

92

.setLinks(links)

93

.setStatus(StatusData.create(StatusCode.OK, "Operation completed"))

94

.setTotalRecordedEvents(2)

95

.setTotalRecordedLinks(1)

96

.build();

97

```

98

99

### Metric Data Builder

100

101

Builder for creating test MetricData instances supporting all metric types (gauges, sums, histograms, exponential histograms, summaries).

102

103

```java { .api }

104

abstract class TestMetricData implements MetricData {

105

// Factory method

106

static Builder builder();

107

108

static class Builder {

109

// Basic properties

110

Builder setResource(Resource resource);

111

Builder setInstrumentationScopeInfo(InstrumentationScopeInfo instrumentationScopeInfo);

112

Builder setName(String name);

113

Builder setDescription(String description);

114

Builder setUnit(String unit);

115

116

// Data type specific setters

117

Builder setDoubleGaugeData(GaugeData<DoublePointData> data);

118

Builder setLongGaugeData(GaugeData<LongPointData> data);

119

Builder setDoubleSumData(SumData<DoublePointData> data);

120

Builder setLongSumData(SumData<LongPointData> data);

121

Builder setHistogramData(HistogramData data);

122

Builder setExponentialHistogramData(ExponentialHistogramData data);

123

Builder setSummaryData(SummaryData data);

124

125

// Build method

126

TestMetricData build();

127

}

128

}

129

```

130

131

Usage examples:

132

133

```java

134

// Create a double gauge metric

135

GaugeData<DoublePointData> gaugeData = ImmutableGaugeData.create(

136

Arrays.asList(

137

ImmutableDoublePointData.create(

138

1000000000L, // startEpochNanos

139

2000000000L, // epochNanos

140

Attributes.of(AttributeKey.stringKey("host"), "server1"),

141

85.5 // value

142

)

143

)

144

);

145

146

TestMetricData gaugeMetric = TestMetricData.builder()

147

.setName("cpu.usage")

148

.setDescription("CPU usage percentage")

149

.setUnit("%")

150

.setDoubleGaugeData(gaugeData)

151

.setResource(Resource.builder()

152

.put(ResourceAttributes.SERVICE_NAME, "monitoring-service")

153

.build())

154

.build();

155

156

// Create a counter sum metric

157

SumData<LongPointData> sumData = ImmutableSumData.create(

158

true, // isMonotonic

159

AggregationTemporality.CUMULATIVE,

160

Arrays.asList(

161

ImmutableLongPointData.create(

162

1000000000L,

163

2000000000L,

164

Attributes.of(AttributeKey.stringKey("endpoint"), "/api/users"),

165

42L // value

166

)

167

)

168

);

169

170

TestMetricData counterMetric = TestMetricData.builder()

171

.setName("http.requests.total")

172

.setDescription("Total number of HTTP requests")

173

.setUnit("1")

174

.setLongSumData(sumData)

175

.build();

176

177

// Create a histogram metric

178

HistogramData histogramData = ImmutableHistogramData.create(

179

AggregationTemporality.CUMULATIVE,

180

Arrays.asList(

181

ImmutableHistogramPointData.create(

182

1000000000L,

183

2000000000L,

184

Attributes.of(AttributeKey.stringKey("method"), "GET"),

185

1250.5, // sum

186

false, // hasMin

187

0.0, // min

188

false, // hasMax

189

0.0, // max

190

Arrays.asList(0.0, 10.0, 50.0, 100.0, 500.0), // boundaries

191

Arrays.asList(5L, 15L, 25L, 10L, 3L), // counts

192

100L // total count

193

)

194

)

195

);

196

197

TestMetricData histogramMetric = TestMetricData.builder()

198

.setName("http.request.duration")

199

.setDescription("HTTP request duration")

200

.setUnit("ms")

201

.setHistogramData(histogramData)

202

.build();

203

```

204

205

### Log Record Data Builder

206

207

Builder for creating test LogRecordData instances with full control over log properties and metadata.

208

209

```java { .api }

210

abstract class TestLogRecordData implements LogRecordData {

211

// Factory method

212

static Builder builder();

213

214

static class Builder {

215

// Basic properties

216

Builder setResource(Resource resource);

217

Builder setInstrumentationScopeInfo(InstrumentationScopeInfo instrumentationScopeInfo);

218

219

// Timing

220

Builder setTimestamp(Instant instant);

221

Builder setTimestamp(long timestamp, TimeUnit unit);

222

Builder setObservedTimestamp(Instant instant);

223

Builder setObservedTimestamp(long timestamp, TimeUnit unit);

224

225

// Content and severity

226

Builder setBody(String body);

227

Builder setBodyValue(Value<?> body);

228

Builder setSeverity(Severity severity);

229

Builder setSeverityText(String severityText);

230

231

// Context and metadata

232

Builder setSpanContext(SpanContext spanContext);

233

Builder setAttributes(Attributes attributes);

234

Builder setTotalAttributeCount(int totalAttributeCount);

235

Builder setEventName(String eventName);

236

237

// Build method

238

TestLogRecordData build();

239

}

240

}

241

```

242

243

Usage examples:

244

245

```java

246

// Create a basic log record

247

TestLogRecordData logRecord = TestLogRecordData.builder()

248

.setBody("User authentication successful")

249

.setSeverity(Severity.INFO)

250

.setSeverityText("INFO")

251

.setTimestamp(Instant.now())

252

.setObservedTimestamp(Instant.now().plusMillis(10))

253

.setAttributes(Attributes.of(

254

AttributeKey.stringKey("user.id"), "12345",

255

AttributeKey.stringKey("auth.method"), "oauth2"

256

))

257

.build();

258

259

// Create a log record with span context

260

SpanContext spanContext = SpanContext.create(

261

"12345678901234567890123456789012",

262

"1234567890123456",

263

TraceFlags.getSampled(),

264

TraceState.getDefault()

265

);

266

267

TestLogRecordData contextualLog = TestLogRecordData.builder()

268

.setBody("Processing user request")

269

.setSeverity(Severity.DEBUG)

270

.setSpanContext(spanContext)

271

.setTimestamp(1000000000L, TimeUnit.NANOSECONDS)

272

.setAttributes(Attributes.of(

273

AttributeKey.stringKey("request.id"), "req-789"

274

))

275

.setResource(Resource.builder()

276

.put(ResourceAttributes.SERVICE_NAME, "user-service")

277

.put(ResourceAttributes.SERVICE_VERSION, "1.2.3")

278

.build())

279

.build();

280

281

// Create an error log record

282

TestLogRecordData errorLog = TestLogRecordData.builder()

283

.setBody("Database connection failed")

284

.setSeverity(Severity.ERROR)

285

.setSeverityText("ERROR")

286

.setTimestamp(Instant.parse("2023-01-01T12:00:00Z"))

287

.setAttributes(Attributes.of(

288

AttributeKey.stringKey("db.host"), "db.example.com",

289

AttributeKey.longKey("db.port"), 5432L,

290

AttributeKey.stringKey("error.type"), "ConnectionTimeout"

291

))

292

.setTotalAttributeCount(3)

293

.build();

294

295

// Create a structured log with complex body

296

Value<?> structuredBody = Value.of(Map.of(

297

"event", "user.created",

298

"user_id", 12345,

299

"metadata", Map.of(

300

"source", "registration_form",

301

"campaign", "spring_2023"

302

)

303

));

304

305

TestLogRecordData structuredLog = TestLogRecordData.builder()

306

.setBodyValue(structuredBody)

307

.setSeverity(Severity.INFO)

308

.setEventName("user.created")

309

.setTimestamp(Instant.now())

310

.build();

311

```

312

313

## Advanced Builder Patterns

314

315

### Reusable Builder Configuration

316

317

```java

318

// Create a base builder with common configuration

319

TestSpanData.Builder baseSpanBuilder = TestSpanData.builder()

320

.setResource(Resource.builder()

321

.put(ResourceAttributes.SERVICE_NAME, "test-service")

322

.put(ResourceAttributes.SERVICE_VERSION, "1.0.0")

323

.build())

324

.setInstrumentationScopeInfo(

325

InstrumentationScopeInfo.create("test-instrumentation", "1.0.0"));

326

327

// Create multiple spans with shared configuration

328

TestSpanData span1 = baseSpanBuilder

329

.setName("operation-1")

330

.setStartEpochNanos(1000000000L)

331

.setEndEpochNanos(1100000000L)

332

.build();

333

334

TestSpanData span2 = baseSpanBuilder

335

.setName("operation-2")

336

.setStartEpochNanos(1200000000L)

337

.setEndEpochNanos(1300000000L)

338

.build();

339

```

340

341

### Building Test Traces

342

343

```java

344

// Create a complete trace with parent-child relationships

345

String traceId = "12345678901234567890123456789012";

346

347

// Parent span

348

TestSpanData parentSpan = TestSpanData.builder()

349

.setSpanContext(SpanContext.create(traceId, "1111111111111111",

350

TraceFlags.getSampled(), TraceState.getDefault()))

351

.setName("parent-operation")

352

.setKind(SpanKind.SERVER)

353

.setStartEpochNanos(1000000000L)

354

.setEndEpochNanos(5000000000L)

355

.build();

356

357

// Child spans

358

TestSpanData child1 = TestSpanData.builder()

359

.setSpanContext(SpanContext.create(traceId, "2222222222222222",

360

TraceFlags.getSampled(), TraceState.getDefault()))

361

.setParentSpanContext(parentSpan.getSpanContext())

362

.setName("child-operation-1")

363

.setKind(SpanKind.INTERNAL)

364

.setStartEpochNanos(1500000000L)

365

.setEndEpochNanos(2500000000L)

366

.build();

367

368

TestSpanData child2 = TestSpanData.builder()

369

.setSpanContext(SpanContext.create(traceId, "3333333333333333",

370

TraceFlags.getSampled(), TraceState.getDefault()))

371

.setParentSpanContext(parentSpan.getSpanContext())

372

.setName("child-operation-2")

373

.setKind(SpanKind.INTERNAL)

374

.setStartEpochNanos(3000000000L)

375

.setEndEpochNanos(4000000000L)

376

.build();

377

378

// Use in assertions

379

List<SpanData> traceSpans = Arrays.asList(parentSpan, child1, child2);

380

assertTraces(traceSpans)

381

.hasTracesSatisfyingExactly(

382

trace -> trace.hasSpansSatisfyingExactly(

383

span -> assertThat(span).hasName("parent-operation"),

384

span -> assertThat(span).hasName("child-operation-1"),

385

span -> assertThat(span).hasName("child-operation-2")

386

)

387

);

388

```

389

390

## Types

391

392

```java { .api }

393

// Core OpenTelemetry data interfaces implemented by test builders

394

interface SpanData {

395

SpanContext getSpanContext();

396

SpanContext getParentSpanContext();

397

Resource getResource();

398

InstrumentationScopeInfo getInstrumentationScopeInfo();

399

String getName();

400

SpanKind getKind();

401

long getStartEpochNanos();

402

long getEndEpochNanos();

403

Attributes getAttributes();

404

List<EventData> getEvents();

405

List<LinkData> getLinks();

406

StatusData getStatus();

407

boolean hasEnded();

408

int getTotalRecordedEvents();

409

int getTotalRecordedLinks();

410

int getTotalAttributeCount();

411

}

412

413

interface MetricData {

414

Resource getResource();

415

InstrumentationScopeInfo getInstrumentationScopeInfo();

416

String getName();

417

String getDescription();

418

String getUnit();

419

MetricDataType getType();

420

Data<?> getData();

421

}

422

423

interface LogRecordData {

424

Resource getResource();

425

InstrumentationScopeInfo getInstrumentationScopeInfo();

426

long getTimestampEpochNanos();

427

long getObservedTimestampEpochNanos();

428

SpanContext getSpanContext();

429

Severity getSeverity();

430

String getSeverityText();

431

Value<?> getBodyValue();

432

Attributes getAttributes();

433

int getTotalAttributeCount();

434

}

435

436

// Supporting data types

437

interface Attributes {

438

Map<AttributeKey<?>, Object> asMap();

439

int size();

440

boolean isEmpty();

441

}

442

443

interface EventData {

444

String getName();

445

long getEpochNanos();

446

Attributes getAttributes();

447

int getTotalAttributeCount();

448

}

449

450

interface LinkData {

451

SpanContext getSpanContext();

452

Attributes getAttributes();

453

int getTotalAttributeCount();

454

}

455

456

interface StatusData {

457

StatusCode getStatusCode();

458

String getDescription();

459

}

460

461

// Enums and value types

462

enum SpanKind { INTERNAL, SERVER, CLIENT, PRODUCER, CONSUMER }

463

enum StatusCode { UNSET, OK, ERROR }

464

enum Severity { TRACE, DEBUG, INFO, WARN, ERROR, FATAL }

465

enum TraceFlags { /* flag values */ }

466

467

class SpanContext {

468

static SpanContext create(String traceId, String spanId, TraceFlags traceFlags, TraceState traceState);

469

String getTraceId();

470

String getSpanId();

471

TraceFlags getTraceFlags();

472

TraceState getTraceState();

473

}

474

```