SlideShare a Scribd company logo
1 of 13
1 de 13
py.test
testes
pythonicos
com
Vinicius Assef - @viniciusban
2 de 13
ambiente
● sem boilerplate
● sem classes
● roda doctests, unittests e nosetests
$ pip install pytest
3 de 13
# test_f.py
from modulo import f
def test_f():
assert f(1) == 1
simplesmente teste
# test_f.py
import pytest
from modulo import um
def test_um():
with pytest.raises(ValueError):
um(2)
4 de 13
convenções
● test_*.py ou *_test.py
● recursedirs
● class Test* # sem def __init__()
● def test_*()
● configuráveis via .ini
5 de 13
mensagens de erro
$ pytest -v
======================== test session starts
=========================
platform linux2 -- Python 2.7.3 -- pytest-2.3.5
collected 1 items
test_f.py:10: test_f1_eh_1 FAILED
============================== FAILURES
==============================
____________________________ test_f1_eh_1
____________________________
def test_f1_eh_1():
> assert f(1) == 0
E assert 1 == 0
E + where 1 = f(1)
test_f.py:11: AssertionError
====================== 1 failed in 0.01 seconds
======================
6 de 13
erro em lista
============================== FAILURES
==============================
________________________ test_lista_completa
_________________________
def test_lista_completa():
> assert "a b".split() == lista()
E assert ['a', 'b'] == ['a', 'b', 'c']
E Right contains more items, first extra item: 'c'
test_f.py:8: AssertionError
====================== 1 failed in 0.01 seconds
======================
7 de 13
erro em dicionário
__________________________ test_dicionario
___________________________
def test_dicionario():
> assert dict(i=20, n="pedro", f="junior") == dicionario()
E assert {'f': 'junior... 'n': 'pedro'} == {'i': 20, 'n':
'pedro'}
E Hiding 2 identical items, use -v to show
E Left contains more items:
E {'f': 'junior'}
test_f.py:10: AssertionError
================= 1 failed, 1 passed in 0.02 seconds
=================
8 de 13
# conftest.py
import pytest
@pytest.fixture
def texto():
return "abc"
fixtures
# test_tudo.py
def test_abc(texto):
assert texto == "abc"
9 de 13
# conftest.py
import pytest
@pytest.fixture
def xyz():
return "x"
@pytest.fixture
def texto(xyz):
return "abc %s" % xyz
fixtures consomem fixtures
10 de 13
escopo de fixtures
@pytest.fixture(scope="module")
● setUp e tearDown
● request.addfinalizer()
● podem receber parâmetros do módulo de
teste
11 de 13
fixtures automáticas
@pytest.fixture(autouse=True)
● setUp e tearDown on steroids
12 de 13
plugins
● pytest-django
● pytest-xdist
● pytest-pep8
● pytest-cov
● oejskit
● Executados automaticamente
13 de 13
viniciusban
twitter
gmail
github
skype

More Related Content

What's hot

Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 

What's hot (20)

Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Selenium TestNG
Selenium TestNGSelenium TestNG
Selenium TestNG
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Selenium cheat sheet
Selenium cheat sheetSelenium cheat sheet
Selenium cheat sheet
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Junit
JunitJunit
Junit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Postman과 Newman을 이용한 RestAPI 테스트 자동화 가이드
Postman과 Newman을 이용한 RestAPI 테스트 자동화 가이드 Postman과 Newman을 이용한 RestAPI 테스트 자동화 가이드
Postman과 Newman을 이용한 RestAPI 테스트 자동화 가이드
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
PHPUnit - Unit testing
PHPUnit - Unit testingPHPUnit - Unit testing
PHPUnit - Unit testing
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
Clean code
Clean codeClean code
Clean code
 

Viewers also liked

Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?
Bernardo Fontes
 
Django: um framework web para perfeccionistas com prazo
Django: um framework web para perfeccionistas com prazoDjango: um framework web para perfeccionistas com prazo
Django: um framework web para perfeccionistas com prazo
Bernardo Fontes
 
Aula 5 linguagens regularese automatosfinitosnãodeterministico
Aula 5   linguagens regularese automatosfinitosnãodeterministicoAula 5   linguagens regularese automatosfinitosnãodeterministico
Aula 5 linguagens regularese automatosfinitosnãodeterministico
wab030
 
