SlideShare une entreprise Scribd logo
Python	Meetup	octobre	2016
les	tests	en	python
Introduction
Meetup	Python	Nantes	-	mai	2016
	( )	 	Arthur	Lutz Logilab @arthurlutz @logilab
Plan
introduction	aux	tests	unittaires
lancer	les	tests	:	unittest	de	base,	py.test,	nose,	pytest,	etc.
tox	pour	lancer	les	test	dans	des	virtualenvs
l'intégration	continue	avec	python	(jenkins,	travis,	etc.)
les	tests	en	prod	:	healthchecks	au	cœur	de	l'application
Meetup Python Nantes - les tests en python
introduction	aux	tests
unitaires
TDD	-	test	driven	developpement	-	dévelopement	piloté	par	les
tests
test	unitaire
passer	des	prints	et	vérification	humaine	à	un	point	OK/not	OK
documenter	des	exemples	d'usage	de	son	code
https://en.wikipedia.org/wiki/Test-driven_development
https://fr.wikipedia.org/wiki/Test_driven_development
https://fr.wikipedia.org/wiki/Test_unitaire
En	python
module	unittest
ne	pas	utiliser	assert	(assertTrue	à	la	place)
https://docs.python.org/3.5/library/unittest.html
assertEqual(a,	b)
assertNotEqual(a,	b)
assertTrue(x)
assertFalse(x)
Écrire	un	test
classes	héritant	de	unittest.TestCase
toutes	les	methodes	commencant	par	test	sont	considérées
comme	un	test	unittaire
Exemple	(de	la	doc)
				import	unittest
				class	TestStringMethods(unittest.TestCase):
								def	test_upper(self):
												self.assertEqual('foo'.upper(),	'FOO')
								def	test_isupper(self):
												self.assertTrue('FOO'.isupper())
												self.assertFalse('Foo'.isupper())
								def	test_split(self):
												s	=	'hello	world'
												self.assertEqual(s.split(),	['hello',	'world'])
												#	check	that	s.split	fails	when	the	separator	is	not	a	string
												with	self.assertRaises(TypeError):
																s.split(2)
				if	__name__	==	'__main__':
								unittest.main()
Avant	/	après	les	tests
def	setUp()
def	tearDown()
setUpClass	et	tearDownClass
setup_method	et	teardown_method
setup_function	et	teardown_function
https://en.wikipedia.org/wiki/Test_fixture#Software
Extensions
couvertures	de	tests	(pycoverage,	python-coverage,	etc.)
linters	(pychecker,	pylint,	flake8,	etc.)
doctests	https://docs.python.org/2/library/doctest.html
https://en.wikipedia.org/wiki/Fuzz_testing
Mock
mock	or	not	to	mock	(or	where	to	mock?)
unittest.mock	:
https://en.wikipedia.org/wiki/Mock_object
https://docs.python.org/3/library/unittest.mock.html
			>>>	from	unittest.mock	import	MagicMock
			>>>	thing	=	ProductionClass()
			>>>	thing.method	=	MagicMock(return_value=3)
			>>>	thing.method(3,	4,	5,	key='value')
			3
			>>>	thing.method.assert_called_with(3,	4,	5,	key='value')
Mock	encore
decorator	@patch
context	manager	with	Patch...
quelques	exemples	d'assertions
assert_called_with
assert_called_once_with
assert_any_call
assert_has_calls
assert_not_called
reset_mock
Ne	pas	mocker
postgresql	à	la	demande	:	
Python	fixtures	and	daemon	managing	tools	for	functional	testing:
http://faitout.fedorainfracloud.org/
https://github.com/jd/pifpaf
platform	specific	1/2
django
cubicweb	-	populate	DB
test	with	real	live	database
https://docs.djangoproject.com/en/1.10/topics/testing/
https://factoryboy.readthedocs.io/en/latest/
https://docs.cubicweb.org/book/devrepo/testing.html
https://docs.cubicweb.org/book/devrepo/testing.html#testing-
on-a-real-life-database
platform	specific	2/2
salt
from	salttesting	import	TestCase
infrastructure:
testinfra	:	
https://docs.saltstack.com/en/latest/topics/development/tests/unit.html
http://testinfra.readthedocs.io/en/latest/
Selenium
http://www.seleniumhq.org/
https://github.com/SeleniumHQ/selenium/tree/master/py
pip	install	selenium
Selenium	exemple
		import	unittest
		from	selenium	import	webdriver
		class	AfpyTestCase(unittest.TestCase):
				def	setUp(self):
								self.browser	=	webdriver.Firefox()
								self.addCleanup(self.browser.quit)
				def	testPageTitle(self):
								self.browser.get('http://nantes.afpy.org/')
								self.assertIn('Python-Nantes',	self.browser.title)
		if	__name__	==	'__main__':
				unittest.main(verbosity=2)
lancer	les	tests
unittest	de	base
unit2
pytest	(logilab-common)
py.test	(next	pytest)
nose	&	nose2
etc
https://wiki.python.org/moin/PythonTestingToolsTaxonomy
unittest.main
En	bas	de	chaque	fichier	python	:
Pour	le	lancer	:
if	__name__	==	'__main__':
			unittest.main()
