SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
The Test Client
  Dr Russell Keith-Magee
     DjangoCon 2009
What is it?

• A way to build unit tests of the full stack
• Acts “kinda-sorta” like a browser
• Stateful
• Default instance on django.test.TestCase
• Can be instantiated outside test framework
The test client isn’t

• A live browser test framework
 • Selenium
 • Twill
 • Windmill
Why is it different?

• TestClient can’t do some things
 • No JavaScript
 • DOM validation or control
• Can do some things that browsers can’t
GET a page
c = TestClient()

c.get(‘/foo/’)

c.get(‘/foo/’, data={‘bar’:3})

c.get(‘/foo/?bar=3’)
Returns a response

• response.status_code
• response.content
• response.cookies
• response[‘Content-Disposition’]
... and a little more
• response.template
 • The template(s) used used in rendering
• response.context
 • The context objects used in rendering
 • response.context[‘foo’]
... and it maintains state


• self.cookies
• self.session
Login/Logout

c.login(username='foo',
        password='password')

c.logout()
POST a page
c = TestClient()

c.post(‘/foo/’)

c.post(‘/foo/?bar=3’)

c.post(‘/foo/’, data={‘bar’: 3})

c.get(‘/foo/?whiz=4’, data={‘bar’:3})
Rest of HTTP
c.put(‘/foo/’)

c.options(‘/foo/’)

c.head(‘/foo/’)

c.delete(‘/foo/’)
A common gotcha
r = self.client.get(‘/foo’)

self.assertEquals(r.status_code, 200)

FAIL Assertion Error: 301 != 200
The fix
r = self.client.get(‘/foo’,
                    follow=True)
self.assertEquals(r.status_code, 200)

response.redirect_chain
  ➡ links visited before a non-redirect was found.
Extra Headers
c = TestClient(HTTP_HOST=‘foo.com’)

c.get(‘/foo/’, HTTP_HOST=‘foo.com’)

response['X-DJANGO-TEST']
Files
c = TestClient()

f = open(‘mydata.txt’)
c.post(‘/foo/’,
    content_type=MULTIPART_CONTENT
    data = {‘file’: f})
f.close()
Assertions
• assertContains()
• assertNotContains()
• assertFormError()
• assertTemplateUsed()
• assertTemplateNotUsed()
• assertRedirects()
Advice
• Don’t rely on assertContains
 • Assertions on template content are weak
• Test at the source
 • Is the context right?
 • Are the forms correct?
• Django’s templates make this possible!
When to use TestClient

• When you need to test the full stack
 • interaction of view and middleware
• Great for testing idempotency
Interesting hack

• Use Client as a factory for Request objects
 • Ticket #9002, Snippet #963
• Then:
 • Construct a request object
 • Use to test a single view/middleware call
Fin

Mais conteúdo relacionado

Mais procurados (6)

C A S Sample Php
C A S Sample PhpC A S Sample Php
C A S Sample Php
 
Client-side Storage 
Client-side Storage Client-side Storage 
Client-side Storage 
 
4. Php MongoDB view_data
4. Php MongoDB view_data4. Php MongoDB view_data
4. Php MongoDB view_data
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
Knockout.js Overview
Knockout.js OverviewKnockout.js Overview
Knockout.js Overview
 
Django Show
Django ShowDjango Show
Django Show
 

Destaque

Fighting Malnutrition with SMS and Django
Fighting Malnutrition with SMS and DjangoFighting Malnutrition with SMS and Django
Fighting Malnutrition with SMS and Django
Andy McKay
 

Destaque (6)

DjangoCon09: No! Bad Pony!
DjangoCon09: No! Bad Pony!DjangoCon09: No! Bad Pony!
DjangoCon09: No! Bad Pony!
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-config
 
State of Pinax
State of PinaxState of Pinax
State of Pinax
 
Fighting Malnutrition with SMS and Django
Fighting Malnutrition with SMS and DjangoFighting Malnutrition with SMS and Django
Fighting Malnutrition with SMS and Django
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with Django
 
DjangoCon 2009 Keynote
DjangoCon 2009 KeynoteDjangoCon 2009 Keynote
DjangoCon 2009 Keynote
 

Semelhante a DjangoCon09: The Test Client

symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 

Semelhante a DjangoCon09: The Test Client (20)

UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for Magento
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
UA Testing with Selenium and PHPUnit - ZendCon 2013
UA Testing with Selenium and PHPUnit - ZendCon 2013UA Testing with Selenium and PHPUnit - ZendCon 2013
UA Testing with Selenium and PHPUnit - ZendCon 2013
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the process
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

DjangoCon09: The Test Client

  • 1. The Test Client Dr Russell Keith-Magee DjangoCon 2009
  • 2. What is it? • A way to build unit tests of the full stack • Acts “kinda-sorta” like a browser • Stateful • Default instance on django.test.TestCase • Can be instantiated outside test framework
  • 3. The test client isn’t • A live browser test framework • Selenium • Twill • Windmill
  • 4. Why is it different? • TestClient can’t do some things • No JavaScript • DOM validation or control • Can do some things that browsers can’t
  • 5. GET a page c = TestClient() c.get(‘/foo/’) c.get(‘/foo/’, data={‘bar’:3}) c.get(‘/foo/?bar=3’)
  • 6. Returns a response • response.status_code • response.content • response.cookies • response[‘Content-Disposition’]
  • 7. ... and a little more • response.template • The template(s) used used in rendering • response.context • The context objects used in rendering • response.context[‘foo’]
  • 8. ... and it maintains state • self.cookies • self.session
  • 9. Login/Logout c.login(username='foo', password='password') c.logout()
  • 10. POST a page c = TestClient() c.post(‘/foo/’) c.post(‘/foo/?bar=3’) c.post(‘/foo/’, data={‘bar’: 3}) c.get(‘/foo/?whiz=4’, data={‘bar’:3})
  • 12. A common gotcha r = self.client.get(‘/foo’) self.assertEquals(r.status_code, 200) FAIL Assertion Error: 301 != 200
  • 13. The fix r = self.client.get(‘/foo’, follow=True) self.assertEquals(r.status_code, 200) response.redirect_chain ➡ links visited before a non-redirect was found.
  • 14. Extra Headers c = TestClient(HTTP_HOST=‘foo.com’) c.get(‘/foo/’, HTTP_HOST=‘foo.com’) response['X-DJANGO-TEST']
  • 15. Files c = TestClient() f = open(‘mydata.txt’) c.post(‘/foo/’, content_type=MULTIPART_CONTENT data = {‘file’: f}) f.close()
  • 16. Assertions • assertContains() • assertNotContains() • assertFormError() • assertTemplateUsed() • assertTemplateNotUsed() • assertRedirects()
  • 17. Advice • Don’t rely on assertContains • Assertions on template content are weak • Test at the source • Is the context right? • Are the forms correct? • Django’s templates make this possible!
  • 18. When to use TestClient • When you need to test the full stack • interaction of view and middleware • Great for testing idempotency
  • 19. Interesting hack • Use Client as a factory for Request objects • Ticket #9002, Snippet #963 • Then: • Construct a request object • Use to test a single view/middleware call
  • 20. Fin