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
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()
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)
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

What's hot

はじめてのGroovy
はじめてのGroovyはじめてのGroovy
はじめてのGroovy
Tsuyoshi Yamamoto
 
Gta v savegame
Gta v savegameGta v savegame
Gta v savegame
hozayfa999
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
Perforce
 
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)
Nikita Popov
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
Gaetano Causio
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
Pierre MARTIN
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?
Nikita Popov
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Jython: Python para la plataforma Java (JRSL 09)
Jython: Python para la plataforma Java (JRSL 09)Leonardo Soto
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
markstory
 
Presentation1
Presentation1Presentation1
Presentation1
Rahadyan Gusti
 
PHP performance 101: so you need to use a database
PHP performance 101: so you need to use a databasePHP performance 101: so you need to use a database
PHP performance 101: so you need to use a database
Leon Fayer
 
PHP 5.4
PHP 5.4PHP 5.4
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Suyeol Jeon
 
Database performance 101
Database performance 101Database performance 101
Database performance 101
Leon Fayer
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
brian d foy
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
Ian Barber
 

What's hot (20)

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

Viewers also liked

Softwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration ToolsSoftwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration Tools
GFU Cyrus AG
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
MicroPyramid .
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
Suraj Deshmukh
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
Eddy Reyes
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
Timo Stollenwerk
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
Python in Test automation
Python in Test automationPython in Test automation
Python in Test automation
Krishnana Sreeraman
 
Py.test
Py.testPy.test
Py.test
soasme
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
Siddhi
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and Validation
Barbara Jones
 
Automated hardware testing using python
Automated hardware testing using pythonAutomated hardware testing using python
Automated hardware testing using python
Yuvaraja Ravi
 
Effective python
Effective pythonEffective python
Effective python
Abhijeet Kasurde
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
Ray Toal
 

Viewers also liked (14)

Softwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration ToolsSoftwarequalitätssicherung mit Continuous Integration Tools
Softwarequalitätssicherung mit Continuous Integration Tools
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Mock testing mit Python
Mock testing mit PythonMock testing mit Python
Mock testing mit Python
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...Python-nose: A unittest-based testing framework for Python that makes writing...
Python-nose: A unittest-based testing framework for Python that makes writing...
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
Python in Test automation
Python in Test automationPython in Test automation
Python in Test automation
 
Py.test
Py.testPy.test
Py.test
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
Automated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and ValidationAutomated Python Test Frameworks for Hardware Verification and Validation
Automated Python Test Frameworks for Hardware Verification and Validation
 
Automated hardware testing using python
Automated hardware testing using pythonAutomated hardware testing using python
Automated hardware testing using python
 
Effective python
Effective pythonEffective python
Effective python
 
unittest in 5 minutes
unittest in 5 minutesunittest in 5 minutes
unittest in 5 minutes
 

Similar to Python Ireland Nov 2010 Talk: Unit Testing

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
Fwdays
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
python codes
python codespython codes
python codes
tusharpanda88
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
dreampuf
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
Mark
 
The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180
Mahmoud Samir Fayed
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
Leonardo Soto
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
UC San Diego
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
Murray Steele
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
DataMapper
DataMapperDataMapper
DataMapper
Yehuda Katz
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsMark Jaquith
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi
 
MongoDB
MongoDB MongoDB
Why ruby
Why rubyWhy ruby
Why ruby
rstankov
 
R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemMaithreya Chakravarthula
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
Rsquared Academy
 

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

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Five
FiveFive
Five
 
python codes
python codespython codes
python codes
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
DataMapper
DataMapperDataMapper
DataMapper
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress Plugins
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
MongoDB
MongoDB MongoDB
MongoDB
 
Why ruby
Why rubyWhy ruby
Why ruby
 
R (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support SystemR (Shiny Package) - Server Side Code for Decision Support System
R (Shiny Package) - Server Side Code for Decision Support System
 
R Programming: Export/Output Data In R
R Programming: Export/Output Data In RR Programming: Export/Output Data In R
R Programming: Export/Output Data In R
 

More from Python Ireland

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

More from Python Ireland (20)

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

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 

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
  • 5.
  • 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()
  • 16.
  • 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)
  • 22.
  • 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