or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdindex.mdrequest-verification.mdresponse-configuration.mdserver-management.md

response-configuration.mddocs/

0

# Response Configuration

1

2

Comprehensive response building capabilities for creating scriptable HTTP responses. MockResponse provides extensive configuration options including status codes, headers, body content, delays, throttling, and connection behavior policies.

3

4

## Capabilities

5

6

### MockResponse Class

7

8

Represents a scriptable HTTP response to be served by MockWebServer.

9

10

```kotlin { .api }

11

/**

12

* Represents a scriptable HTTP response. Implements Cloneable for creating response templates.

13

*/

14

class MockResponse : Cloneable {

15

/**

16

* Default constructor creates a new MockResponse with default settings

17

*/

18

constructor()

19

20

/**

21

* Create a copy of the response

22

* @returns New MockResponse instance with identical configuration

23

*/

24

fun clone(): MockResponse

25

}

26

```

27

28

### Status and Response Codes

29

30

Configure HTTP response status lines and codes.

31

32

```kotlin { .api }

33

/**

34

* Set the complete HTTP status line (e.g., "HTTP/1.1 200 OK")

35

* @param status Full status line string

36

* @returns This MockResponse for method chaining

37

*/

38

fun setStatus(status: String): MockResponse

39

40

/**

41

* Set response code with default reason phrase for the code

42

* @param code HTTP status code (e.g., 200, 404, 500)

43

* @returns This MockResponse for method chaining

44

*/

45

fun setResponseCode(code: Int): MockResponse

46

```

47

48

**Usage Examples:**

49

50

```kotlin

51

// Set specific status codes

52

val okResponse = MockResponse().setResponseCode(200)

53

val notFoundResponse = MockResponse().setResponseCode(404)

54

val serverErrorResponse = MockResponse().setResponseCode(500)

55

56

// Set custom status line

57

val customResponse = MockResponse().setStatus("HTTP/1.1 418 I'm a teapot")

58

```

59

60

### Headers Management

61

62

Comprehensive header manipulation including adding, setting, and removing headers.

63

64

```kotlin { .api }

65

/**

66

* Remove all headers

67

* @returns This MockResponse for method chaining

68

*/

69

fun clearHeaders(): MockResponse

70

71

/**

72

* Add header from "name: value" string format

73

* @param header Header string in "name: value" format

74

* @returns This MockResponse for method chaining

75

*/

76

fun addHeader(header: String): MockResponse

77

78

/**

79

* Add header with separate name and value

80

* @param name Header name

81

* @param value Header value (converted to string)

82

* @returns This MockResponse for method chaining

83

*/

84

fun addHeader(name: String, value: Any): MockResponse

85

86

/**

87

* Add header without validation (for testing malformed headers)

88

* @param name Header name

89

* @param value Header value

90

* @returns This MockResponse for method chaining

91

*/

92

fun addHeaderLenient(name: String, value: Any): MockResponse

93

94

/**

95

* Replace all headers with given name

96

* @param name Header name

97

* @param value New header value

98

* @returns This MockResponse for method chaining

99

*/

100

fun setHeader(name: String, value: Any): MockResponse

101

102

/**

103

* Remove all headers with given name

104

* @param name Header name to remove

105

* @returns This MockResponse for method chaining

106

*/

107

fun removeHeader(name: String): MockResponse

108

109

/**

110

* Set all headers at once

111

* @param headers Headers instance containing all headers

112

* @returns This MockResponse for method chaining

113

*/

114

fun setHeaders(headers: Headers): MockResponse

115

```

116

117

**Usage Examples:**

118

119

```kotlin

120

val response = MockResponse()

121

.setResponseCode(200)

122

.addHeader("Content-Type", "application/json")

123

.addHeader("X-Custom-Header", "custom-value")

124

.setHeader("Cache-Control", "no-cache")

125

126

// Add multiple cookies

127

response

128

.addHeader("Set-Cookie", "session=abc123; Path=/")

129

.addHeader("Set-Cookie", "theme=dark; Path=/; Max-Age=3600")

130

131

// JSON API response headers

132

val jsonResponse = MockResponse()

133

.setResponseCode(200)

134

.addHeader("Content-Type", "application/json; charset=utf-8")

135

.addHeader("Access-Control-Allow-Origin", "*")

136

.setBody("""{"status": "success"}""")

137

```

138

139

### Body Content

140

141

Configure response body content with various encoding options.

142

143

