or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# pytest-aiohttp

1

2

Pytest plugin for aiohttp support providing fixtures for test server and client creation. The plugin integrates with pytest-asyncio to enable comprehensive testing of aiohttp web applications and clients with automatic resource cleanup.

3

4

## Package Information

5

6

- **Package Name**: pytest-aiohttp

7

- **Package Type**: pytest plugin

8

- **Language**: Python

9

- **Installation**: `pip install pytest-aiohttp`

10

11

## Core Imports

12

13

```python

14

import pytest

15

import pytest_aiohttp

16

```

17

18

The plugin is automatically loaded by pytest through the entry point system when pytest-aiohttp is installed. Individual fixtures are available directly in test functions without explicit imports:

19

20

```python

21

async def test_example(aiohttp_client):

22

# fixture is available automatically

23

pass

24

```

25

26

For direct access to Protocol classes or version information:

27

28

```python

29

from pytest_aiohttp import AiohttpClient, AiohttpServer, AiohttpRawServer

30

import pytest_aiohttp

31

32

# Check version

33

print(pytest_aiohttp.__version__)

34

```

35

36

## Basic Usage

37

38

```python

39

import pytest

40

from aiohttp import web

41

42

43

async def hello(request):

44

return web.Response(body=b"Hello, world")

45

46

47

def create_app():

48

app = web.Application()

49

app.router.add_route("GET", "/", hello)

50

return app

51

52

53

async def test_hello(aiohttp_client):

54

client = await aiohttp_client(create_app())

55

resp = await client.get("/")

56

assert resp.status == 200

57

text = await resp.text()

58

assert "Hello, world" in text

59

```

60

61

## Configuration

62

63

Add `asyncio_mode = auto` to your pytest configuration file. The plugin also works with `asyncio_mode = strict`. The plugin automatically handles legacy mode migration with deprecation warnings.

64

65

```ini

66

# pytest.ini or setup.cfg

67

[tool:pytest]

68

asyncio_mode = auto

69

```

70

71

## Capabilities

72

73

### Test Client Factory

74

75

Creates test clients for aiohttp applications and servers with automatic resource cleanup.

76

77

```python { .api }

78

async def aiohttp_client(

79

app_or_server: Union[Application, BaseTestServer],

80

*,

81

server_kwargs: Optional[Dict[str, Any]] = None,

82

**kwargs: Any

83

) -> TestClient:

84

"""

85

Factory to create a TestClient instance.

86

87

Parameters:

88

- app_or_server: aiohttp Application or BaseTestServer instance

89

- server_kwargs: optional kwargs for server creation (when using Application)

90

- **kwargs: additional arguments passed to TestClient constructor

91

92

Returns:

93

TestClient instance with automatic cleanup

94

"""

95

```

96

97

Usage examples:

98

99

```python

100

# With Application

101

async def test_app(aiohttp_client):

102

app = web.Application()

103

client = await aiohttp_client(app)

104

# client is automatically cleaned up

105

106

# With server kwargs

107

async def test_custom_port(aiohttp_client, unused_tcp_port):

108

app = web.Application()

109

client = await aiohttp_client(app, server_kwargs={'port': unused_tcp_port})

110

assert client.port == unused_tcp_port

111

112

# With existing server

113

async def test_server(aiohttp_client, aiohttp_server):

114

app = web.Application()

115

server = await aiohttp_server(app)

116

client = await aiohttp_client(server)

117

```

118

119

### Test Server Factory

120

121

Creates test servers for aiohttp applications with configurable options.

122

123

```python { .api }

124

async def aiohttp_server(

125

app: Application,

126

*,

127

host: str = "127.0.0.1",

128

port: Optional[int] = None,

129

**kwargs: Any

130

) -> TestServer:

131

"""

132

Factory to create a TestServer instance, given an app.

133

134

Parameters:

135

- app: aiohttp Application instance

136

- host: server host address (default: "127.0.0.1")

137

- port: server port (optional, auto-assigned if None)

138

- **kwargs: additional arguments passed to start_server()

139

140

Returns:

141

TestServer instance with automatic cleanup

142

"""

143

```

144

145

Usage example:

146

147

```python

148

async def test_server(aiohttp_server):

149

app = web.Application()

150

app.router.add_get('/', lambda r: web.Response(text='OK'))

151

152

server = await aiohttp_server(app, port=8080)

153

assert server.port == 8080

154

# server is automatically cleaned up

155

```

