SlideShare a Scribd company logo
Unit testing

 For those seeking instant
       gratification
Maciej Bliziński <blizinski@google.com>
       Python Ireland 2010-11-10
Helps the design
Provides live documentation
Helps refactoring
But I'm hungry right now!
I love to see my code run
Python Ireland Nov 2010 Talk: Unit Testing
task: Index a list of dictionaries by one of the fields

def IndexBy(d_list, field_name):
 result = {}
 for d in d_list:
  result[d[field_name]] = d
 return result
def MakePackageNameBySoname(soname):                                          (continued...)
 """Find the package name based on the soname.
                                                                               for key in parsed:
 Returns a pair of pkgname, catalogname.                                         if parsed[key]:
 """                                                                               keywords_pkgname[key] = SonameToStringWithChar(parsed[key], "-")
 def AddSeparator(d, sep):                                                         keywords_catalogname[key] = SonameToStringWithChar(parsed[key], "_")
   """Adds a separator based on the neighboring                                  else:
   of two digits."""                                                               keywords_pkgname[key] = ""
   dc = copy.copy(d)                                                               keywords_catalogname[key] = ""
   if dc["version"]:                                                           pkgname_list = []
     if (dc["basename"][-1].isdigit()                                          keywords_pkgname = AddSeparator(keywords_pkgname, "-")
        and                                                                    pkgname_list.append(
        dc["version"][0].isdigit()):                                               "CSW%(basename)s%(sep)s%(version)s" % keywords_pkgname)
       dc["sep"] = sep                                                         keywords_catalogname = AddSeparator(keywords_catalogname, "_")
     else:                                                                     catalogname_list = [
       dc["sep"] = ""                                                              "%(basename)s%(sep)s%(version)s" % keywords_catalogname,
   else:                                                                       ]
     dc["sep"] = ""                                                            return pkgname_list, catalogname_list
   return dc
 soname_re = re.compile(r"(?P<basename>[w+]+([.-]+[w+]+)*)"
                  r".so"
                  r"(.(?P<version>[d.]+))?"
                  r"$")
 m = soname_re.match(soname)
 if not m:
   # There was no ".so" component, so it's hardo to figure out which one is
   # the name, but we'll try to figure out the numeric part of the soname.
   digits = "".join(re.findall(r"[0-9]+", soname))
   alnum = "".join(re.findall(r"[a-zA-Z]+", soname))
   parsed = {
       "basename": alnum,
       "version": digits,
   }
 else:
   parsed = m.groupdict()
 keywords_pkgname = {}
 keywords_catalogname = {}




                                                                                                           Real life example
task: Index a list of dictionaries by one of the fields

def IndexBy(d_list, field_name):
 result = {}
 for d in d_list:
  result[d[field_name]] = d
 return result
import example_1

def main():
 d = [{"foo": "a", "bar": "b"},
    {"foo": "c", "bar": "d"}]
 print example_1.IndexBy(d, "foo")

if __name__ == '__main__':
  main()
import unittest
import example_1
import pprint

class IndexByUnitTest(unittest.TestCase):

 def testTwoElements(self):
  d = [{"foo": "a", "bar": "b"},
      {"foo": "c", "bar": "d"}]
  pprint.pprint(example_1.IndexBy(d, "foo"))

if __name__ == '__main__':
  unittest.main()
import unittest
import example_1


class IndexByUnitTest(unittest.TestCase):

 def testTwoElements(self):
  d = [{"foo": "a", "bar": "b"},
      {"foo": "c", "bar": "d"}]
  expected = {
     'a': {'foo': 'a', 'bar': 'b'},
     'c': {'foo': 'c', 'bar': 'd'},
  }
  self.assertEquals(expected, example_1.IndexBy(d, "foo"))

if __name__ == '__main__':
  unittest.main()
blizinski@workstation ~/unit-test-talk $ python2.6 example_1_test.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Cultured way of playing with code
Changing your code
import unittest
import example_1