```kotlin { .api }

144

/**

145

* Get response body as Buffer

146

* @returns Buffer containing response body or null if not set

147

*/

148

fun getBody(): Buffer?

149

150

/**

151

* Set response body from Buffer

152

* @param body Buffer containing response data

153

* @returns This MockResponse for method chaining

154

*/

155

fun setBody(body: Buffer): MockResponse

156

157

/**

158

* Set response body from UTF-8 string

159

* @param body String content for response body

160

* @returns This MockResponse for method chaining

161

*/

162

fun setBody(body: String): MockResponse

163

164

/**

165

* Set chunked response body from Buffer

166

* @param body Buffer containing response data

167

* @param maxChunkSize Maximum size of each chunk in bytes

168

* @returns This MockResponse for method chaining

169

*/

170

fun setChunkedBody(body: Buffer, maxChunkSize: Int): MockResponse

171

172

/**

173

* Set chunked response body from string

174

* @param body String content for response body

175

* @param maxChunkSize Maximum size of each chunk in bytes

176

* @returns This MockResponse for method chaining

177

*/

178

fun setChunkedBody(body: String, maxChunkSize: Int): MockResponse

179

```

180

181

**Usage Examples:**

182

183

```kotlin

184

// Simple text response

185

val textResponse = MockResponse()

186

.setResponseCode(200)

187

.addHeader("Content-Type", "text/plain")

188

.setBody("Hello, World!")

189

190

// JSON response

191

val jsonResponse = MockResponse()

192

.setResponseCode(201)

193

.addHeader("Content-Type", "application/json")

194

.setBody("""

195

{

196

"id": 123,

197

"name": "John Doe",

198

"email": "john@example.com"

199

}

200

""".trimIndent())

201

202

// Large chunked response

203

val chunkedResponse = MockResponse()

204

.setResponseCode(200)

205

.addHeader("Content-Type", "text/plain")

206

.setChunkedBody("A".repeat(10000), 1024) // 10KB in 1KB chunks

207

208

// Binary data from Buffer

209

val buffer = Buffer().writeUtf8("Binary content")

210

val binaryResponse = MockResponse()

211

.setResponseCode(200)

212

.addHeader("Content-Type", "application/octet-stream")

213

.setBody(buffer)

214

```

215

216

### Response Timing and Throttling

217

218

Control response timing, delays, and bandwidth throttling.

219

220

```kotlin { .api }

221

/**

222

* Throttle response body transmission

223

* @param bytesPerPeriod Number of bytes to send per time period

224

* @param period Duration of each time period

225

* @param unit Time unit for the period

226

* @returns This MockResponse for method chaining

227

*/

228

fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit): MockResponse

229

230

/**

231

* Get throttle period in specified units

232

* @param unit Time unit for result

233

* @returns Throttle period in specified units

234

*/

235

fun getThrottlePeriod(unit: TimeUnit): Long

236

237

/**

238

* Set delay before body transmission starts

239

* @param delay Delay duration

240

* @param unit Time unit for delay

241

* @returns This MockResponse for method chaining

242

*/

243

fun setBodyDelay(delay: Long, unit: TimeUnit): MockResponse

244

245

/**

246

* Get body delay in specified units

247

* @param unit Time unit for result

248

* @returns Body delay in specified units

249

*/

250

fun getBodyDelay(unit: TimeUnit): Long

251

252

/**

253

* Set delay before headers are sent

254

* @param delay Delay duration

255

* @param unit Time unit for delay

256

* @returns This MockResponse for method chaining

257

*/

258

fun setHeadersDelay(delay: Long, unit: TimeUnit): MockResponse

259

260

/**

261

* Get headers delay in specified units

262

* @param unit Time unit for result

263

* @returns Headers delay in specified units

264

*/

265

fun getHeadersDelay(unit: TimeUnit): Long

266

```

267

268

**Usage Examples:**

269

270

```kotlin

271

// Simulate slow network connection

272

val slowResponse = MockResponse()

273

.setResponseCode(200)

274

.addHeader("Content-Type", "application/json")

275

.setBody("""{"data": "large response"}""")

276

.throttleBody(1024, 1, TimeUnit.SECONDS) // 1KB per second

277

278

// Add delays to simulate server processing time

279

val delayedResponse = MockResponse()

280

.setResponseCode(200)

281

.setHeadersDelay(500, TimeUnit.MILLISECONDS) // 500ms before headers

282

.setBodyDelay(1, TimeUnit.SECONDS) // 1s before body

283

.setBody("Processed data")

284

285

// Simulate very slow server

286

val verySlowResponse = MockResponse()

287

.setResponseCode(200)

288

.setBody("Slow response")

289

.throttleBody(10, 1, TimeUnit.SECONDS) // Only 10 bytes per second

290

```

291

292

### Connection Policies

293

294

Control socket behavior and connection lifecycle using SocketPolicy.

295

296

```kotlin { .api }

297

/**

298

* Set socket behavior policy

299

* @param socketPolicy Policy defining connection behavior

300

* @returns This MockResponse for method chaining

301

*/

302

fun setSocketPolicy(socketPolicy: SocketPolicy): MockResponse

303

304

/**

305

* Socket behavior policy (default: KEEP_OPEN)

306

*/

307

var socketPolicy: SocketPolicy

308

```

309

310

**Usage Examples:**

311

312

