or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-testing.mddatabase-testing.mddjango-assertions.mddjango-utilities.mdemail-testing.mdindex.mdlive-server-testing.mdpytest-marks.mdquery-testing.mdsettings-management.mdtransaction-callbacks.mduser-management.md

django-assertions.mddocs/

0

# Django Assertions

1

2

All Django TestCase assertion methods for comprehensive testing capabilities. These assertions provide Django-specific testing functionality including HTTP response testing, form validation, template usage, and HTML/JSON comparison.

3

4

## Capabilities

5

6

### HTTP Response Assertions

7

8

Test HTTP responses, redirects, and response content.

9

10

```python { .api }

11

def assertRedirects(

12

response: HttpResponseBase,

13

expected_url: str,

14

status_code: int = 302,

15

target_status_code: int = 200,

16

msg_prefix: str = "",

17

fetch_redirect_response: bool = True

18

) -> None:

19

"""

20

Assert that response is a redirect to expected URL.

21

22

Args:

23

response: HTTP response object

24

expected_url: Expected redirect target URL

25

status_code: Expected redirect status code (default: 302)

26

target_status_code: Expected final response status (default: 200)

27

msg_prefix: Optional message prefix for assertion errors

28

fetch_redirect_response: Whether to fetch and check final response

29

"""

30

31

def assertContains(

32

response: HttpResponseBase,

33

text: object,

34

count: Optional[int] = None,

35

status_code: int = 200,

36

msg_prefix: str = "",

37

html: bool = False

38

) -> None:

39

"""

40

Assert that response contains specified text.

41

42

Args:

43

response: HTTP response object

44

text: Text that should be present in response

45

count: Expected number of occurrences (None for any)

46

status_code: Expected response status code (default: 200)

47

msg_prefix: Optional message prefix for assertion errors

48

html: Whether to compare as HTML (ignores whitespace differences)

49

"""

50

51

def assertNotContains(

52

response: HttpResponseBase,

53

text: object,

54

status_code: int = 200,

55

msg_prefix: str = "",

56

html: bool = False

57

) -> None:

58

"""

59

Assert that response does not contain specified text.

60

61

Args:

62

response: HTTP response object

63

text: Text that should not be present in response

64

status_code: Expected response status code (default: 200)

65

msg_prefix: Optional message prefix for assertion errors

66

html: Whether to compare as HTML (ignores whitespace differences)

67

"""

68

69

def assertURLEqual(url1: str, url2: str, msg_prefix: str = "") -> None:

70

"""

71

Assert that two URLs are equal, ignoring order of query parameters.

72

73

Args:

74

url1: First URL to compare

75

url2: Second URL to compare

76

msg_prefix: Optional message prefix for assertion errors

77

"""

78

```

79

80

### Template Assertions

81

82

Test template usage and rendering.

83

84

```python { .api }

85

def assertTemplateUsed(

86

response: Optional[HttpResponseBase] = None,

87

template_name: Optional[str] = None,

88

msg_prefix: str = "",

89

count: Optional[int] = None

90

):

91

"""

92

Assert that specified template was used in rendering response.

93

94

Args:

95

response: HTTP response object (or None for last response)

96

template_name: Expected template name

97

msg_prefix: Optional message prefix for assertion errors

98

count: Expected number of times template was used

99

"""

100

101

def assertTemplateNotUsed(

102

response: Optional[HttpResponseBase] = None,

103

template_name: Optional[str] = None,

104

msg_prefix: str = ""

105

):

106

"""

107

Assert that specified template was not used in rendering response.

108

109

Args:

110

response: HTTP response object (or None for last response)

111

template_name: Template name that should not have been used

112

msg_prefix: Optional message prefix for assertion errors

113

"""

114

```

115

116

### Form Assertions

117

118

Test form validation and errors.

119

120