Apresentação python fábio jr alves
Apresentação python   fábio jr alvesApresentação python   fábio jr alves
Apresentação python fábio jr alves
Grupython Ufla
 
14 programando em python - interfaces graficas com tk
 14   programando em python - interfaces graficas com tk 14   programando em python - interfaces graficas com tk
14 programando em python - interfaces graficas com tk
Victor Marcelino
 

Viewers also liked (20)

TDD em django sem desculpas versao fisl
TDD em django sem desculpas versao fislTDD em django sem desculpas versao fisl
TDD em django sem desculpas versao fisl
 
Testes, deploy e integração continua com Python e Django
Testes, deploy e integração continua com Python e DjangoTestes, deploy e integração continua com Python e Django
Testes, deploy e integração continua com Python e Django
 
Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?
 
TDD com Python
TDD com PythonTDD com Python
TDD com Python
 
Melhorando Testes No Django Com O Model Mommy
Melhorando Testes No Django Com O Model MommyMelhorando Testes No Django Com O Model Mommy
Melhorando Testes No Django Com O Model Mommy
 
Como melhoramos a performance dos testes automatizados com py.test e factoryboy
Como melhoramos a performance dos testes automatizados com py.test e factoryboyComo melhoramos a performance dos testes automatizados com py.test e factoryboy
Como melhoramos a performance dos testes automatizados com py.test e factoryboy
 
Customizando Admin do Django
Customizando Admin do DjangoCustomizando Admin do Django
Customizando Admin do Django
 
python: Listas, deques, Dicionarios e outros monstros mitologicos
python: Listas, deques, Dicionarios e outros monstros mitologicospython: Listas, deques, Dicionarios e outros monstros mitologicos
python: Listas, deques, Dicionarios e outros monstros mitologicos
 
Django: um framework web para perfeccionistas com prazo
Django: um framework web para perfeccionistas com prazoDjango: um framework web para perfeccionistas com prazo
Django: um framework web para perfeccionistas com prazo
 
Aula 5 linguagens regularese automatosfinitosnãodeterministico
Aula 5   linguagens regularese automatosfinitosnãodeterministicoAula 5   linguagens regularese automatosfinitosnãodeterministico
Aula 5 linguagens regularese automatosfinitosnãodeterministico
 
REST com Python
REST com PythonREST com Python
REST com Python
 
Apresentando a Linguagem de Programação Python
Apresentando a Linguagem de Programação PythonApresentando a Linguagem de Programação Python
Apresentando a Linguagem de Programação Python
 
Arduino: Brincando de eletrônica com Python e Hardware Livre
Arduino: Brincando de eletrônica com Python e Hardware LivreArduino: Brincando de eletrônica com Python e Hardware Livre
Arduino: Brincando de eletrônica com Python e Hardware Livre
 
Apresentação python fábio jr alves
Apresentação python   fábio jr alvesApresentação python   fábio jr alves
Apresentação python fábio jr alves
 
14 programando em python - interfaces graficas com tk
 14   programando em python - interfaces graficas com tk 14   programando em python - interfaces graficas com tk
14 programando em python - interfaces graficas com tk
 
Introdução à Programação em Python
Introdução à Programação em PythonIntrodução à Programação em Python
Introdução à Programação em Python
 
Desenvolvendo aplicações web com python e web2py
Desenvolvendo aplicações web com python e web2pyDesenvolvendo aplicações web com python e web2py
Desenvolvendo aplicações web com python e web2py
 
Seminário - Guido van Rossum: Breve história da linguagem Python
Seminário - Guido van Rossum: Breve história da linguagem PythonSeminário - Guido van Rossum: Breve história da linguagem Python
Seminário - Guido van Rossum: Breve história da linguagem Python
 
Python - Programação funcional
Python - Programação funcionalPython - Programação funcional
Python - Programação funcional
 
Arduino: Robótica e Automação com Software e Hardware Livres
Arduino: Robótica e Automação com Software e Hardware LivresArduino: Robótica e Automação com Software e Hardware Livres
Arduino: Robótica e Automação com Software e Hardware Livres
 

Similar to Testes pythonicos com pytest

pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기
Yeongseon Choe
 
Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010
Timo Stollenwerk
 
ZopeSkel & Buildout packages
ZopeSkel & Buildout packagesZopeSkel & Buildout packages
ZopeSkel & Buildout packages
Quintagroup
 