#	python	test_this.py
pytest	(logilab-common)
historique
testlib	-	extension	de	unittest
pytest	-	lanceur	de	tests
selection	tags	avec	des	decorateurs	(tags)
supprimé	au	profit	de	nouveaux	projets
unit2
unittest2	est	un	backport	python2	du	nouveau	unittest	python3
unit2	==	python	-m	unittest2
unit2	discover
py.test
py.test	(bientôt	pytest)
http://docs.pytest.org/en/latest/
$	pip	install	pytest
py.test
py.test
py.test	-x	:	s'arrête	à	la	première	erreur
py.test	--maxfail=3	:	s'arrête	au	bout	de	3	erreurs
py.test	selection
py.test	test_module.py
py.test	test_mod.py::test_func
py.test	test_mod.py::TestClass::test_method
py.test	affichage
py.test	--tb=long	#	the	default	informative	traceback	formatting
py.test	--tb=native	#	the	Python	standard	library	formatting
py.test	--tb=short	#	a	shorter	traceback	format
py.test	--tb=line	#	only	one	line	per	failure
py.test	avancé
markers	
fixtures	
parametrisation	
py.test	--fixtures
plugins	pip	search	pytest	(ou	apt-cache	search	pytest)
http://docs.pytest.org/en/latest/mark.html
http://docs.pytest.org/en/latest/fixture.html
http://docs.pytest.org/en/latest/parametrize.html
nose	&	nose2
Commandes	:
nosetests
nose2
https://nose.readthedocs.io/en/latest/
https://github.com/nose-devs/nose2
tox	pour	lancer	les	test	dans
des	virtualenvs
https://tox.readthedocs.io/en/latest/
#	content	of:	tox.ini	,	put	in	same	dir	as	setup.py
[tox]
envlist	=	py26,py27
[testenv]
deps=pytest							#	install	pytest	in	the	venvs
commands=py.test		#	or	'nosetests'	or	...
tox	est	amour
Slides	:	
Vidéo	:	
http://tox.jehaisleprintemps.net/#/
http://video-pyconfr2015.paulla.asso.fr/108_-
_Bruno_Bord_-_tox_est_amour.html
Accélerer	tox	:	caches
server	pypi	local	:	
dans	docker	(avec	apt-cacher-ng	et	squid)
http://doc.devpi.net/latest/
https://github.com/ebar0n/proxy-cache
L'intégration	continue	avec
python
	(monopole	avec	github	?)
	(tests	sous	windows)
etc.
hudson
jenkins
apycot
travis
bitbucket	pipelines
drone.io
appveyor
Jenkins
Python	Plugin	:	
Shining	Panda	:	
https://wiki.jenkins-
ci.org/display/JENKINS/Python+Plugin
https://wiki.jenkins-
ci.org/display/JENKINS/ShiningPanda+Plugin
Matrix	Project
Matrix	Project	pour	plusieurs	environnements	:
jenkins-job-builder	(description	de	vos	projets	en	YAML)	:
https://wiki.jenkins-ci.org/display/JENKINS/Matrix+Project+Plugin
http://docs.openstack.org/infra/jenkins-job-
builder/project_matrix.html
Junit	/	xUnit
fichiers	XML	de	description	des	tests	réussis	ou	non
il	existe	aussi	des	formats	xml	pour	la	couverture	de	tests
(Corbetura,	etc.)
https://en.wikipedia.org/wiki/XUnit
Quand	lancer	les	tests	?
Sur	chaque	pull	request	?
sur	chaque	tête
avant	un	push	?	avant	un	commit	?
sur	l'ensemble	?
sur	quel	sous-ensemble	?
les	tests	en	prod	:
healthchecks	au	cœur	de
l'application
Inspirations
pyconfr	2015	:	Benoit	Bryon,	Peopledoc
Kelsey	Hightower	-	healthz:	Stop	reverse	engineering	applications
and	start	monitoring	from	the	inside
Vidéo	:	
Code	:	
https://blog.notmyidea.org/pyconfr-2015-hospital-des-tests-en-
prod.html
https://vimeo.com/173610242
https://github.com/kelseyhightower/app-healthz
healthchecks	-	principe
lancer	des	tests	directement	au	coeur	de	l'application	en
production
complément	de	la	supervision	traditionnelle
permet	de	différentier	entre	"le	process	tourne"	et
"le	service	répond"
particulièrement	utile	pour	le	déploiement	continue	et	la
répartission	de	charge	dynamique
healthchecks	en	python
https://github.com/python-hospital/hospital
https://github.com/danielfrg/django-hospital
https://github.com/healthchecks/healthchecks
https://github.com/ludia/pyramid_health
Fin
Des	questions	?
Des	ajouts	?
Présentation	:	
Contact	:	 	
http://slides.logilab.fr/2016/meetup_python_nantes_tests/
@arthurlutz @logilab

Contenu connexe