```kotlin

313

// Normal HTTP/1.1 behavior (default)

314

val keepAliveResponse = MockResponse()

315

.setResponseCode(200)

316

.setBody("Normal response")

317

.setSocketPolicy(SocketPolicy.KEEP_OPEN)

318

319

// HTTP/1.0 behavior - close after response

320

val http10Response = MockResponse()

321

.setResponseCode(200)

322

.setBody("HTTP/1.0 style")

323

.setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)

324

325

// Simulate network failures

326

val failedConnectionResponse = MockResponse()

327

.setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)

328

329

// Simulate server that reads request but doesn't respond

330

val hangingResponse = MockResponse()

331

.setSocketPolicy(SocketPolicy.NO_RESPONSE)

332

333

// Simulate SSL handshake failure

334

val sslFailureResponse = MockResponse()

335

.setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE)

336

```

337

338

### Trailers and HTTP/2 Features

339

340

Advanced HTTP features including trailers and HTTP/2 specific functionality.

341

342

```kotlin { .api }

343

/**

344

* Set trailers for chunked responses

345

* @param trailers Headers to send as trailers

346

* @returns This MockResponse for method chaining

347

*/

348

fun setTrailers(trailers: Headers): MockResponse

349

350

/**

351

* Set HTTP/2 error code for stream resets

352

* @param http2ErrorCode HTTP/2 error code (default: -1 for no error)

353

* @returns This MockResponse for method chaining

354

*/

355

fun setHttp2ErrorCode(http2ErrorCode: Int): MockResponse

356

357

/**

358

* HTTP trailers for chunked responses

359

*/

360

var trailers: Headers

361

362

/**

363

* HTTP/2 error code for stream resets (default: -1)

364

*/

365

var http2ErrorCode: Int

366

```

367

368

**Usage Examples:**

369

370

```kotlin

371

// Chunked response with trailers

372

val trailersResponse = MockResponse()

373

.setResponseCode(200)

374

.addHeader("Transfer-Encoding", "chunked")

375

.setChunkedBody("Response data", 64)

376

.setTrailers(headersOf("X-Final-Status", "complete"))

377

378

// HTTP/2 stream reset

379

val resetResponse = MockResponse()

380

.setResponseCode(200)

381

.setHttp2ErrorCode(8) // CANCEL error code

382

```

383

384

### HTTP/2 and WebSocket Features

385

386

Advanced HTTP/2 and WebSocket specific functionality.

387

388

```kotlin { .api }

389

/**

390

* Add informational response (1xx status codes)

391

* @param informationalResponse MockResponse with 1xx status code

392

* @returns This MockResponse for method chaining

393

*/

394

fun addInformationalResponse(informationalResponse: MockResponse): MockResponse

395

396

/**

397

* Add HTTP/2 server push promise

398

* @param promise PushPromise containing push information

399

* @returns This MockResponse for method chaining

400

*/

401

fun withPush(promise: PushPromise): MockResponse

402

403

/**

404

* Configure HTTP/2 settings frame

405

* @param settings HTTP/2 settings to send

406

* @returns This MockResponse for method chaining

407

*/

408

fun withSettings(settings: Settings): MockResponse

409

410

/**

411

* Enable WebSocket upgrade for this response

412

* @param listener WebSocket listener for handling WebSocket events

413

* @returns This MockResponse for method chaining

414

*/

415

fun withWebSocketUpgrade(listener: WebSocketListener): MockResponse

416

```

417

418

**Usage Examples:**

419

420

```kotlin

421

import okhttp3.internal.http2.Settings

422

import okhttp3.WebSocketListener

423

424

// HTTP/2 server push

425

val pushPromise = PushPromise(

426

"GET",

427

"/api/user/1/avatar",

428

headersOf("accept", "image/*"),

429

MockResponse().setBody("avatar-data")

430

)

431

432

val responseWithPush = MockResponse()

433

.setResponseCode(200)

434

.setBody("Main response")

435

.withPush(pushPromise)

436

437

// HTTP/2 settings

438

val settings = Settings()

439

settings[Settings.MAX_CONCURRENT_STREAMS] = 100

440

val responseWithSettings = MockResponse()

441

.setResponseCode(200)

442

.withSettings(settings)

443

444

// WebSocket upgrade

445

val wsResponse = MockResponse()

446

.setResponseCode(101)

447

.withWebSocketUpgrade(object : WebSocketListener() {

448

override fun onOpen(webSocket: WebSocket, response: Response) {

449

webSocket.send("Hello WebSocket!")

450

}

451

})

452

```

453

454

### Duplex Streaming

455

456

Support for duplex (bidirectional) streaming responses.

457

458

```kotlin { .api }

459

/**

460

* Duplex response body for bidirectional streaming (read-only)

461

*/

462

val duplexResponseBody: DuplexResponseBody?

463

464

/**

465

* Whether this response supports duplex streaming (read-only)

466

*/

467

val isDuplex: Boolean

468

```

469

470

**Usage Examples:**

471

472

```kotlin

473

// Check if response supports duplex streaming

474

val response = MockResponse()

475

if (response.isDuplex) {

476

val duplexBody = response.duplexResponseBody

477

// Handle duplex streaming

478

}

479

```