Similar to Testes pythonicos com pytest (20)

UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
 
Commencer avec le TDD
Commencer avec le TDDCommencer avec le TDD
Commencer avec le TDD
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Software development practices in python
Software development practices in pythonSoftware development practices in python
Software development practices in python
 
pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기pytest로 파이썬 코드 테스트하기
pytest로 파이썬 코드 테스트하기
 
Python testing
Python  testingPython  testing
Python testing
 
Isolated development in python
Isolated development in pythonIsolated development in python
Isolated development in python
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
Using Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsUsing Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python Projects
 
Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
ZopeSkel & Buildout packages
ZopeSkel & Buildout packagesZopeSkel & Buildout packages
ZopeSkel & Buildout packages
 

More from viniciusban (7)

Gitlab flow solo
Gitlab flow soloGitlab flow solo
Gitlab flow solo
 
Gitlab flow solo (pt-BR)
Gitlab flow solo (pt-BR)Gitlab flow solo (pt-BR)
Gitlab flow solo (pt-BR)
 
Gitlab flow solo (minimo)
Gitlab flow solo (minimo)Gitlab flow solo (minimo)
Gitlab flow solo (minimo)
 
Gitlab flow
Gitlab flowGitlab flow
Gitlab flow
 
Git na pratica
Git na praticaGit na pratica
Git na pratica
 
Git conceitos
Git conceitosGit conceitos
Git conceitos
 
Git commits - como, quando e por quê?
Git commits - como, quando e por quê?Git commits - como, quando e por quê?
Git commits - como, quando e por quê?
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Testes pythonicos com pytest

  • 2. 2 de 13 ambiente ● sem boilerplate ● sem classes ● roda doctests, unittests e nosetests $ pip install pytest
  • 3. 3 de 13 # test_f.py from modulo import f def test_f(): assert f(1) == 1 simplesmente teste # test_f.py import pytest from modulo import um def test_um(): with pytest.raises(ValueError): um(2)
  • 4. 4 de 13 convenções ● test_*.py ou *_test.py ● recursedirs ● class Test* # sem def __init__() ● def test_*() ● configuráveis via .ini
  • 5. 5 de 13 mensagens de erro $ pytest -v ======================== test session starts ========================= platform linux2 -- Python 2.7.3 -- pytest-2.3.5 collected 1 items test_f.py:10: test_f1_eh_1 FAILED ============================== FAILURES ============================== ____________________________ test_f1_eh_1 ____________________________ def test_f1_eh_1(): > assert f(1) == 0 E assert 1 == 0 E + where 1 = f(1) test_f.py:11: AssertionError ====================== 1 failed in 0.01 seconds ======================
  • 6. 6 de 13 erro em lista ============================== FAILURES ============================== ________________________ test_lista_completa _________________________ def test_lista_completa(): > assert "a b".split() == lista() E assert ['a', 'b'] == ['a', 'b', 'c'] E Right contains more items, first extra item: 'c' test_f.py:8: AssertionError ====================== 1 failed in 0.01 seconds ======================
  • 7. 7 de 13 erro em dicionário __________________________ test_dicionario ___________________________ def test_dicionario(): > assert dict(i=20, n="pedro", f="junior") == dicionario() E assert {'f': 'junior... 'n': 'pedro'} == {'i': 20, 'n': 'pedro'} E Hiding 2 identical items, use -v to show E Left contains more items: E {'f': 'junior'} test_f.py:10: AssertionError ================= 1 failed, 1 passed in 0.02 seconds =================
  • 8. 8 de 13 # conftest.py import pytest @pytest.fixture def texto(): return "abc" fixtures # test_tudo.py def test_abc(texto): assert texto == "abc"
  • 9. 9 de 13 # conftest.py import pytest @pytest.fixture def xyz(): return "x" @pytest.fixture def texto(xyz): return "abc %s" % xyz fixtures consomem fixtures
  • 10. 10 de 13 escopo de fixtures @pytest.fixture(scope="module") ● setUp e tearDown ● request.addfinalizer() ● podem receber parâmetros do módulo de teste
  • 11. 11 de 13 fixtures automáticas @pytest.fixture(autouse=True) ● setUp e tearDown on steroids
  • 12. 12 de 13 plugins ● pytest-django ● pytest-xdist ● pytest-pep8 ● pytest-cov ● oejskit ● Executados automaticamente