Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Uma visão rápida de Django & PyTest
Search
Roger Camargo
January 09, 2016
Programming
65
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
35
Mapa de estudo dev frontend 2023
huogerac
1
94
Documentando API no Django com django-ninja
huogerac
1
130
Um pouco da origem para chegar no WSGI
huogerac
0
55
"API Design First" pt-br
huogerac
0
280
Design First Web APIs - OpenAPI 3
huogerac
1
120
3 Arquiteturas Django
huogerac
1
350
Django ORM vs SQLAlchemy (queries)
huogerac
0
200
Django ORM vs SQLAlchemy (intro)
huogerac
0
110
Other Decks in Programming
See All in Programming
Contextとはなにか
chiroruxx
1
390
LLMによるContent Moderationの本番運用の裏側と品質担保への挑戦
suikabar
3
840
Hatena Engineer Seminar #37「言語モデルの活用に関する研究」
slashnephy
0
520
OS アップデート対応の取り組み方がもっと共有されてほしい
andpad
0
110
エンジニアと一緒にテストコードの設計と実装を改善した話
mototakatsu
0
260
ソフトウェア設計に溶けるインフラ ― AWS CDK のインフラ認識論
konokenj
2
240
AIを活用したE2Eテスト実装効率化のあゆみ / ebisu-mobile-14-kotetu
kotetuco
0
170
ローカルLLMでどこまでコードが書けるか -拡張版 / How much code can be written on a local LLM Extended
kishida
12
4.7k
初めてのKubernetes 本番運用でハマった話
oku053
0
120
1B+ /day規模のログを管理する技術
broadleaf
0
140
型も通る、synthも通る、それでも危ない 〜AIのCDKの権限とコストを機械で検証する〜 / It Passes Type Checks, It Passes Synth Checks, but It’s Still Risky — Automatically Verifying Permissions and Costs in AI’s CDK —
seike460
PRO
0
140
SREの積み重ねがAI駆動開発のガードレールになった ― 7つの実践/SRE Guardrails The 7
tomoyakitaura
8
4.1k
Featured
See All Featured
Unsuck your backbone
ammeep
672
58k
Typedesign – Prime Four
hannesfritz
42
3.1k
Bootstrapping a Software Product
garrettdimon
PRO
307
120k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
390
Paper Plane (Part 1)
katiecoart
PRO
0
9.6k
Large-scale JavaScript Application Architecture
addyosmani
515
110k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
367
27k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
128
56k
brightonSEO & MeasureFest 2025 - Christian Goodrich - Winning strategies for Black Friday CRO & PPC
cargoodrich
3
750
The Hidden Cost of Media on the Web [PixelPalooza 2025]
tammyeverts
2
340
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
460
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]