SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

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
Masahiro Nagano
 
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
 

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

En vedette

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 Test
David Xie
 
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
 

En vedette (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
 

Similaire à Python Ireland Nov 2010 Talk: Unit Testing

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
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
 
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
 
Creating and Maintaining WordPress Plugins
Creating and Maintaining WordPress PluginsCreating and Maintaining WordPress Plugins
Creating and Maintaining WordPress Plugins
Mark Jaquith
 
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
Maithreya Chakravarthula
 

Similaire à 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
 

Plus de 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
 
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
 

Plus de 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
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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?
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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