SlideShare a Scribd company logo
1 of 20
Download to read 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

More Related Content

What's hot (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
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
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
 

Recently uploaded (20)

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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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...
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

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