class IndexByUnitTest(unittest.TestCase):

 def testTwoElements(self):
  d = [{"foo": "a", "bar": "b"},
      {"foo": "c", "bar": "d"},
      {"foo": "c", "bar": "e"}]
  expected = {
     'a': {'foo': 'a', 'bar': 'b'},
     'c': {'foo': 'c', 'bar': 'd'},
  }
  self.assertEquals(expected, example_1.IndexBy(d, "foo"))

if __name__ == '__main__':
  unittest.main()
Python Ireland Nov 2010 Talk: Unit Testing
task: Index a list of dictionaries by one of the fields

def IndexBy(d_list, field_name):
 result = {}
 for d in d_list:
  result.setdefault(d[field_name], [])
  result[d[field_name]].append(d)
 return result
Keeping a track record
def testMakePackageNameDashesNoDashes(self):
 soname = "libpyglib-2.0-python.so.0"
 expected = (
   ['CSWlibpyglib2-0python0'],
   ['libpyglib2_0python0'],
 )
 self.assertEqual(expected,
            su.MakePackageNameBySoname(soname))

def testMakePackageNameDashesNoDashesPython(self):
 soname = "libpython3.1.so.1.0"
 expected = (
   ['CSWlibpython3-1-1-0'],
   ['libpython3_1_1_0'],
 )
 self.assertEqual(expected,
            su.MakePackageNameBySoname(soname))
The trust issue

Your first steps in unit testing
Hug me, I only look alien!
    (never mind my boxing gloves)
Python Ireland Nov 2010 Talk: Unit Testing
It's about the way
  pieces of code
    fit together
Your trust will gradually shift
Part of the development process
It's a tool which helps with
some of the everyday tasks.
Further reading

  http://en.wikipedia.org/wiki/Unit_testing
  http://diveintopython.org/unit_testing/index.html
  Mock objects, stubs and fakes


Contact
         Maciej Bliziński <blizinski@google.com>
References

Images:

      http://commons.wikimedia.org/wiki/File:Pantheon_rome_inside_1-muniu.jpg by Muniu
      http://commons.wikimedia.org/wiki/File:Instant_miso_soup.jpg by Gleam
      http://www.flickr.com/photos/f-oxymoron/4203860207/sizes/l/in/photostream/ by f-oxymoron
      http://www.flickr.com/photos/jurvetson/1381322008/sizes/l/in/photostream/ by jurvetson
      http://www.flickr.com/photos/7332902@N05/3221210836/ by David O'Driscoll
      http://www.flickr.com/photos/edsweeney/4212380812/sizes/o/in/photostream/ by Ed Sweeney
http://www.flickr.com/photos/jenny-pics/3230153121/sizes/l/in/photostream/ by jenny downing
      http://www.flickr.com/photos/oskay/265899766/ by Windell Oskay
      http://www.flickr.com/photos/alismith44/357361903/ by Ali West
      http://www.flickr.com/photos/cezaryborysiuk/3947857278/ by Cezary Borysiuk
      http://www.flickr.com/photos/wilhei/109403331/ by wilhei55
      http://www.flickr.com/photos/antonymayfield/3221876089/ by antony_mayfield
      http://www.flickr.com/photos/ralphandjenny/4999895776/ by Ralph Daily

More Related Content

PPTX
Topological indices (t is) of the graphs to seek qsar models of proteins com...
PDF
R57shell
PDF
Building Real Time Systems on MongoDB Using the Oplog at Stripe
PDF
PHP tips and tricks
PDF
Aggregation Pipeline Power++: MongoDB 4.2 파이프 라인 쿼리, 업데이트 및 구체화된 뷰 소개 [MongoDB]
PDF
Command Bus To Awesome Town
PDF
Things I Believe Now That I'm Old
PPT
An Elephant of a Different Colour: Hack
Topological indices (t is) of the graphs to seek qsar models of proteins com...
R57shell
Building Real Time Systems on MongoDB Using the Oplog at Stripe
PHP tips and tricks
Aggregation Pipeline Power++: MongoDB 4.2 파이프 라인 쿼리, 업데이트 및 구체화된 뷰 소개 [MongoDB]
Command Bus To Awesome Town
Things I Believe Now That I'm Old
An Elephant of a Different Colour: Hack

