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
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
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
91
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
340
Django ORM vs SQLAlchemy (queries)
huogerac
0
200
Django ORM vs SQLAlchemy (intro)
huogerac
0
110
Other Decks in Programming
See All in Programming
Vite+ Unified Toolchain for the Web
naokihaba
0
320
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
240
ユニットテストの先へ:テスト技法で要求・仕様を整理するJava開発実践 / Beyond_Unit_Testing_Practical_Java_Development_Techniques_for_Organizing_Requirements_and_Specifications
shimashima35
0
410
ECSアプリログをFireLensでコスト削減しようとしたけど諦めた話 in Fargate×Node.js
akihisaikeda
2
4.2k
メソッドのジェネリクスでGoの夢は広がるか? / Kyoto.go #65
utgwkk
3
810
作って学ぶ、 JSX (TSX) ランタイムの基本
syumai
7
1.6k
LLM本来の能力を解き放つサンドボックス技術とAI民主化への適用
yukukotani
3
4.3k
Claspは野良GASの夢をみるか
takter00
0
200
気づいたらRubyで100作品 ー クリエイティブコーディングが生活の一部になるまで / 100 Ruby Sketches Later: How Creative Coding Became Part of My Life
chobishiba
3
590
Lemonade + Foundry Toolkit でお手軽アプリ開発
seosoft
1
360
CSC307 Lecture 17
javiergs
PRO
0
320
IBM Bobを活用したレガシーアプリの最新化
oniak3ibm
PRO
1
200
Featured
See All Featured
The innovator’s Mindset - Leading Through an Era of Exponential Change - McGill University 2025
jdejongh
PRO
1
200
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
160
The Cult of Friendly URLs
andyhume
79
6.9k
Digital Projects Gone Horribly Wrong (And the UX Pros Who Still Save the Day) - Dean Schuster
uxyall
1
1.7k
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
0
420
ReactJS: Keep Simple. Everything can be a component!
pedronauck
666
130k
Making Projects Easy
brettharned
120
6.7k
Digital Ethics as a Driver of Design Innovation
axbom
PRO
1
320
Building Applications with DynamoDB
mza
96
7.1k
Joys of Absence: A Defence of Solitary Play
codingconduct
1
400
The Illustrated Children's Guide to Kubernetes
chrisshort
51
52k
Being A Developer After 40
akosma
91
590k
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]