PDF
De la chaîne de production au SI géré par des logiciels
PDF
Testinfra pyconfr 2017
PDF
Formation Gratuite Total Tests par les experts Java Ippon
PDF
Production logicielle, outils et pratiques
PDF
Outils de construction pour la recherche
PPTX
Les tests en PHP
PDF
Java OOP Programming language (Part 1) - Introduction to Java
PDF
Python - Lecture 1
De la chaîne de production au SI géré par des logiciels
Testinfra pyconfr 2017
Formation Gratuite Total Tests par les experts Java Ippon
Production logicielle, outils et pratiques
Outils de construction pour la recherche
Les tests en PHP
Java OOP Programming language (Part 1) - Introduction to Java
Python - Lecture 1

En vedette (20)

PPTX
Introduction to Advanced Javascript
PDF
Learning notes of r for python programmer (Temp1)
PDF
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
PDF
PyCon 2013 : Scripting to PyPi to GitHub and More
PPT
Operator Overloading
PDF
Installing Python on Mac
PDF
Python for All
PDF
Lesson1 python an introduction
PDF
Introduction to python
PDF
Python master class part 1
DOCX
Introduction to Python - Running Notes
PDF
Introduction to facebook java script sdk
PDF
Introduction to facebook javascript sdk
PPTX
Mastering python lesson2
PPTX
Lec02 structures (2)
PDF
Running openCV project on Mac OS
PDF
Concise Notes on Python
PPTX
Python Basis Tutorial
PPT
Uncommon Python - What is special in Python
PPTX
Python Hype?
Introduction to Advanced Javascript
Learning notes of r for python programmer (Temp1)
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
PyCon 2013 : Scripting to PyPi to GitHub and More
Operator Overloading
Installing Python on Mac
Python for All
Lesson1 python an introduction
Introduction to python
Python master class part 1
Introduction to Python - Running Notes
Introduction to facebook java script sdk
Introduction to facebook javascript sdk
Mastering python lesson2
Lec02 structures (2)
Running openCV project on Mac OS
Concise Notes on Python
Python Basis Tutorial
Uncommon Python - What is special in Python
Python Hype?
Publicité

Plus de Arthur Lutz (18)

PDF
Donnez des couleurs a votre terminal
PDF
Capitole du Libre 2018 - Déployer des applications python dans un cluster Ope...
PDF
PyParis2018 - Python tooling for continuous deployment
PDF
Pyconfr2018 deploy des application python dans un cluster open shift
PDF
Meetup Nantes Monitoring - janvier 2018 - netdata & sensu
PDF
Salt Paris Meetup - septembre 2017 - formulas and salt-cloud
PDF
Meetup Nantes Monitoring - Supervision d'une application web (et de son archi...
PDF
Python Nantes Meetup - Collecter les erreurs avec Sentry
PDF
Collecter les erreurs de description d'infrastructure avec Salt et Sentry
PDF
cfgmgmtcamp 2016 - Roll out active Supervision with Salt, Graphite and Grafana
PDF
FOSDEM 2016 - After describing your infrastructure as code, reuse that to mon...
PDF
Salt Paris meetup - décembre 2015 - La supervision pilotée par Salt avec carb...
PDF
Debian meetup nantes 2015 : Salt pour gérer de nombreux serveurs debian
PDF
Pyconfr2015 : Marre de faire du C++ sur une Arduino ? Faites du Python avec M...
PDF
PyConFR 2015 : Utiliser salt pour tester son infrastructure sur open stack ou...
PDF
Générer des stats sur son infra salt
PDF
Présentation "Outils agiles : revue de code & publication continue"
PDF
Présentation éclair "Retours d'experience data.bnf.fr" - datapride Nantes
Donnez des couleurs a votre terminal
Capitole du Libre 2018 - Déployer des applications python dans un cluster Ope...
PyParis2018 - Python tooling for continuous deployment
Pyconfr2018 deploy des application python dans un cluster open shift
Meetup Nantes Monitoring - janvier 2018 - netdata & sensu
Salt Paris Meetup - septembre 2017 - formulas and salt-cloud
Meetup Nantes Monitoring - Supervision d'une application web (et de son archi...
Python Nantes Meetup - Collecter les erreurs avec Sentry
Collecter les erreurs de description d'infrastructure avec Salt et Sentry
cfgmgmtcamp 2016 - Roll out active Supervision with Salt, Graphite and Grafana
FOSDEM 2016 - After describing your infrastructure as code, reuse that to mon...
Salt Paris meetup - décembre 2015 - La supervision pilotée par Salt avec carb...
Debian meetup nantes 2015 : Salt pour gérer de nombreux serveurs debian
Pyconfr2015 : Marre de faire du C++ sur une Arduino ? Faites du Python avec M...
PyConFR 2015 : Utiliser salt pour tester son infrastructure sur open stack ou...
Générer des stats sur son infra salt
Présentation "Outils agiles : revue de code & publication continue"
Présentation éclair "Retours d'experience data.bnf.fr" - datapride Nantes
Publicité

Meetup Python Nantes - les tests en python