What's hot (20)

PDF
はじめてのGroovy
TXT
Gta v savegame
PDF
Agile database access with CakePHP 3
PDF
Perforce Object and Record Model
PDF
PHP 7 – What changed internally? (Forum PHP 2015)
PDF
Everything About PowerShell
KEY
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
PDF
Internationalizing CakePHP Applications
PDF
PHP 7 – What changed internally?
KEY
Jython: Python para la plataforma Java (EL2009)
KEY
Jython: Python para la plataforma Java (JRSL 09)
KEY
Php 101: PDO
PDF
Future of HTTP in CakePHP
PPTX
Presentation1
PPTX
PHP performance 101: so you need to use a database
PDF
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
PPTX
Database performance 101
PDF
Perl Bag of Tricks - Baltimore Perl mongers
PDF
Teaching Your Machine To Find Fraudsters
はじめてのGroovy
Gta v savegame
Agile database access with CakePHP 3
Perforce Object and Record Model
PHP 7 – What changed internally? (Forum PHP 2015)
Everything About PowerShell
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Internationalizing CakePHP Applications
PHP 7 – What changed internally?
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (JRSL 09)
Php 101: PDO
Future of HTTP in CakePHP
Presentation1
PHP performance 101: so you need to use a database
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Database performance 101
Perl Bag of Tricks - Baltimore Perl mongers
Teaching Your Machine To Find Fraudsters
Ad

Viewers also liked (14)

PDF
Softwarequalitätssicherung mit Continuous Integration Tools
PPTX
Unit Testing with Python
PDF
Mock testing mit Python
PDF
Python testing using mock and pytest
PDF
TDD in Python With Pytest
PDF
Python-nose: A unittest-based testing framework for Python that makes writing...
PDF
Python Unit Test
PPTX
Python in Test automation
PDF
Py.test
PDF
Test Driven Development With Python
PPTX
Automated Python Test Frameworks for Hardware Verification and Validation
PPT
Automated hardware testing using python
PDF
Effective python
PPTX
unittest in 5 minutes
Softwarequalitätssicherung mit Continuous Integration Tools
Unit Testing with Python
Mock testing mit Python
Python testing using mock and pytest
TDD in Python With Pytest
Python-nose: A unittest-based testing framework for Python that makes writing...
Python Unit Test
Python in Test automation
Py.test
Test Driven Development With Python
Automated Python Test Frameworks for Hardware Verification and Validation
Automated hardware testing using python
Effective python
unittest in 5 minutes
Ad

Similar to Python Ireland Nov 2010 Talk: Unit Testing (7)

PPTX
PDF
Python 2.5 reference card (2009)
PPTX
Clonewise - Automatically Detecting Package Clones and Inferring Security Vu...
ODP
(1) c sharp introduction_basics_dot_net
ODP
(2) c sharp introduction_basics_part_i
PDF
IT Data Visualization - Sumit 2008
PPTX
Ropython-windbg-python-extensions
Python 2.5 reference card (2009)
Clonewise - Automatically Detecting Package Clones and Inferring Security Vu...
(1) c sharp introduction_basics_dot_net
(2) c sharp introduction_basics_part_i
IT Data Visualization - Sumit 2008
Ropython-windbg-python-extensions

More from Python Ireland (20)

