or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

contrib.mddebugging.mdevents.mdexceptions.mdindex.mdload-shapes.mdtasksets.mduser-classes.mdwait-time.md

user-classes.mddocs/

0

# User Classes

1

2

User classes define the behavior patterns for virtual users in load tests. Locust provides three main user classes: the base User class, HttpUser for HTTP testing, and FastHttpUser for high-performance HTTP testing.

3

4

## Capabilities

5

6

### Base User Class

7

8

The abstract base class that all user classes inherit from. Defines the core user lifecycle and task execution framework.

9

10

```python { .api }

11

class User:

12

"""

13

Base class for all user classes.

14

15

Attributes:

16

host (str): Target host for requests

17

weight (int): Relative weight for user selection in load tests

18

fixed_count (int): Fixed number of users (overrides weight-based selection)

19

tasks (list | dict): Tasks to execute - list of functions or dict with weights

20

wait_time (callable): Function returning wait time between tasks

21

abstract (bool): Mark class as abstract (won't be executed)

22

"""

23

24

def __init__(self, environment):

25

"""

26

Initialize user with environment.

27

28

Args:

29

environment: Locust environment instance

30

"""

31

32

def on_start(self):

33

"""Called when user starts executing."""

34

35

def on_stop(self):

36

"""Called when user stops executing."""

37

38

def run(self):

39

"""Main execution loop - runs tasks with wait times."""

40

41

def wait(self):

42

"""Wait between tasks using wait_time function."""

43

44

def start(self, group):

45

"""Start user execution in a greenlet group."""

46

47

def stop(self, force=False):

48

"""

49

Stop user execution.

50

51

Args:

52

force (bool): Force immediate stop without cleanup

53

"""

54

55

def context(self, **kwargs):

56

"""

57

Context manager for temporary user configuration.

58

59

Returns:

60

Context manager for user settings

61

"""

62

63

@property

64

def group(self):

65

"""Group this user belongs to."""

66

67

@property

68

def greenlet(self):

69

"""Greenlet instance running this user."""

70

```

71

72

### HttpUser Class

73

74

HTTP-specific user class that provides an HTTP client for making web requests. Built on the requests library with Locust-specific enhancements.

75

76

```python { .api }

77

class HttpUser(User):

78

"""

79

User class for HTTP load testing using requests library.

80

81

Attributes:

82

client (HttpSession): HTTP session for making requests

83

pool_manager: Connection pool manager

84

"""

85

86

# Inherits all User methods and attributes

87

# client is automatically created as HttpSession instance

88

```

89

90

#### HttpSession

91

92

The HTTP client used by HttpUser, extending requests.Session with load testing features.

93

94

```python { .api }

95

class HttpSession:

96

"""

97

Extended requests.Session with Locust event integration.

98

99

Attributes:

100

base_url (str): Base URL for all requests

101

request_event: Event hook for request statistics

102

user: Associated user instance

103

request_name (str): Current request name for statistics

104

"""

105

106

def __init__(self, base_url, request_event, user, *args, pool_manager=None, **kwargs):

107

"""

108

Initialize HTTP session.

109

110

Args:

111

base_url (str): Base URL for requests

112

request_event: Event hook for statistics

113

user: User instance

114

pool_manager: Optional connection pool manager

115

"""

116

117

def get(self, url, **kwargs):

118

"""

119

Send GET request.

120

121

Args:

122

url (str): Request URL

123

**kwargs: Additional requests parameters

124

125

Returns:

126

LocustResponse: Enhanced response object

127

"""

128

129

def post(self, url, data=None, json=None, **kwargs):

130

"""

131

Send POST request.

132

133

Args:

134

url (str): Request URL

135

data: Request body data

136

json: JSON data to send

137

**kwargs: Additional requests parameters

138

139

Returns:

140

LocustResponse: Enhanced response object

141

"""

142

143

def put(self, url, data=None, **kwargs):

144

"""Send PUT request."""

145

146

def patch(self, url, data=None, **kwargs):

147

"""Send PATCH request."""

148

149

def delete(self, url, **kwargs):

150

"""Send DELETE request."""

151

152

def head(self, url, **kwargs):

153

"""Send HEAD request."""

154

155

def options(self, url, **kwargs):

156

"""Send OPTIONS request."""

157

158

def request(self, method, url, **kwargs):

159

"""

160

Send HTTP request with specified method.

161

162

Args:

163

method (str): HTTP method

164

url (str): Request URL

165

**kwargs: Additional requests parameters

166

167

Returns:

168

LocustResponse: Enhanced response object

169

"""

170

171

def rename_request(self, name):

172

"""

173

Context manager to rename request for statistics.

174

175

Args:

176

name (str): Name to use in statistics

177

178

Returns:

179

Context manager

180

"""

181

```

182

183

### FastHttpUser Class

184

185

High-performance HTTP user class using geventhttpclient instead of requests for better performance with high concurrency.

186

187