```python { .api }

121

def assertFormError(

122

form: forms.BaseForm,

123

field: Optional[str],

124

errors: Union[str, Sequence[str]],

125

msg_prefix: str = ""

126

) -> None:

127

"""

128

Assert that form has specific validation errors.

129

130

Args:

131

form: Django form instance

132

field: Field name with error (None for non-field errors)

133

errors: Expected error message(s)

134

msg_prefix: Optional message prefix for assertion errors

135

"""

136

137

def assertFormSetError(

138

formset: forms.BaseFormSet,

139

form_index: Optional[int],

140

field: Optional[str],

141

errors: Union[str, Sequence[str]],

142

msg_prefix: str = ""

143

) -> None:

144

"""

145

Assert that formset has specific validation errors.

146

147

Args:

148

formset: Django formset instance

149

form_index: Index of form with error (None for formset errors)

150

field: Field name with error (None for non-field errors)

151

errors: Expected error message(s)

152

msg_prefix: Optional message prefix for assertion errors

153

"""

154

```

155

156

### HTML/XML Assertions

157

158

Test HTML and XML content with intelligent comparison.

159

160

```python { .api }

161

def assertHTMLEqual(html1: str, html2: str, msg: Optional[str] = None) -> None:

162

"""

163

Assert that HTML strings are equivalent, ignoring whitespace.

164

165

Args:

166

html1: First HTML string

167

html2: Second HTML string

168

msg: Optional custom assertion message

169

"""

170

171

def assertHTMLNotEqual(html1: str, html2: str, msg: Optional[str] = None) -> None:

172

"""

173

Assert that HTML strings are not equivalent.

174

175

Args:

176

html1: First HTML string

177

html2: Second HTML string

178

msg: Optional custom assertion message

179

"""

180

181

def assertInHTML(

182

needle: str,

183

haystack: str,

184

count: Optional[int] = None,

185

msg_prefix: str = ""

186

) -> None:

187

"""

188

Assert that HTML fragment is present in HTML document.

189

190

Args:

191

needle: HTML fragment to search for

192

haystack: HTML document to search in

193

count: Expected number of occurrences (None for any)

194

msg_prefix: Optional message prefix for assertion errors

195

"""

196

197

def assertXMLEqual(xml1: str, xml2: str, msg: Optional[str] = None) -> None:

198

"""

199

Assert that XML strings are equivalent.

200

201

Args:

202

xml1: First XML string

203

xml2: Second XML string

204

msg: Optional custom assertion message

205

"""

206

207

def assertXMLNotEqual(xml1: str, xml2: str, msg: Optional[str] = None) -> None:

208

"""

209

Assert that XML strings are not equivalent.

210

211

Args:

212

xml1: First XML string

213

xml2: Second XML string

214

msg: Optional custom assertion message

215

"""

216

```

217

218

### JSON Assertions

219

220

Test JSON content and structure.

221

222

```python { .api }

223

def assertJSONEqual(raw: str, expected_data: Any, msg: Optional[str] = None) -> None:

224

"""

225

Assert that JSON string matches expected data structure.

226

227

Args:

228

raw: JSON string to parse and compare

229

expected_data: Expected Python data structure

230

msg: Optional custom assertion message

231

"""

232

233

def assertJSONNotEqual(raw: str, expected_data: Any, msg: Optional[str] = None) -> None:

234

"""

235

Assert that JSON string does not match expected data structure.

236

237

Args:

238

raw: JSON string to parse and compare

239

expected_data: Python data structure that should not match

240

msg: Optional custom assertion message

241

"""

242

```

243

244

### Database Assertions

245

246

Test database queries and QuerySet behavior.

247

248

```python { .api }

249

def assertQuerySetEqual(

250

qs,

251

values,

252

transform=repr,

253

ordered: bool = True,

254

msg: Optional[str] = None

255

) -> None:

256

"""

257

Assert that QuerySet matches expected values.

258

259

Args:

260

qs: QuerySet to test

261

values: Expected values (list)

262

transform: Function to transform QuerySet items for comparison

263

ordered: Whether order matters in comparison

264

msg: Optional custom assertion message

265

"""

266

267

def assertNumQueries(

268

num: int,

269

func=None,

270

*args,

271

using: str = "default",

272

**kwargs

273

):

274

"""

275

Assert that function executes exact number of database queries.

276

277

Args:

278

num: Expected number of queries

279

func: Function to execute (None for context manager usage)

280

args: Positional arguments for function

281

using: Database alias to monitor

282

kwargs: Keyword arguments for function

283

284

Returns:

285

Context manager if func is None, otherwise function result

286

"""

287

```