PDF
Async I/O in Python
PDF
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
PDF
Python Ireland - Who, how, what
PPT
Object Orientation vs. Functional Programming in Python
PDF
What's the Scoop with Python 3?
PDF
Google App Engine in 40 minutes (the absolute essentials)
PDF
Introduction to Erlang for Python Programmers
PPT
Web-service based Mobile Geospatial Application Development using Python
PDF
Utopia Kingdoms scaling case. From 4 users to 50.000+
PPT
The Larch - a visual interactive programming environment
PDF
Python vs JLizard.... a python logging experience
PDF
Vim and Python
PDF
Python Ireland Nov 2009 Talk - Appengine
ODP
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
PDF
Python Ireland Nov 2010 - RESTing with Django
ODP
Python Ireland Feb '11 Talks: Introduction to Python
PPTX
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
PDF
KEY
Python for cloud computing
ODP
IPython: The awesome python shell
Async I/O in Python
Python Ireland 2012 - Message brokers and Python by Fernando Ciciliati
Python Ireland - Who, how, what
Object Orientation vs. Functional Programming in Python
What's the Scoop with Python 3?
Google App Engine in 40 minutes (the absolute essentials)
Introduction to Erlang for Python Programmers
Web-service based Mobile Geospatial Application Development using Python
Utopia Kingdoms scaling case. From 4 users to 50.000+
The Larch - a visual interactive programming environment
Python vs JLizard.... a python logging experience
Vim and Python
Python Ireland Nov 2009 Talk - Appengine
Python Ireland May 2011 - What is Pyramid and where is it with respect to Dja...
Python Ireland Nov 2010 - RESTing with Django
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland Dec Talks - Windows Azure -- The Nuts and Bolts
Python for cloud computing
IPython: The awesome python shell

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation theory and applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Unlocking AI with Model Context Protocol (MCP)
Reach Out and Touch Someone: Haptics and Empathic Computing
Per capita expenditure prediction using model stacking based on satellite ima...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MYSQL Presentation for SQL database connectivity
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Network Security Unit 5.pdf for BCA BBA.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
sap open course for s4hana steps from ECC to s4
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
“AI and Expert System Decision Support & Business Intelligence Systems”
The Rise and Fall of 3GPP – Time for a Sabbatical?
20250228 LYD VKU AI Blended-Learning.pptx

