SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Testing Django Applications




Honza Král


Follow me: @honzakral
E-mail me: honza.kral@gmail.com
Why Test?
You already do!
Whenever you
●   open your browser to look at the result
●   run some part of your code in a console
●   look into the database directly


Is it fun?
Be lazy!

Let the computer do the boring work.
Even if you are perfect
    programmers (which you are not)

Tests will make you fearless of:
●   deployment (will this work?)
●   refactoring (what will this break?)
●   new developers (can I trust them?)
●   regressions (didn't I fix this before?)


Why assume it's OK when you can test?
Terminology
●   Unit tests
●   Integration tests
●   Acceptance tests
●   Performance tests
●   Load tests
●   Stress tests
●   UX tests
●   .........
Unit tests
from unittest import TestCase

class TestInterview(TestCase):
  def setUp(self):
     self.interview = Interview( ... )

  def test_ask_indicators_when_active(self):
    self.assertEquals(
       True, self.interview.asking_started())
    self.assertEquals(
       False, self.interview.asking_ended())
    self.assertEquals(
       True, self.interview.can_ask())
Unit tests
●   No interaction with other components
    ●   Including DB
●   Fast
●   Tied to the code
●   Testing small portion of the code
Integration tests
from django.test import TestCase

class TestInterview(TestCase):
  def setUp(self):
     self.interview = Interview.objects.create(
       ...)

  def test_unanswered_questions(self):
    q = Question.objects.create(
         interview=self.interview,
         content='What ?')

    self.assertEquals(
      [q],
      self.interview.unanswered_questions())
Integration tests
●   Test how components cooperate together
●   Most common tests in Django apps
●   Usually slower and cover more code
●   Important to have
Testability
(unit) testability
●   avoid side effects
●   separate components
●   only accept parameters you need
    ●
        request is bad
●   be smart about transactions and models
●   don't put busines logic into views (use models)
Separate components (views)
def my_view(request, some_id, action, ...):
  main_model = get_object_or_404(M, pk=some_id)
  other = main_model.method(action)
  ...
  compute ... some ... data
  ...
  return render_to_response(...)
●   To test this you need to:
    ●   define the template
    ●   mock request or use test client
    ●   access the database
    ●   ...
Class-based views FTW!
class MyView(object):
  def get_objects(self, some_id, action):
     ...
  def render_response(self, context):
     ...
  def compute_data(self, m1, m2):
     ...
  def __call__(
     self, request, some_id, action, ...):
     m1, m2 = self.get_objects(some_id, action)
     context = self.compute_data(m1, m2)
     return self.render_response(context)
●   now you can easily test individual methods
●   or just the interesting ones (compute_data)
Separate components (template tags)
def test_parse_fails_on_too_few_arguments(self):
  self.assertRaises(
     TemplateSyntaxError, _parse_box,
     ['box', 'box_type', 'for'])

def test_parse_box_with_pk(self):
  node = _parse_box( ['box', 'box_type', 'for',
      'core.category', 'with', 'pk', '1'])

  self.assertTrue(isinstance(node, BoxNode))
  self.assertEquals('box_type', node.box_type)
  self.assertEquals(Category, node.model)
  self.assertEquals(('pk', '1'), node.lookup)
Testing templatetags
from unittest import TestCase

class TestRenderTag(TestCase):
  def setUp(self):
     self.template = template.Template(
     '{% load myapp %}{% render var %}')

  def test_does_not_escape_output(self):
    c = template.Context({'var': '<html> ""'})
    self.assertEquals(
       '<html> ""', self.template.render(c))
Testing models
Try to avoid DB

def test_taller_img_gets_cropped_to_ratio(self):
     format = Format(
       max_height=100, max_width=100)
     i = Image.new('RGB', (100, 200), "black")
     f = Formatter(i, format)

    i, crop_box = f.format()
    self.assertEquals(
      (0, 50, 100, 150), crop_box)
    self.assertEquals((100, 100), i.size)
Populating test DB
●   fixtures only work for static data
●   natural keys FTW!
●   use factories when fixtures aren't enough
def get_payment_assesment(stay, ** kwargs):
  defaults = {
     'modified_by':
User.objects.get_or_create(...),
     'stay': stay,
     ...}
  defaults.update(kwargs)
  return PaymentAssesment.objects.create(
       **defaults)
Testing forms
from unittest import TestCase

class TestPaymentAssesmentFormSet(TestCase):
  def setUp(self):
     self.data = {…}

  def test_formset_validates_valid_data(self):
    fset = PaymentAssesmentFormSet(self.data)
    self.assertTrue(fset.is_valid())

  def test_fail_for_change_inside_a_month(self):
    self.data['form-0-valid_to'] = '1.06.2009'
    self.data['form-1-valid_from'] = '2.06.2009'
    fset = PaymentAssesmentFormSet(self.data)
    self.assertFalse(fset.is_valid())
Tests alone are not enough!
Infrastructure
●   simple and convenient way to run tests
●   fast tests (or way to run just part of the suite)
●   never let your test suite break
●   continuous integration
    ●   reporting
    ●   leaving this to the experts
        (assuming they catch their flight)
Other requirements
●   when test fails you must know what went wrong
    ●   no doctests
    ●   descriptive test names
    ●   short tests touching minimal amount of code
●   write even trivial tests as a starting point
●   make sure tests work
Happy hour
If you have done your tests right, you will get
extras:
●   convenient way to bootstrap your application
●   no need for server/browser during development
●   calmer nerves
●   people will trust your work!
?
Thanks for listening




Honza Král


Follow me: @honzakral
E-mail me: honza.kral@gmail.com

Contenu connexe

Tendances

Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with JestMichał Pierzchała
 
Py.test
Py.testPy.test
Py.testsoasme
 
Scraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & SeleniumScraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & SeleniumRoger Barnes
 
Continuous Integration Testing in Django
Continuous Integration Testing in DjangoContinuous Integration Testing in Django
Continuous Integration Testing in DjangoKevin Harvey
 
Test driven development with react
Test driven development with reactTest driven development with react
Test driven development with reactLeon Bezuidenhout
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Pytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsPytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsAndreu Vallbona Plazas
 
Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Toru Furukawa
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Test Failed, Then...
Test Failed, Then...Test Failed, Then...
Test Failed, Then...Toru Furukawa
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanizecoreygoldberg
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your DatabaseDavid Wheeler
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo cleanHector Canto
 

Tendances (20)

Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
Py.test
Py.testPy.test
Py.test
 
Scraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & SeleniumScraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & Selenium
 
Django Deployment-in-AWS
Django Deployment-in-AWSDjango Deployment-in-AWS
Django Deployment-in-AWS
 
Continuous Integration Testing in Django
Continuous Integration Testing in DjangoContinuous Integration Testing in Django
Continuous Integration Testing in Django
 
Test driven development with react
Test driven development with reactTest driven development with react
Test driven development with react
 
Night Watch with QA
Night Watch with QANight Watch with QA
Night Watch with QA
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Pytest - testing tips and useful plugins
Pytest - testing tips and useful pluginsPytest - testing tips and useful plugins
Pytest - testing tips and useful plugins
 
Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Test Failed, Then...
Test Failed, Then...Test Failed, Then...
Test Failed, Then...
 
Testing Ansible
Testing AnsibleTesting Ansible
Testing Ansible
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 
Unit Test Your Database
Unit Test Your DatabaseUnit Test Your Database
Unit Test Your Database
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
Django Testing
Django TestingDjango Testing
Django Testing
 

En vedette

Propuesta del Plan Social presentada por el PSOE de Gijón
Propuesta del Plan Social presentada por el PSOE de GijónPropuesta del Plan Social presentada por el PSOE de Gijón
Propuesta del Plan Social presentada por el PSOE de Gijónpsoegijon
 
Asm memoria 2013_aaff (1)
Asm memoria 2013_aaff (1)Asm memoria 2013_aaff (1)
Asm memoria 2013_aaff (1)dimematrimonio
 

En vedette (8)

Propuesta del Plan Social presentada por el PSOE de Gijón
Propuesta del Plan Social presentada por el PSOE de GijónPropuesta del Plan Social presentada por el PSOE de Gijón
Propuesta del Plan Social presentada por el PSOE de Gijón
 
Asm memoria 2013_aaff (1)
Asm memoria 2013_aaff (1)Asm memoria 2013_aaff (1)
Asm memoria 2013_aaff (1)
 
Travis
TravisTravis
Travis
 
Descriptors
DescriptorsDescriptors
Descriptors
 
My Dearest Carmen
My Dearest CarmenMy Dearest Carmen
My Dearest Carmen
 
Jean school
Jean schoolJean school
Jean school
 
Sand and Sea
Sand and SeaSand and Sea
Sand and Sea
 
El paro en españa
El paro en españaEl paro en españa
El paro en españa
 

Similaire à Testing Django Applications

Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Howsatesgoral
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010Timo Stollenwerk
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
E2E testing con nightwatch.js  - Drupalcamp Spain 2018E2E testing con nightwatch.js  - Drupalcamp Spain 2018
E2E testing con nightwatch.js - Drupalcamp Spain 2018Salvador Molina (Slv_)
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETBen Hall
 
Automation test
Automation testAutomation test
Automation testyuyijq
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testingdn
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testingmalcolmt
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocksAyla Khan
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkPeter Kofler
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in nodeGoa App
 
Automated Testing in Django
Automated Testing in DjangoAutomated Testing in Django
Automated Testing in DjangoLoek van Gent
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic Peopledavismr
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 

Similaire à Testing Django Applications (20)

Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Plone testingdzug tagung2010
Plone testingdzug tagung2010Plone testingdzug tagung2010
Plone testingdzug tagung2010
 
E2E testing con nightwatch.js - Drupalcamp Spain 2018
E2E testing con nightwatch.js  - Drupalcamp Spain 2018E2E testing con nightwatch.js  - Drupalcamp Spain 2018
E2E testing con nightwatch.js - Drupalcamp Spain 2018
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
Automation test
Automation testAutomation test
Automation test
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testing
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocks
 
Unit testing
Unit testingUnit testing
Unit testing
 
Writing Tests with the Unity Test Framework
Writing Tests with the Unity Test FrameworkWriting Tests with the Unity Test Framework
Writing Tests with the Unity Test Framework
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in node
 
Automated Testing in Django
Automated Testing in DjangoAutomated Testing in Django
Automated Testing in Django
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 

Dernier

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 Scriptwesley chun
 
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...Neo4j
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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 RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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?Antenna Manufacturer Coco
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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 MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
[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.pdfhans926745
 
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 MenDelhi Call girls
 

Dernier (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
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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?
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[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
 
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
 

Testing Django Applications

  • 1. Testing Django Applications Honza Král Follow me: @honzakral E-mail me: honza.kral@gmail.com
  • 3. You already do! Whenever you ● open your browser to look at the result ● run some part of your code in a console ● look into the database directly Is it fun?
  • 4. Be lazy! Let the computer do the boring work.
  • 5. Even if you are perfect programmers (which you are not) Tests will make you fearless of: ● deployment (will this work?) ● refactoring (what will this break?) ● new developers (can I trust them?) ● regressions (didn't I fix this before?) Why assume it's OK when you can test?
  • 6. Terminology ● Unit tests ● Integration tests ● Acceptance tests ● Performance tests ● Load tests ● Stress tests ● UX tests ● .........
  • 7. Unit tests from unittest import TestCase class TestInterview(TestCase): def setUp(self): self.interview = Interview( ... ) def test_ask_indicators_when_active(self): self.assertEquals( True, self.interview.asking_started()) self.assertEquals( False, self.interview.asking_ended()) self.assertEquals( True, self.interview.can_ask())
  • 8. Unit tests ● No interaction with other components ● Including DB ● Fast ● Tied to the code ● Testing small portion of the code
  • 9. Integration tests from django.test import TestCase class TestInterview(TestCase): def setUp(self): self.interview = Interview.objects.create( ...) def test_unanswered_questions(self): q = Question.objects.create( interview=self.interview, content='What ?') self.assertEquals( [q], self.interview.unanswered_questions())
  • 10. Integration tests ● Test how components cooperate together ● Most common tests in Django apps ● Usually slower and cover more code ● Important to have
  • 12. (unit) testability ● avoid side effects ● separate components ● only accept parameters you need ● request is bad ● be smart about transactions and models ● don't put busines logic into views (use models)
  • 13. Separate components (views) def my_view(request, some_id, action, ...): main_model = get_object_or_404(M, pk=some_id) other = main_model.method(action) ... compute ... some ... data ... return render_to_response(...) ● To test this you need to: ● define the template ● mock request or use test client ● access the database ● ...
  • 14. Class-based views FTW! class MyView(object): def get_objects(self, some_id, action): ... def render_response(self, context): ... def compute_data(self, m1, m2): ... def __call__( self, request, some_id, action, ...): m1, m2 = self.get_objects(some_id, action) context = self.compute_data(m1, m2) return self.render_response(context) ● now you can easily test individual methods ● or just the interesting ones (compute_data)
  • 15. Separate components (template tags) def test_parse_fails_on_too_few_arguments(self): self.assertRaises( TemplateSyntaxError, _parse_box, ['box', 'box_type', 'for']) def test_parse_box_with_pk(self): node = _parse_box( ['box', 'box_type', 'for', 'core.category', 'with', 'pk', '1']) self.assertTrue(isinstance(node, BoxNode)) self.assertEquals('box_type', node.box_type) self.assertEquals(Category, node.model) self.assertEquals(('pk', '1'), node.lookup)
  • 16. Testing templatetags from unittest import TestCase class TestRenderTag(TestCase): def setUp(self): self.template = template.Template( '{% load myapp %}{% render var %}') def test_does_not_escape_output(self): c = template.Context({'var': '<html> ""'}) self.assertEquals( '<html> ""', self.template.render(c))
  • 17. Testing models Try to avoid DB def test_taller_img_gets_cropped_to_ratio(self): format = Format( max_height=100, max_width=100) i = Image.new('RGB', (100, 200), "black") f = Formatter(i, format) i, crop_box = f.format() self.assertEquals( (0, 50, 100, 150), crop_box) self.assertEquals((100, 100), i.size)
  • 18. Populating test DB ● fixtures only work for static data ● natural keys FTW! ● use factories when fixtures aren't enough def get_payment_assesment(stay, ** kwargs): defaults = { 'modified_by': User.objects.get_or_create(...), 'stay': stay, ...} defaults.update(kwargs) return PaymentAssesment.objects.create( **defaults)
  • 19. Testing forms from unittest import TestCase class TestPaymentAssesmentFormSet(TestCase): def setUp(self): self.data = {…} def test_formset_validates_valid_data(self): fset = PaymentAssesmentFormSet(self.data) self.assertTrue(fset.is_valid()) def test_fail_for_change_inside_a_month(self): self.data['form-0-valid_to'] = '1.06.2009' self.data['form-1-valid_from'] = '2.06.2009' fset = PaymentAssesmentFormSet(self.data) self.assertFalse(fset.is_valid())
  • 20. Tests alone are not enough!
  • 21. Infrastructure ● simple and convenient way to run tests ● fast tests (or way to run just part of the suite) ● never let your test suite break ● continuous integration ● reporting ● leaving this to the experts (assuming they catch their flight)
  • 22. Other requirements ● when test fails you must know what went wrong ● no doctests ● descriptive test names ● short tests touching minimal amount of code ● write even trivial tests as a starting point ● make sure tests work
  • 23. Happy hour If you have done your tests right, you will get extras: ● convenient way to bootstrap your application ● no need for server/browser during development ● calmer nerves ● people will trust your work!
  • 24. ?
  • 25. Thanks for listening Honza Král Follow me: @honzakral E-mail me: honza.kral@gmail.com