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
72
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
44
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
60
"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
A2UI for Android: Safely Rendering AI-Generated UI with Jetpack Compose - DroidKaigi 2026
itsmedreamwalker
0
140
スマートフォンでモールス信号を送受信する 〜スマートフォンのLEDとカメラで作る光通信の設計と実装〜
atsuki_seo
0
120
自分的「カンファレンスの楽しみ方」
syumai
0
200
How I Stole PSI from Android Studio - DroidKaigi2026
worker8
0
130
Building an Out-of-Order CPU
latte72
1
780
更なる可用性を求めて、5年間運用したKotlinのアプリケーションをGoでリプレイスする話
ken_tunc
0
240
Vibes Containers 〜AIで変わるコンテナ設計と運用〜
tkikuc
3
550
App Intentsのビルドプロセスを支える技術
kntkymt
0
370
テストを司るデーモンに会いに行く 〜隔離した仮想マシンでテストを通すまで〜
h1d3mun3
1
370
FreeBSDでZabbixを動かす.pdf
kenkino
0
280
AIは賢い。でも実行環境は? CLIおじさんがAI時代に伝えたいこと ~ CLIおじさんがAI時代に伝えたいこと ~
curekoshimizu
1
240
C#の現在地 進化の歴史と、AI時代の.NET Everywhere
neuecc
0
180
Featured
See All Featured
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
287
14k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.9k
Taking LLMs out of the black box: A practical guide to human-in-the-loop distillation
inesmontani
PRO
3
2.4k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
8.3k
Measuring Dark Social's Impact On Conversion and Attribution
stephenakadiri
2
280
More Than Pixels: Becoming A User Experience Designer
marktimemedia
3
520
Marketing Yourself as an Engineer | Alaka | Gurzu
gurzu
0
300
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.3k
Primal Persuasion: How to Engage the Brain for Learning That Lasts
tmiket
0
450
Site-Speed That Sticks
csswizardry
13
1.5k
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.7k
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]