Python Ireland Nov 2010 Talk: Unit Testing

  • 1. Unit testing For those seeking instant gratification Maciej Bliziński <blizinski@google.com> Python Ireland 2010-11-10
  • 2. Helps the design Provides live documentation Helps refactoring
  • 3. But I'm hungry right now!
  • 4. I love to see my code run
  • 6. task: Index a list of dictionaries by one of the fields def IndexBy(d_list, field_name): result = {} for d in d_list: result[d[field_name]] = d return result
  • 7. def MakePackageNameBySoname(soname): (continued...) """Find the package name based on the soname. for key in parsed: Returns a pair of pkgname, catalogname. if parsed[key]: """ keywords_pkgname[key] = SonameToStringWithChar(parsed[key], "-") def AddSeparator(d, sep): keywords_catalogname[key] = SonameToStringWithChar(parsed[key], "_") """Adds a separator based on the neighboring else: of two digits.""" keywords_pkgname[key] = "" dc = copy.copy(d) keywords_catalogname[key] = "" if dc["version"]: pkgname_list = [] if (dc["basename"][-1].isdigit() keywords_pkgname = AddSeparator(keywords_pkgname, "-") and pkgname_list.append( dc["version"][0].isdigit()): "CSW%(basename)s%(sep)s%(version)s" % keywords_pkgname) dc["sep"] = sep keywords_catalogname = AddSeparator(keywords_catalogname, "_") else: catalogname_list = [ dc["sep"] = "" "%(basename)s%(sep)s%(version)s" % keywords_catalogname, else: ] dc["sep"] = "" return pkgname_list, catalogname_list return dc soname_re = re.compile(r"(?P<basename>[w+]+([.-]+[w+]+)*)" r".so" r"(.(?P<version>[d.]+))?" r"$") m = soname_re.match(soname) if not m: # There was no ".so" component, so it's hardo to figure out which one is # the name, but we'll try to figure out the numeric part of the soname. digits = "".join(re.findall(r"[0-9]+", soname)) alnum = "".join(re.findall(r"[a-zA-Z]+", soname)) parsed = { "basename": alnum, "version": digits, } else: parsed = m.groupdict() keywords_pkgname = {} keywords_catalogname = {} Real life example
  • 8. task: Index a list of dictionaries by one of the fields def IndexBy(d_list, field_name): result = {} for d in d_list: result[d[field_name]] = d return result
  • 9. import example_1 def main(): d = [{"foo": "a", "bar": "b"}, {"foo": "c", "bar": "d"}] print example_1.IndexBy(d, "foo") if __name__ == '__main__': main()
  • 10. import unittest import example_1 import pprint class IndexByUnitTest(unittest.TestCase): def testTwoElements(self): d = [{"foo": "a", "bar": "b"}, {"foo": "c", "bar": "d"}] pprint.pprint(example_1.IndexBy(d, "foo")) if __name__ == '__main__': unittest.main()
  • 11. import unittest import example_1 class IndexByUnitTest(unittest.TestCase): def testTwoElements(self): d = [{"foo": "a", "bar": "b"}, {"foo": "c", "bar": "d"}] expected = { 'a': {'foo': 'a', 'bar': 'b'}, 'c': {'foo': 'c', 'bar': 'd'}, } self.assertEquals(expected, example_1.IndexBy(d, "foo")) if __name__ == '__main__': unittest.main()
  • 12. blizinski@workstation ~/unit-test-talk $ python2.6 example_1_test.py . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
  • 13. Cultured way of playing with code
  • 15. import unittest import example_1 class IndexByUnitTest(unittest.TestCase): def testTwoElements(self): d = [{"foo": "a", "bar": "b"}, {"foo": "c", "bar": "d"}, {"foo": "c", "bar": "e"}] expected = { 'a': {'foo': 'a', 'bar': 'b'}, 'c': {'foo': 'c', 'bar': 'd'}, } self.assertEquals(expected, example_1.IndexBy(d, "foo")) if __name__ == '__main__': unittest.main()
  • 17. task: Index a list of dictionaries by one of the fields def IndexBy(d_list, field_name): result = {} for d in d_list: result.setdefault(d[field_name], []) result[d[field_name]].append(d) return result
  • 18. Keeping a track record
  • 19. def testMakePackageNameDashesNoDashes(self): soname = "libpyglib-2.0-python.so.0" expected = ( ['CSWlibpyglib2-0python0'], ['libpyglib2_0python0'], ) self.assertEqual(expected, su.MakePackageNameBySoname(soname)) def testMakePackageNameDashesNoDashesPython(self): soname = "libpython3.1.so.1.0" expected = ( ['CSWlibpython3-1-1-0'], ['libpython3_1_1_0'], ) self.assertEqual(expected, su.MakePackageNameBySoname(soname))
  • 20. The trust issue Your first steps in unit testing
  • 21. Hug me, I only look alien! (never mind my boxing gloves)
  • 23. It's about the way pieces of code fit together
  • 24. Your trust will gradually shift
  • 25. Part of the development process
  • 26. It's a tool which helps with some of the everyday tasks.
  • 27. Further reading http://en.wikipedia.org/wiki/Unit_testing http://diveintopython.org/unit_testing/index.html Mock objects, stubs and fakes Contact Maciej Bliziński <blizinski@google.com>
  • 28. References Images: http://commons.wikimedia.org/wiki/File:Pantheon_rome_inside_1-muniu.jpg by Muniu http://commons.wikimedia.org/wiki/File:Instant_miso_soup.jpg by Gleam http://www.flickr.com/photos/f-oxymoron/4203860207/sizes/l/in/photostream/ by f-oxymoron http://www.flickr.com/photos/jurvetson/1381322008/sizes/l/in/photostream/ by jurvetson http://www.flickr.com/photos/7332902@N05/3221210836/ by David O'Driscoll http://www.flickr.com/photos/edsweeney/4212380812/sizes/o/in/photostream/ by Ed Sweeney http://www.flickr.com/photos/jenny-pics/3230153121/sizes/l/in/photostream/ by jenny downing http://www.flickr.com/photos/oskay/265899766/ by Windell Oskay http://www.flickr.com/photos/alismith44/357361903/ by Ali West http://www.flickr.com/photos/cezaryborysiuk/3947857278/ by Cezary Borysiuk http://www.flickr.com/photos/wilhei/109403331/ by wilhei55 http://www.flickr.com/photos/antonymayfield/3221876089/ by antony_mayfield http://www.flickr.com/photos/ralphandjenny/4999895776/ by Ralph Daily