Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Je teste mon code avec py.test
Search
Ronan Amicel
October 25, 2014
Programming
1
340
Je teste mon code avec py.test
Présentation à la conférence PyCon FR à Lyon le 25 octobre 2014.
Ronan Amicel
October 25, 2014
Tweet
Share
More Decks by Ronan Amicel
See All by Ronan Amicel
Développeur : ce qu’on ne m’a pas appris à l’école
ronnix
1
370
Refactoring: la méthode Mikado
ronnix
0
280
Techniques de test avancées en Python
ronnix
0
340
Product Development in a Startup
ronnix
2
280
Performance des frameworks web : Python vs The World (v1.1)
ronnix
1
8.2k
Performance des frameworks web : Python vs The World
ronnix
0
450
Introduction au Customer Development
ronnix
1
150
Rendez votre code Python plus beau !
ronnix
1
580
Trompez-vous, et vite !
ronnix
2
310
Other Decks in Programming
See All in Programming
AIに任せる範囲を安全に広げるためにやっていること
fukucheee
0
110
PostgreSQL を使った快適な go test 環境を求めて
otakakot
0
400
AI主導でFastAPIのWebサービスを作るときに 人間が構造化すべき境界線
okajun35
0
540
Takumiから考えるSecurity_Maturity_Model.pdf
gessy0129
1
120
受け入れテスト駆動開発(ATDD)×AI駆動開発 AI時代のATDDの取り組み方を考える
kztakasaki
2
520
社内規程RAGの精度を73.3% → 100%に改善した話
oharu121
13
7.5k
API Platformを活用したPHPによる本格的なWeb API開発 / api-platform-book-intro
ttskch
1
120
Agent Skills Workshop - AIへの頼み方を仕組み化する
gotalab555
14
7.9k
nuget-server - あなたが必要だったNuGetサーバー
kekyo
PRO
0
170
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
390
JPUG勉強会 OSSデータベースの内部構造を理解しよう
oga5
2
230
クライアントワークでSREをするということ。あるいは事業会社におけるSREと同じこと・違うこと
nnaka2992
1
310
Featured
See All Featured
First, design no harm
axbom
PRO
2
1.1k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
80
Facilitating Awesome Meetings
lara
57
6.8k
VelocityConf: Rendering Performance Case Studies
addyosmani
333
24k
Building AI with AI
inesmontani
PRO
1
760
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
310
Navigating the moral maze — ethical principles for Al-driven product design
skipperchong
2
280
The Cult of Friendly URLs
andyhume
79
6.8k
A Soul's Torment
seathinner
5
2.4k
Paper Plane
katiecoart
PRO
0
47k
jQuery: Nuts, Bolts and Bling
dougneiner
65
8.4k
How GitHub (no longer) Works
holman
316
140k
Transcript
Je teste mon code avec py.test Ronan Amicel @amicel PyCon
FR — 25 octobre 2014 — Lyon
Ronan Amicel Fondateur @ Pocket Sensei Hacker en résidence @
The Family
Préambule
None
C’est quoi py.test ?
$ py.test • Un outil en ligne de commande pour
lancer vos tests : • découverte • exécution • affichage des résultats
import pytest • Un framework pour écrire vos tests •
avec très peu de bla bla • avec un mécanisme de fixtures très flexible
Le plan • Écrire ses tests avec py.test • Moins
de bla bla • Utiliser les fixtures • Lancer ses tests avec py.test • Comment passer facilement à py.test
Écrire ses tests avec py.test
Moins de bla bla
Rappel : unittest import unittest def fact(n): return 1 if
n <= 1 else n * fact(n - 1) class TestFact(unittest.TestCase): def test_three(self): self.assertEqual(fact(3), 6) if __name__ == '__main__': unittest.main()
Avec py.test def fact(n): return 1 if n <= 1
else n * fact(n - 1) def test_fact(self): assert fact(3) == 6
Démo assertions
Les fixtures
Setup from selenium import webdriver import pytest @pytest.fixture def browser():
return webdriver.Firefox() def test_pycon(browser): browser.get('http://pycon.fr/') assert 'Bienvenue' in browser.title
Durée de vie @pytest.fixture(scope='function') ... @pytest.fixture(scope='module') ... @pytest.fixture(scope='session') ...
Teardown (1/2) @pytest.fixture def browser(request): b = webdriver.Firefox() def teardown():
b.quit() request.addfinalizer(teardown) return b
Teardown (2) @pytest.yield_fixture def browser(): b = webdriver.Firefox() yield b
b.quit()
Fixtures paramétrées @pytest.fixture(scope='session', params=['firefox', 'chrome']) def browser(request): if request.param ==
'firefox': return webdriver.Firefox() elif request.param == 'chrome': return webdriver.Chrome() else: raise ValueError('Unknown browser')
Trouver et lancer ses tests avec py.test
Rappel : Python ≥ 2.7 $ python -m unittest discover
py.test $ py.test
Découverte • Parcours récursif des répertoires • Fichiers test_*.py ou
*_test.py • Classes qui commencent par Test • Fonctions et méthodes qui commencent par test_ • Reconnait les tests unittest et nose existants
Exécuter seulement certains tests $ py.test tata/ $ py.test toto.py
$ py.test --pyargs mon.module
Collecter les tests uniquement $ py.test --collect-only
Un test bien précis $ py.test fichier.py::fonction $ py.test fichier.py::Classe::methode
Seulement les tests dont le nom contient un mot-clé $
py.test -k toto $ py.test -k 'toto or tata'
Exécution
S’arrêter en cas d'erreur $ py.test -x $ py.test --maxfail=3
Lancer le debugger en cas d’erreur $ py.test --pdb $
py.test -x --pdb
Contrôle de l'affichage
Afficher le nom des tests $ py.test -v
Ne pas capturer la sortie standard $ py.test -s $
py.test --capture=no
Niveau de détail des tracebacks $ py.test --tb=auto # défaut
$ py.test --tb=long $ py.test --tb=short $ py.test --tb=line $ py.test --tb=native $ py.test --tb=no
Afficher les valeurs des variables locales $ py.test --showlocals $
py.test -l
Afficher un résumé à la fin $ py.test -rf #
failures
Afficher les tests les plus lents $ py.test --durations=10
Plugins
Lancer ses tests en parallèle $ pip install pytest-xdist $
py.test -n4
Couverture de tests $ pip install pytest-cov $ py.test --cov
myproj
Django $ pip install pytest-django $ py.test --ds=proj.settings
BDD $ pip install pytest-bdd $ py.test --ds=proj.settings
Passer facilement à py.test
Recette facile en 2 étapes 1. Utilisez py.test pour lancer
vos tests existants (unittest, doctest, nose, Django) 2. Commencez à (ré)écrire vos tests dans le style py.test
En savoir plus http://pytest.org/
Questions ?
Merci !