-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
499 lines (436 loc) · 13.2 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
<!doctype html>
<html lang="ru" >
<head>
<title>Advanced py.test usage</title>
<meta name="description" content="">
<meta name="author" content="Andrew Svetlov">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/custom.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>py.test</h1>
<h3>продвинутое использование</h3>
<p>
Андрей Светлов
<p>
<small>http://asvetlov.blogspot.com</small><br>
<small>[email protected]</small>
</p>
</p>
</section>
<section>
<blockquote cite="http://bugs.python.org/issue17908">
“Eveybody is
using py.test anyway...”
</blockquote>
<p>Guido van Rossum</p>
</section>
<section>
<section data-background="Jupiter_bayan_accordion.jpg" data-background-size="60%">
</section>
<section data-markdown>
<script type="text/template">
## Примитивы
```python
import pytest
def test_a():
assert 1 == 2
class TestB:
def test_b(self):
assert 'a'.upper() == 'A'
def test_c(self):
with pytest.raises(ZeroDivisionError):
1/0
```
</script>
</section>
<section>
<h2>Запуск</h2>
<pre><code>$ py.test -k "(a or B) and not c"</code></pre>
</section>
</section>
<section>
<section data-background="fixture.jpg" data-background-size="60%">
</section>
<section data-markdown>
<script type="text/template">
## Fixture
```python
import socket
@pytest.fixture()
def unique_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', 0))
return s.getsockname()[1]
```
```python
def test_port(unique_port):
print(unique_port)
```
<!-- .element: class="fragment" -->
</script>
</section>
</section>
<section data-markdown>
<script type="text/template">
## Освобождение ресурсов
```python
import asyncio
@pytest.yield_fixture
def loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
yield loop
if not loop.is_closed():
loop.call_soon(loop.stop)
loop.run_forever()
loop.close()
```
```python
def test_loop(loop):
fut = asyncio.Future(loop=loop)
loop.call_soon(fut.set_result, 1)
ret = loop.run_until_complete(fut)
assert ret == 1
```
<!-- .element: class="fragment" -->
</script>
</section>
<section>
<section data-markdown>
<script type="text/template">
## Fixture factory
```
@pytest.fixture()
def unused_port():
def factory():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', 0))
return s.getsockname()[1]
return factory
```
```python
def test_unused_port(unused_port):
print(unused_port()) # NB: скобки!
print(unused_port()) # другое значение
```
<!-- .element: class="fragment" -->
</script>
</section>
<section data-markdown>
<script type="text/template">
## Фабрика с параметрами
```python
@pytest.yield_fixture
def create_server(loop, unused_port):
srv = None
async def create(*, ssl_ctx=None):
nonlocal srv
port = unused_port()
srv = await make_server(loop, port, ssl_ctx)
proto = 'https' is ssl_ctx else 'http'
url = "{}://127.0.0.1:{}".format(proto, port)
return app, url
yield create
async def finish():
srv.close()
await srv.wait_closed()
loop.run_until_complete(finish())
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Использование фабрики с параметрами
```python
def test_create_server(create_server, loop):
app, url = loop.run_until_complete(
create_server(ssl_ctx=None))
```
Фууу!!! <!-- .element: class="fragment" -->
</script>
</section>
<section data-markdown>
<script type="text/template">
## Выглядит как гуано
Хочу `await`!!!
```python
def test_create_server(create_server):
app, url = await create_server(ssl_ctx=None)
```
</script>
</section>
</section>
<section data-markdown>
<script type="text/template">
## conftest.py
```python
pytest_plugins = ['asyncio_fixtures', 'controller_fixtures',
'log_fixtures', 'redis_fixtures', 'statsd_fixtures']
```
###И никаких `import` инструкций.
</script>
</section>
<section>
<section>
<h2>Плагины</h2>
<h3>или</h3>
<h2>Сеанс ч<span style="text-decoration: underline;">о</span>рной магии</h2>
</section>
<section data-background="vudu.jpg" data-background-size="60%">
</section>
<section data-markdown>
<script type="text/template">
## Добавляем пометку
```python
@pytest.mark.run_loop
def test_create_server(create_server):
app, url = await create_server(ssl_ctx=None)
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Перегружаем создание теста
```python
@pytest.mark.tryfirst
def pytest_pycollect_makeitem(collector, name, obj):
if collector.funcnamefilter(name):
item = pytest.Function(name, parent=collector)
if 'run_loop' in item.keywords:
return list(collector._genfunctions(name, obj))
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Перегружаем запуск теста
```python
@pytest.mark.tryfirst
def pytest_pyfunc_call(pyfuncitem):
if 'run_loop' in pyfuncitem.keywords:
funcargs = pyfuncitem.funcargs
loop = funcargs['loop']
testargs = {arg: funcargs[arg]
for arg in pyfuncitem._fixtureinfo.argnames}
loop.run_until_complete(pyfuncitem.obj(**testargs))
return True
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Добавляем к тесту loop fixture если ещё нету
```python
def pytest_runtest_setup(item):
if 'run_loop' in item.keywords:
if 'loop' not in item.fixturenames:
item.fixturenames.append('loop')
```
</script>
</section>
<section data-markdown>
<script type="text/template">
##Profit!!! 😁
```python
@pytest.mark.run_loop
def test_create_server():
await asyncio.sleep(0.1)
```
</script>
</section>
</section>
<section>
<section>
<h2>Рулим из командной строки</h2>
</section>
<section data-background="commandline.jpg" data-background-size="60%">
</section>
<section data-markdown>
<script type="text/template">
## Добавляем новый параметр
```python
def pytest_addoption(parser):
parser.addoption('--gc-collect', action='store_true',
default=False,
help="Perform GC collection after every test")
```
</script>
</section>
<section data-markdown>
<script type="text/template">
## Подкручиваем завершение теста
```python
@pytest.mark.trylast
def pytest_runtest_teardown(item, nextitem):
if item.config.getoption('--gc-collect'):
gc.collect()
return nextitem
```
</script>
</section>
<section>
<h2>Profit!!! 😇</h2>
<pre><code>$ py.test --gc-collect</code></pre>
</section>
<section data-markdown>
<script type="text/template">
## Пропуск долгих тестов
```python
def pytest_addoption(parser):
parser.addoption('--run-slow', action='store_true',
default=False,
help="Run slow tests")
def pytest_runtest_setup(item):
if ('slowtest' in item.keywords and
(not item.config.getoption('--run-slow'))):
pytest.skip('Need --run-slow to run')
```
```python
@pytest.mark.slowtest
def test_xxx():
...
```
<!-- .element: class="fragment" -->
```
py.test --run-slow
```
<!-- .element: class="fragment" -->
</script>
</section>
</section>
<section>
<section>
<h2>Docker и тесты</h2>
</section>
<section data-background="docker.jpg" data-background-size="60%">
</section>
<section>
<h2>Fixture scope</h2>
<ul>
<li>function</li>
<li>class</li>
<li>module</li>
<li>session</li>
</ul>
</section>
<section data-markdown>>
<script type="text/template">
## Уникальный ID и docker client
```python
import docker as libdocker
import uuid
@pytest.fixture(scope='session')
def session_id():
return str(uuid.uuid4())
@pytest.fixture(scope='session')
def docker():
return libdocker.Client(version='auto')
```
</script>
</section>
<section data-markdown>>
<script type="text/template">
## Запуск контейнера
```python
@pytest.yield_fixture(scope='session')
def redis_server(unused_port, session_id, docker):
docker.pull('redis')
port = unused_port()
container = docker.create_container(
image='redis',
name='test-redis-{}'.format(session_id),
ports=[6379],
detach=True,
host_config=docker.create_host_config(
port_bindings={6379: port}))
docker.start(container=container['Id'])
yield port
docker.kill(container=container['Id'])
docker.remove_container(container['Id'])
```
</script>
</section>
<section data-markdown>>
<script type="text/template">
## Создание клиента
```python
@pytest.fixture
def redis_client(redis_server):
for i in range(100):
try:
client = redis.StrictRedis(host='127.0.0.1',
port=port, db=0)
client.get('some_key')
return client
except redis.ConnectionError:
time.sleep(0.01)
```
</script>
</section>
<section data-markdown>>
<script type="text/template">
## Тест
```python
def test_redis(redis_client):
redis_client.set(b'key', b'value')
assert redis_client.get(b'key') == b'value'
```
</script>
</section>
<section>
<h1>Вопросы?</h1>
<p>
Андрей Светлов
<p>
<small>http://asvetlov.blogspot.com</small><br>
<small>[email protected]</small>
</p>
</p>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
slideNumber: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true },
{ src: 'plugin/notes/notes.js', async: true }
]
});
</script>
</body>
</html>