SlideShare a Scribd company logo
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

More Related Content

PPT
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
PDF
Making the most of your Test Suite
PDF
Deploying on the cutting edge
PDF
Token Testing Slides
PPTX
Mozilla Web QA - Evolution of our Python WebDriver framework
PDF
Towards Continuous Deployment with Django
PPTX
Django deployment best practices
PDF
Effective testing with pytest
Selenium with py test by Alexandr Vasyliev for Lohika Odessa Python TechTalks
Making the most of your Test Suite
Deploying on the cutting edge
Token Testing Slides
Mozilla Web QA - Evolution of our Python WebDriver framework
Towards Continuous Deployment with Django
Django deployment best practices
Effective testing with pytest

What's hot (20)

PDF
Painless JavaScript Testing with Jest
PDF
Py.test
PDF
Scraping recalcitrant web sites with Python & Selenium
PPTX
Django Deployment-in-AWS
PDF
Continuous Integration Testing in Django
PPTX
Test driven development with react
PDF
Night Watch with QA
PDF
Python testing using mock and pytest
PDF
Pytest - testing tips and useful plugins
PDF
Trying Continuous Delivery - pyconjp 2012
KEY
Agile JavaScript Testing
PPT
Beyond Unit Testing
ODT
Testing in-python-and-pytest-framework
PDF
Test Failed, Then...
PPTX
Testing Ansible
PDF
Modern Python Testing
PPT
Performance and Scalability Testing with Python and Multi-Mechanize
KEY
Unit Test Your Database
PDF
Keep your repo clean
PDF
Django Testing
Painless JavaScript Testing with Jest
Py.test
Scraping recalcitrant web sites with Python & Selenium
Django Deployment-in-AWS
Continuous Integration Testing in Django
Test driven development with react
Night Watch with QA
Python testing using mock and pytest
Pytest - testing tips and useful plugins
Trying Continuous Delivery - pyconjp 2012
Agile JavaScript Testing
Beyond Unit Testing
Testing in-python-and-pytest-framework
Test Failed, Then...
Testing Ansible
Modern Python Testing
Performance and Scalability Testing with Python and Multi-Mechanize
Unit Test Your Database
Keep your repo clean
Django Testing
Ad

Viewers also liked (8)

PDF
Propuesta del Plan Social presentada por el PSOE de Gijón
PDF
Asm memoria 2013_aaff (1)
ODP
Travis
ODP
Descriptors
PPT
My Dearest Carmen
PPTX
Jean school
DOCX
Sand and Sea
PPTX
El paro en españa
Propuesta del Plan Social presentada por el PSOE de Gijón
Asm memoria 2013_aaff (1)
Travis
Descriptors
My Dearest Carmen
Jean school
Sand and Sea
El paro en españa
Ad

Similar to Testing Django Applications (20)

PDF
Testing for Pragmatic People
ODP
Automated Testing in Django
PDF
Advanced Django
PPTX
Django strategy-test
PDF
Factories, mocks and spies: a tester's little helpers
PDF
DIY in 5 Minutes: Testing Django App with Pytest
PDF
The Future is Now: Writing Automated Tests To Grow Your Code
PPTX
Upstate CSCI 540 Unit testing
PPTX
10 ways to shoot yourself in the foot with tests - Shai Geva, PyConUS 2023
PDF
Some testing - Everything you should know about testing to go with @pedro_g_s...
PDF
DSR Testing (Part 1)
PDF
10 ways to shoot yourself in the foot with tests - Shai Geva, PyCon IL, 2024
PDF
Let's make this test suite run faster - Paris JUG 2011
PDF
Plone Testing Tools And Techniques
PPTX
A Beginer's Guide to testing in Django
PDF
Django
PDF
Let's make this test suite run faster! SoftShake 2010
PPT
Building Quality with Foundations of Mud
PDF
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
PDF
Testing untestable code - IPC12
Testing for Pragmatic People
Automated Testing in Django
Advanced Django
Django strategy-test
Factories, mocks and spies: a tester's little helpers
DIY in 5 Minutes: Testing Django App with Pytest
The Future is Now: Writing Automated Tests To Grow Your Code
Upstate CSCI 540 Unit testing
10 ways to shoot yourself in the foot with tests - Shai Geva, PyConUS 2023
Some testing - Everything you should know about testing to go with @pedro_g_s...
DSR Testing (Part 1)
10 ways to shoot yourself in the foot with tests - Shai Geva, PyCon IL, 2024
Let's make this test suite run faster - Paris JUG 2011
Plone Testing Tools And Techniques
A Beginer's Guide to testing in Django
Django
Let's make this test suite run faster! SoftShake 2010
Building Quality with Foundations of Mud
DjangoCon 2013 - How to Write Fast and Efficient Unit Tests in Django
Testing untestable code - IPC12

Recently uploaded (20)

PPTX
TLE Review Electricity (Electricity).pptx
PPTX
A Presentation on Touch Screen Technology
PDF
Hybrid model detection and classification of lung cancer
PPTX
A Presentation on Artificial Intelligence
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
August Patch Tuesday
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
project resource management chapter-09.pdf
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
DP Operators-handbook-extract for the Mautical Institute
PPTX
Chapter 5: Probability Theory and Statistics
TLE Review Electricity (Electricity).pptx
A Presentation on Touch Screen Technology
Hybrid model detection and classification of lung cancer
A Presentation on Artificial Intelligence
Univ-Connecticut-ChatGPT-Presentaion.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Approach and Philosophy of On baking technology
Encapsulation_ Review paper, used for researhc scholars
Heart disease approach using modified random forest and particle swarm optimi...
August Patch Tuesday
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Web App vs Mobile App What Should You Build First.pdf
Encapsulation theory and applications.pdf
Unlocking AI with Model Context Protocol (MCP)
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Group 1 Presentation -Planning and Decision Making .pptx
project resource management chapter-09.pdf
A novel scalable deep ensemble learning framework for big data classification...
DP Operators-handbook-extract for the Mautical Institute
Chapter 5: Probability Theory and Statistics

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