SlideShare a Scribd company logo
INTRODUÇÃO A TESTESINTRODUÇÃO A TESTES
COMCOM DJANGODJANGO
IgorLeroy
POR QUE?POR QUE?
PRA QUE? CONFIO NO MEU CÓDIGO, EU GARANTO!PRA QUE? CONFIO NO MEU CÓDIGO, EU GARANTO!
RETRABALHO, RETRABALHO E CAÇA AOS BUGS.RETRABALHO, RETRABALHO E CAÇA AOS BUGS.
NAAH... CHEGA DISSO.NAAH... CHEGA DISSO.
TESTES DEVEM SER OBRIGATÓRIOS!TESTES DEVEM SER OBRIGATÓRIOS!
CULTURACULTURA
CÓDIGOCÓDIGO SIMPLESSIMPLES == FÁCIL DE TESTAR== FÁCIL DE TESTAR
CÓDIGOCÓDIGO MODULARIZADOMODULARIZADO == FÁCIL DE TESTAR== FÁCIL DE TESTAR
MODULARIZAÇÃOMODULARIZAÇÃO =!=! ABSTRAÇÃOABSTRAÇÃO
DJANGO 1.4, 1.5DJANGO 1.4, 1.5
project/myapp/tests.pyproject/myapp/tests.py
./manage.py test myapp./manage.py test myapp
TESTES UNITÁRIOSTESTES UNITÁRIOS
from django.test import TestCase
from myapp.models import Animal
class AnimalTestCase(TestCase):
def setUp(self):
Animal.objects.create(name="lion", sound="roar")
Animal.objects.create(name="cat", sound="meow")
def test_animals_can_speak(self):
"""Animals that can speak are correctly identified"""
lion = Animal.objects.get(name="lion")
cat = Animal.objects.get(name="cat")
self.assertEqual(lion.speak(), 'The lion says "roar"')
self.assertEqual(cat.speak(), 'The cat says "meow"')
TESTES FUNCIONAISTESTES FUNCIONAIS
import unittest
from django.test import Client
class SimpleTest(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_details(self):
response = self.client.get('/customer/details/')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['customers']), 5)
TESTS.PYTESTS.PY
UM ÚNICO MODULO DE TESTES É UMAUM ÚNICO MODULO DE TESTES É UMA MÁMÁ IDÉIA.IDÉIA.
TESTES TAMBÉM SÃO CÓDIGOS,TESTES TAMBÉM SÃO CÓDIGOS, PRECISAMPRECISAM SERSER
MODULARIZADOS.MODULARIZADOS.
BEM ESCRITO E FÁCILBEM ESCRITO E FÁCIL DE ENTENDER.DE ENTENDER.
TEST RUNNERTEST RUNNER
DJANGONOSE
https://github.com/jbalogh/django-nose
TEST_RUNNER='django_nose.NoseTestSuiteRunner'
ONOSEpossuemaiscoisaslegais!
TEST ENVIRONMENTTEST ENVIRONMENT
createdb -U postgres_user -h localhost test_db
python manage.py syncdb --settings myproject.test_settings
python manage.py migrate --settings myproject.test_settings
os.environ['REUSE_DB'] = "1"
ou
REUSE_DB=1 python manage.py test
FIXTURESFIXTURES
='(
{
"pk": 4,
"model": "auth.user",
"fields": {
"username": "manager",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": false,
"is_staff": false,
"last_login": "2012-02-06 15:06:44",
FACTORYGIRL
FACTORYBOY
MODEL MOMMY!MODEL MOMMY!
https://github.com/vandersonmota/model_mommy
Dadosemmemória.
SetornaopcionalsalvardadosnoDB.
Rápido!
Introdução a testes com Django (2013)
from model_mommy import mommy
from family.models import Kid
kid = mommy.make(Kid)
MOMMY_MODELS.PYMOMMY_MODELS.PY
from model_mommy.recipe import Recipe, foreign_key
from family.models import Person, Dog
person = Recipe(Person,
name = 'John Doe',
nickname = 'joe',
age = 18,
birthday = date.today(),
appointment = datetime.now()
)
dog = Recipe(Dog,
breed = 'Pug',
owner = foreign_key(person)
)
E AGORA?E AGORA?
.....myapp/
...................tests/
.............................test_models.py
.............................test_views.py
.............................test_urls.py
.............................test_forms.py
.............................test_features.py
BDD!BDD!
Client()éumaboaidéia?
Testarsomentenossocódigopythonnãofaznosso
sistema100%livredebugs.
Precisamostestarasfuncionalidades.
CAPYBARACAPYBARA
SPLINTERSPLINTER!!
http://splinter.cobrateam.info
Introdução a testes com Django (2013)
from splinter import Browser
browser = Browser()
browser.visit('http://google.com')
browser.fill('q', 'splinter - python acceptance testing for web
applications')
browser.find_by_name('btnG').click()
if browser.is_text_present('splinter.cobrateam.info'):
print "Yes, the official website was found!"
else:
print "No, it wasn't found... We need to improve our SEO te
chniques"
browser.quit()
Obrigado!
@lerrua
github.com/lerrua

More Related Content

PDF
Python Type Hints
Igor Leroy
 
PDF
First steps with Data Science
Igor Leroy
 
PDF
O mundo mágico do Trabalho Remoto
Igor Leroy
 
PDF
Por que escolher Python?
Igor Leroy
 
PDF
Ruby vs python
Igor Leroy
 
PDF
2024 Trend Updates: What Really Works In SEO & Content Marketing
Search Engine Journal
 
PDF
Storytelling For The Web: Integrate Storytelling in your Design Process
Chiara Aliotta
 
PDF
Artificial Intelligence, Data and Competition – SCHREPEL – June 2024 OECD dis...
OECD Directorate for Financial and Enterprise Affairs
 
Python Type Hints
Igor Leroy
 
First steps with Data Science
Igor Leroy
 
O mundo mágico do Trabalho Remoto
Igor Leroy
 
Por que escolher Python?
Igor Leroy
 
Ruby vs python
Igor Leroy
 
2024 Trend Updates: What Really Works In SEO & Content Marketing
Search Engine Journal
 
Storytelling For The Web: Integrate Storytelling in your Design Process
Chiara Aliotta
 
Artificial Intelligence, Data and Competition – SCHREPEL – June 2024 OECD dis...
OECD Directorate for Financial and Enterprise Affairs
 

Recently uploaded (20)

PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Doc9.....................................
SofiaCollazos
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Software Development Methodologies in 2025
KodekX
 
The Future of Artificial Intelligence (AI)
Mukul
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Ad
Ad

Introdução a testes com Django (2013)