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
66
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
36
Mapa de estudo dev frontend 2023
huogerac
1
96
Documentando API no Django com django-ninja
huogerac
1
130
Um pouco da origem para chegar no WSGI
huogerac
0
56
"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
210
Django ORM vs SQLAlchemy (intro)
huogerac
0
110
Other Decks in Programming
See All in Programming
為什麼你並不需要ViewModel / No, you don't need a ViewModel
lovee
1
480
Prismを使った型安全な暗号化_関数型まつり2026
_fhhmm
0
170
Foundation Models frameworkで画像分析
ryodeveloper
1
570
霧の中の代数的エフェクト
funnyycat
1
470
ドリフトを絶対に許さない(?)CDK運用 / CDK Ops with Zero Tolerance for Drifts (?)
akihisaikeda
1
170
使いながら育てる Claude Code — 開発フローの1コマンド化 × 繰り返し指摘の自動仕組み化
shiki_kakaku
0
1.7k
アルゴリズムは何を圧縮しているのか ─ Haskell から育った「圧縮代数」というメンタルモデル
naoya
16
3.8k
AWS CDK を「作」ってみた 〜フルスクラッチで見えた CDK の裏側〜 / aws-cdk-from-scratch
gotok365
3
2.8k
進化を続けるGo toolsの現在地 / The Current State of Ever-Evolving Go Tools
hond0413
0
130
「寝てても仕事が進む」Claude Codeで組む第二の脳
tomoyafujita2016
0
300
ソフトウェア設計に溶けるインフラ ― AWS CDK のインフラ認識論
konokenj
3
750
Apache Hive: そしてCloud Native Lakehouseへ
okumin
1
210
Featured
See All Featured
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
2
440
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
63
45k
Intergalactic Javascript Robots from Outer Space
tanoku
273
27k
Winning Ecommerce Organic Search in an AI Era - #searchnstuff2025
aleyda
1
2.1k
Designing Dashboards & Data Visualisations in Web Apps
destraynor
232
55k
The Language of Interfaces
destraynor
162
27k
Leveraging Curiosity to Care for An Aging Population
cassininazir
1
460
Evolving SEO for Evolving Search Engines
ryanjones
0
250
The Curse of the Amulet
leimatthew05
2
14k
VelocityConf: Rendering Performance Case Studies
addyosmani
333
25k
Marketing to machines
jonoalderson
1
5.6k
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
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]