156

157

### Raw Test Server Factory

158

159

Creates raw test servers for testing with custom request handlers.

160

161

```python { .api }

162

async def aiohttp_raw_server(

163

handler: _RequestHandler,

164

*,

165

port: Optional[int] = None,

166

**kwargs: Any

167

) -> RawTestServer:

168

"""

169

Factory to create a RawTestServer instance, given a web handler.

170

171

Parameters:

172

- handler: request handler function

173

- port: server port (optional, auto-assigned if None)

174

- **kwargs: additional arguments passed to start_server()

175

176

Returns:

177

RawTestServer instance with automatic cleanup

178

"""

179

```

180

181

Usage example:

182

183

```python

184

from aiohttp import web

185

186

async def handler(request):

187

return web.Response(text="OK")

188

189

async def test_raw_server(aiohttp_raw_server, aiohttp_client):

190

server = await aiohttp_raw_server(handler)

191

client = await aiohttp_client(server)

192

resp = await client.get('/')

193

assert resp.status == 200

194

```

195

196

### Custom Client Class Configuration

197

198

Allows customization of the TestClient class used by aiohttp_client.

199

200

```python { .api }

201

def aiohttp_client_cls() -> Type[TestClient]:

202

"""

203

Client class to use in aiohttp_client factory.

204

205

Returns:

206

TestClient class or subclass

207

208

Default: TestClient

209

"""

210

```

211

212

Usage example:

213

214

```python

215

from aiohttp.test_utils import TestClient

216

217

class MyClient(TestClient):

218

async def login(self, *, user, pw):

219

payload = {"username": user, "password": pw}

220

return await self.post("/login", json=payload)

221

222

@pytest.fixture

223

def aiohttp_client_cls():

224

return MyClient

225

226

async def test_login(aiohttp_client):

227

app = web.Application()

228

client = await aiohttp_client(app)

229

await client.login(user="admin", pw="s3cr3t")

230

```

231

232

## Types

233

234

The following Protocol classes are directly importable from the pytest_aiohttp module:

235

236

```python { .api }

237

from typing import Protocol, Union, Dict, Any, Optional, Awaitable, Type

238

from aiohttp.web import Application, BaseRequest

239

from aiohttp.test_utils import TestClient, TestServer, RawTestServer, BaseTestServer

240

from aiohttp.web_protocol import _RequestHandler

241

242

class AiohttpClient(Protocol):

243

"""Protocol for aiohttp_client fixture."""

244

async def __call__(

245

self,

246

app_or_server: Union[Application, BaseTestServer],

247

*,

248

server_kwargs: Optional[Dict[str, Any]] = None,

249

**kwargs: Any

250

) -> TestClient: ...

251

252

class AiohttpServer(Protocol):

253

"""Protocol for aiohttp_server fixture."""

254

def __call__(

255

self, app: Application, *, port: Optional[int] = None, **kwargs: Any

256

) -> Awaitable[TestServer]: ...

257

258

class AiohttpRawServer(Protocol):

259

"""Protocol for aiohttp_raw_server fixture."""

260

def __call__(

261

self,

262

handler: _RequestHandler,

263

*,

264

port: Optional[int] = None,

265

**kwargs: Any

266

) -> Awaitable[RawTestServer]: ...

267

```

268

269

These Protocol classes can be imported directly for type annotations:

270

271

```python

272

from pytest_aiohttp import AiohttpClient, AiohttpServer, AiohttpRawServer

273

274

def my_test_helper(client_factory: AiohttpClient) -> None:

275

# Use the client factory with proper typing

276

pass

277

```

278

279

## Error Handling

280

281

The plugin automatically handles cleanup of resources (clients and servers) when tests complete or fail. If server creation fails, appropriate exceptions are propagated:

282

283

- `RuntimeError`: Raised when application factory fails

284

- Standard aiohttp server exceptions for port binding and network issues

285

286

## Package Attributes

287

288

```python { .api }

289

__version__: str

290

"""Package version string."""

291

```

292

293

Usage example:

294

295

```python

296

import pytest_aiohttp

297

print(f"pytest-aiohttp version: {pytest_aiohttp.__version__}")

298

```

299

300

## Dependencies

301

302

- pytest >= 6.1.0

303

- aiohttp >= 3.11.0b0

304

- pytest-asyncio >= 0.17.2