288

289

### Exception and Warning Assertions

290

291

Test exception and warning behavior.

292

293

```python { .api }

294

def assertRaisesMessage(

295

expected_exception: type[Exception],

296

expected_message: str,

297

*args,

298

**kwargs

299

):

300

"""

301

Assert that exception is raised with specific message.

302

303

Args:

304

expected_exception: Expected exception class

305

expected_message: Expected exception message

306

args: Positional arguments for callable

307

kwargs: Keyword arguments for callable

308

309

Returns:

310

Context manager for use with 'with' statement

311

"""

312

313

def assertWarnsMessage(

314

expected_warning: Warning,

315

expected_message: str,

316

*args,

317

**kwargs

318

):

319

"""

320

Assert that warning is issued with specific message.

321

322

Args:

323

expected_warning: Expected warning class

324

expected_message: Expected warning message

325

args: Positional arguments for callable

326

kwargs: Keyword arguments for callable

327

328

Returns:

329

Context manager for use with 'with' statement

330

"""

331

```

332

333

### Field Testing Assertions

334

335

Test form field validation behavior.

336

337

```python { .api }

338

def assertFieldOutput(

339

fieldclass,

340

valid,

341

invalid,

342

field_args=None,

343

field_kwargs=None,

344

empty_value: str = ""

345

) -> None:

346

"""

347

Assert that form field behaves correctly with valid and invalid inputs.

348

349

Args:

350

fieldclass: Form field class to test

351

valid: Dict of {input: expected_output} for valid inputs

352

invalid: List of inputs that should be invalid

353

field_args: Positional arguments for field constructor

354

field_kwargs: Keyword arguments for field constructor

355

empty_value: Expected output for empty input

356

"""

357

```

358

359

### Message Framework Assertions (Django 5.0+)

360

361

Test Django's message framework.

362

363

```python { .api }

364

def assertMessages(

365

response: HttpResponseBase,

366

expected_messages: Sequence[Message],

367

*args,

368

ordered: bool = True

369

) -> None:

370

"""

371

Assert that response contains expected messages.

372

373

Available in Django 5.0+. Tests messages added via Django's

374

message framework.

375

376

Args:

377

response: HTTP response object

378

expected_messages: Expected message objects

379

args: Additional arguments

380

ordered: Whether message order matters

381

"""

382

```

383

384

## Assertion Types

385

386

```python { .api }

387

from django.http import HttpResponseBase, HttpResponse

388

from django.forms import BaseForm, BaseFormSet

389

from django.contrib.messages import Message

390

from typing import Any, Optional, Union, Sequence, Callable, ContextManager

391

392

# Response types

393

HttpResponseType = HttpResponseBase

394

JsonData = Any # JSON-serializable data

395

396

# Form types

397

FormType = BaseForm

398

FormSetType = BaseFormSet

399

ValidationErrors = Union[str, Sequence[str]]

400

401

# HTML/XML content types

402

HtmlContent = str

403

XmlContent = str

404

JsonContent = str

405

406

# QuerySet comparison types

407

QuerySetValues = Sequence[Any]

408

TransformFunction = Callable[[Any], Any]

409

410

# Exception/Warning types

411

ExceptionClass = type[Exception]

412

WarningClass = type[Warning]

413

ExceptionMessage = str

414

WarningMessage = str

415

416

# Field testing types

417

FieldClass = type[BaseForm]

418

ValidInputs = dict[Any, Any]

419

InvalidInputs = Sequence[Any]

420

FieldArgs = Sequence[Any]

421

FieldKwargs = dict[str, Any]

422

```