Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Uma visão rápida de Django & PyTest
Search
Roger Camargo
January 09, 2016
Programming
73
3
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Uma visão rápida de Django & PyTest
Roger Camargo
January 09, 2016
More Decks by Roger Camargo
See All by Roger Camargo
AWS Lambda, Rodar local, com testes, IaC e Deploy via ansible
huogerac
1
45
Mapa de estudo dev frontend 2023
huogerac
1
97
Documentando API no Django com django-ninja
huogerac
1
140
Um pouco da origem para chegar no WSGI
huogerac
0
61
"API Design First" pt-br
huogerac
0
290
Design First Web APIs - OpenAPI 3
huogerac
1
120
3 Arquiteturas Django
huogerac
1
350
Django ORM vs SQLAlchemy (queries)
huogerac
0
220
Django ORM vs SQLAlchemy (intro)
huogerac
0
110
Other Decks in Programming
See All in Programming
技術的負債を組織課題として解く-増えすぎたマイクロサービスとの戦い-
reimaru
1
2.6k
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
390
mrbgem 三角測量 開発
ogom
0
180
UPDATE をやめる — EF Core でマスタをバージョン管理する
panda728
PRO
0
1.1k
Verilogで学ぶCPU自作入門.pdf
uyuki234
7
3.9k
GitHubハンズオン講座 — 実務レベルのチーム開発のフローを身につけよう
junhat6
0
120
マイコン向けの軽量Ruby「PicoRuby」で各種デバイスを制御するネイティブアプリの実現手法
bash0c7
0
470
Everything will be SERVERLESS — 信じて運用した10年の経験値 / Everything Will be Serverless — Lessons Learned from 10 Years of Operational Experience
seike460
PRO
1
680
iOSDC Japan 2026 - Swiftで作って学ぼう!データベース自作入門
kaseken
2
430
モバイル交通系ICへのチャージ実例から考える、クロスプラットフォーム開発におけるiOS実機テスト設計とCI運用
yusuga
1
570
カツオ、ご期待ください
suneo3476
0
140
Workers Cache を知る
syumai
0
320
Featured
See All Featured
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.9k
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
6
1.2k
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.5k
Optimising Largest Contentful Paint
csswizardry
37
4k
Amusing Abliteration
ianozsvald
1
320
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
900
WCS-LA-2024
lcolladotor
0
840
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
450
Practical Orchestrator
shlominoach
192
12k
What does AI have to do with Human Rights?
axbom
PRO
1
2.4k
Building AI with AI
inesmontani
PRO
1
1.3k
Transcript
Django & Pytest Roger Camargo - Django SJC meetup 9/jan/2016
Vantagens 1 Fácil de migrar para PyTest $ pip install
pytest-django [pytest] DJANGO_SETTINGS_MODULE=seucorretor.settings.development $ py.test
Vantagens 2 Melhor legibilidade from django.test import TestCase class TestHelloWorld(TestCase):
def test_hello_world(self): response = self.client.get('/hi/') self.assertEqual(response.status_code, 200)
def test_hello_world(client): response = client.get('/hi/') assert response.status_code == 200 Vantagens
2 Melhor legibilidade from django.test import TestCase class TestHelloWorld(TestCase): def test_hello_world(self): response = self.client.get('/hi/') self.assertEqual(response.status_code, 200) Pytest PyTest == Pythonic style fonte: A.Pelme 2013
Vantagens 3 Completo “a full-featured Python testing tool”
Vantagens 4 Plugins Fácil de estender
Vantagens 5 Fácil visualizar o problema (quando o teste falha)
======= FAILURES ======== _______ test_answer ________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:5: AssertionError ======= 1 failed in 0.12 seconds ========
Use Factories (não use fixtures do django) PyTest + Factory-Boy
ou PyTest + django-mommy
Use factories def test_lista_todos_imoveis(self): # Dado imovel_do_roger = Imovel.objects.create( proprietario=self.roger,
tipo_imovel=Imovel.TIPO_IMOVEL.apartamento, valor_venda=300000, dormitorios=2, cidade=self.sjc, bairro=self.aquarius, complemento='Apto 14A', ) ...
Use factories def setup_method(self, test_method): self.apartamento = Recipe(Imovel, proprietario=foreign_key(self.proprietario), tipo_imovel=Imovel.TIPO_IMOVEL.apartamento,
dormitorios=2, condominio=foreign_key(self.condominio), cidade=foreign_key(self.cidade), bairro=foreign_key(self.bairro), complemento='Apto 14A', ) def test_lista_todos_imoveis(self): # Dado apto = self.apartamento.make( valor_venda=300000, )
Resumo
Padrão Django class FiltrarTestCase(TestCase): def setUp(self): self.sjc = Cidade.objects.create(nome='São José
dos Campos') self.regiao_oeste = Regiao.objects.create(nome='Oeste', cidade=self.sjc) def test_lista_todos_imoveis(self): # Dado imovel_do_roger = Imovel.objects.create( proprietario=self.roger, tipo_imovel=Imovel.TIPO_IMOVEL.apartamento, valor_venda=300000, dormitorios=2, cidade=self.sjc, bairro=self.aquarius, complemento='Apto 14A', ) # Quando todos_imoveis = Imovel.objects.all() # É esperado self.assertEqual(1, len(todos_imoveis)) self.assertEqual(imovel_do_roger, todos_imoveis[0])
PyTest + django-mommy @pytest.mark.django_db class TestFiltrarImoveis: def setup_method(self, test_method): self.cidade
= Recipe(Cidade, nome='São José dos Campos') self.regiao = Recipe(Regiao, nome='Oeste') self.apartamento = Recipe(...) def test_lista_todos_imoveis(self): # Dado apto = self.apartamento.make(valor_venda=300000) # Quando todos_imoveis = Imovel.objects.all() # É esperado assert len(todos_imoveis) == 1 assert todos_imoveis[0] == apto
PyTest + django-mommy def test_lista_imoveis_por_qtd_min_dormitorio(self): # Dado apto150A = self.apartamento.make(
valor_venda=300000, dormitorios=3, complemento='Apto 150A', ) apto90A = self.apartamento.make( valor_venda=260000, dormitorios=2, complemento='Apto 90A', ) apto14A = self.apartamento.make( valor_venda=240000, dormitorios=1, complemento='Apto 14A', ) # Quando resultado = Imovel.para_venda.por_tipo_imovel( Imovel.TIPO_IMOVEL.apartamento).por_min_dormitorio(2) # É esperado assert len(resultado) == 2 assert apto14A not in resultado
PyTest + django-mommy def test_lista_imoveis_por_qtd_min_dormitorio(self): # É esperado assert apto150A,
apto90A in resultado assert casa, apto_locacao not in resultado
EXTRA
Refactoring sem testes https://twitter.com/RichRogersHDS/status/682618243882856448
"There is no secret to writing tests... there are only
secrets to writing testable code!" - Misko Hevery fonte: A.Pelme 2013
Referências: A.Pelme EUROPython 2013 https://www.youtube.com/watch?v=aUf8Fkb7TaY A.Toddy https://www.youtube.com/watch?v=P-AhpukDIik H. Krekel https://www.youtube.com/watch?v=9LVqBQcFmyw
Vinicius Assef https://www.youtube.com/watch?v=QUKoq2K7bis Bernardo Fontes http://www.slideshare.net/bernardofontes/melhorando-testes-no-django-com-o-model-mommy-21860913 http://pytest.org/latest/ https://pytest-django.readthedocs.org/en/latest/
Obrigado @huogerac
[email protected]