```python { .api }

188

class FastHttpUser(User):

189

"""

190

High-performance HTTP user using geventhttpclient.

191

192

Configuration Attributes:

193

network_timeout (float): Network timeout in seconds

194

connection_timeout (float): Connection timeout in seconds

195

max_redirects (int): Maximum redirects to follow

196

max_retries (int): Maximum retry attempts

197

insecure (bool): Skip SSL certificate verification

198

default_headers (dict): Default headers for all requests

199

concurrency (int): Connection concurrency level

200

proxy_host (str): Proxy hostname

201

proxy_port (int): Proxy port

202

client_pool: Connection pool configuration

203

ssl_context_factory: Custom SSL context factory

204

205

Attributes:

206

client (FastHttpSession): Fast HTTP session for requests

207

"""

208

209

# Inherits all User methods and attributes

210

# client is automatically created as FastHttpSession instance

211

212

def rest(self, method, url, **kwargs):

213

"""

214

Make REST API request with automatic JSON handling.

215

216

Args:

217

method (str): HTTP method

218

url (str): Request URL

219

**kwargs: Request parameters

220

221

Returns:

222

Parsed JSON response

223

"""

224

225

def rest_(self, method, url, **kwargs):

226

"""

227

Make REST API request returning response context manager.

228

229

Args:

230

method (str): HTTP method

231

url (str): Request URL

232

**kwargs: Request parameters

233

234

Returns:

235

RestResponseContextManager: Context for response validation

236

"""

237

```

238

239

## Usage Examples

240

241

### Basic HttpUser Example

242

243

```python

244

from locust import HttpUser, task, between

245

246

class WebsiteUser(HttpUser):

247

wait_time = between(1, 3)

248

249

def on_start(self):

250

# Login when user starts

251

response = self.client.post("/login", json={

252

"username": "testuser",

253

"password": "secret"

254

})

255

# Store auth token if needed

256

self.auth_token = response.json()["token"]

257

258

@task(3)

259

def browse_products(self):

260

# Get product list

261

self.client.get("/products")

262

263

# View random product

264

product_id = random.randint(1, 100)

265

self.client.get(f"/products/{product_id}")

266

267

@task(1)

268

def add_to_cart(self):

269

self.client.post("/cart", json={

270

"product_id": random.randint(1, 100),

271

"quantity": random.randint(1, 5)

272

})

273

274

def on_stop(self):

275

# Cleanup when user stops

276

self.client.post("/logout")

277

```

278

279

### FastHttpUser Example

280

281

```python

282

from locust.contrib.fasthttp import FastHttpUser

283

from locust import task, between

284

285

class HighPerformanceUser(FastHttpUser):

286

wait_time = between(0.1, 0.5) # Very fast requests

287

288

# Configure for high performance

289

connection_timeout = 60.0

290

network_timeout = 60.0

291

concurrency = 10

292

293

@task

294

def api_endpoint(self):

295

# Use REST helper for JSON APIs

296

data = self.rest("GET", "/api/data")

297

298

# Traditional request

299

response = self.client.get("/api/status")

300

301

# Validate with context manager

302

with self.rest_("POST", "/api/process", json={"data": data}) as response:

303

if response.js["status"] != "success":

304

response.failure("Processing failed")

305

```

306

307

### Custom User Base Class

308

309

```python

310

from locust import User, task, events

311

import time

312

313

class CustomProtocolUser(User):

314

"""User for testing custom protocols."""

315

316

abstract = True # Don't run this class directly

317

318

def __init__(self, environment):

319

super().__init__(environment)

320

# Initialize custom client

321

self.client = CustomClient(host=self.host)

322

323

def on_start(self):

324

# Connect to custom service

325

start_time = time.time()

326

try:

327

self.client.connect()

328

# Fire request event for statistics

329

events.request.fire(

330

request_type="CONNECT",

331

name="connect",

332

response_time=(time.time() - start_time) * 1000,

333

response_length=0

334

)

335

except Exception as e:

336

events.request.fire(

337

request_type="CONNECT",

338

name="connect",

339

response_time=(time.time() - start_time) * 1000,

340

response_length=0,

341

exception=e

342

)

343

344

def on_stop(self):

345

self.client.disconnect()

346

347

class MyCustomUser(CustomProtocolUser):

348

wait_time = between(1, 2)

349

350

@task

351

def custom_operation(self):

352

start_time = time.time()

353

try:

354

result = self.client.send_command("GET_DATA")

355

events.request.fire(

356

request_type="CUSTOM",

357

name="get_data",

358

response_time=(time.time() - start_time) * 1000,

359

response_length=len(result)

360

)

361

except Exception as e:

362

events.request.fire(

363

request_type="CUSTOM",

364

name="get_data",

365

response_time=(time.time() - start_time) * 1000,

366

response_length=0,

367

exception=e

368

)

369

```

370

371

## Types

372

373

```python { .api }

374

from typing import Optional, Dict, Any, Callable

375

from requests import Response

376

import gevent

377

378

# HTTP Session types

379

HttpMethod = str # "GET", "POST", "PUT", etc.

380

RequestData = Optional[Dict[str, Any]]

381

RequestHeaders = Optional[Dict[str, str]]

382

383

# Response types

384

class LocustResponse(Response):

385

"""Extended requests.Response with Locust features."""

386

387

class FastResponse:

388

"""Fast HTTP response from geventhttpclient."""

389

390

status_code: int

391

headers: Dict[str, str]

392

content: bytes

393

text: str

394

395

def json(self) -> Any:

396

"""Parse response as JSON."""

397

398

# Context managers

399

class ResponseContextManager:

400

"""Context manager for response validation."""

401

402

def __enter__(self) -> LocustResponse: ...

403

def __exit__(self, exc_type, exc_val, exc_tb): ...

404

405

class RestResponseContextManager:

406

"""REST-specific response context manager."""

407

408

def __enter__(self) -> FastResponse: ...

409

def __exit__(self, exc_type, exc_val, exc_tb): ...

410

```