SlideShare ist ein Scribd-Unternehmen logo
1 von 10
Downloaden Sie, um offline zu lesen
Testing in Hard to Reach Places




            Lee Begg
           Begg Digital
Overview
●   Goals
●   The module
●   Refactoring
●   SqlAlchemy tricks
●   Mocking hard things


      Code: http://github.com/llnz/kiwipycon2011testing
      Slides: http://www.beggdigital.com/media/kiwipycon2011testing.pdf
Goals
●   Make sure it works properly
    ●   All the time
    ●   In all conditions
●   Unit testing to check
    ●   Cover 100%
    ●   Might still miss cases
Example module
  def main():
    '''Check the tripwire, email if the latest values have an RMS value over 2'''

    session = model.Session()
    values = session.query(model.MeasuredValue).order_by(model.MeasuredValue.desc()).limit(20).all()

    totalsq = 0
    for value in values:
        totalsq += value.value**2
    rms = math.sqrt(totalsq)
    if rms > 2:
        body = """Database trip wire has been tripped

RMS value was: %s
"""

    subject = "Tripwire report %s" % datetime.date.today()

    msg = MIMEText(body)
    msg['Subject'] = '[DBTW] %s' % subject
    msg['To'] = ','.join(settings.TO_ADDRESSES)
    msg['From'] = settings.FROM_ADDRESS

    server = smtplib.SMTP('localhost')
    result = server.sendmail(settings.FROM_ADDRESS, settings.TO_ADDRESSES, msg.as_string())
    if len(result) != 0:
        print "sendmail failures: %s" % result
    server.quit()
Refactoring
●   Refactor out components to test
class RMSTest(unittest.TestCase):
   '''Test the RMS calculations'''

    def testRMSCalc(self):                   def calcRMS(values):
      testvalues = [                           totalsq = 0.0
               ([0], 0),                       for value in values:
               ([1], 1),                          totalsq += value**2
               ([2], 2),
               ([0, 0], 0),                    rms = math.sqrt(totalsq/len(values))
               ([1, 1], 1),                    return rms
               ([0] * 20, 0),
               ([1] * 20, 1),
               ([0, 0, 0, 1], 0.5),
               ([3, 1, 3, 0, 1], 2),
               ]

    for values, expected in testvalues:
       result = tripwire.calcRMS(values)
       self.assertAlmostEqual(result, expected, msg='rmsCalc(%s) gave %s,
expected %s' % (values, result, expected))
SqlAlchemy Tricks
●   Change the database in the unittest setUp
    method
●   Done internally by Django


#override database setting
from dbtripwire import settings
settings.DATABASE_URL = 'sqlite:///:memory:'


from dbtripwire.model import initDatabase, dropDatabase
SqlAlchemy Tricks
class DatabaseTestSetup(object):
   '''Create the database in the setUp, and drop it in tearDown

  Used to abstract this away from all the unittests that use the Database.

  Must be the first class inherited from, or TestCase will override these
  methods, not the other way around.
  '''

  def setUp(self):
    '''Initialise the database with the tables'''
    initDatabase()


  def tearDown(self):
    '''Drop the tables'''
    dropDatabase()
SqlAlchemy Tricks
class ModelTest(DatabaseTestSetup, unittest.TestCase):
   '''Test the model classes'''

  def testMeasuredValueTable(self):
    '''MeasuredValue table test'''

    session = model.Session()

    self.assertEqual(session.query(model.MeasuredValue).count(), 0)

    mv = model.MeasuredValue(5)
    self.assert_(mv)

    session.add(mv)
    session.commit()

    self.assertEqual(session.query(model.MeasuredValue).count(), 1)

    mv1 = session.query(model.MeasuredValue).one()
    self.assertEqual(mv1.id, 1)
    self.assertEqual(mv1.value, 5)
    #don't forget to test the __repr__ string
    self.assertEqual(repr(mv1), "<MeasuredValue(1, 5)>")

    session.delete(mv1)

    session.commit()

    self.assertEqual(session.query(model.MeasuredValue).count(), 0)
Mock
●   Creating fake “mock” objects/classes/modules
●   Replace things you couldn't normally control
●   A few frameworks available
●   Very useful in replacing network connections
    ●   Httplib for example
    ●   Smtplib for another
Mock example
class SendEmailTest(unittest.TestCase):
   '''Test sending email'''

  def testSendEmail(self):
    tt = minimock.TraceTracker()
    smtpconn = minimock.Mock('smtplib.SMTP', tracker=tt)
    minimock.mock('smtplib.SMTP', mock_obj=smtpconn)
    smtpconn.mock_returns = smtpconn
    smtpconn.sendmail.mock_returns = {}

       tripwire.sendEmail(2.5, datetime.date(2011, 8, 16))
       expected = r"""Called smtplib.SMTP('localhost')
Called smtplib.SMTP.sendmail(
   'lee@beggdigital.co.nz',
   ['lee@beggdigital.co.nz', 'llnz@paradise.net.nz'],
   'Content-Type: text/plain; charset="us-ascii"nMIME-Version: 1.0nContent-Transfer-Encoding:
7bitnSubject: [DBTW] Tripwire Report 2011-08-16nTo: lee@beggdigital.co.nz,
llnz@paradise.net.nznFrom: lee@beggdigital.co.nznnDatabase trip wire has been tripped.nnRMS
value was: 2.5n')
Called smtplib.SMTP.quit()"""
       self.assertTrue(tt.check(expected), tt.diff(expected))

    minimock.restore()

Weitere Àhnliche Inhalte

Was ist angesagt?

ExercĂ­cios Netbeans - Vera Cymbron
ExercĂ­cios Netbeans - Vera CymbronExercĂ­cios Netbeans - Vera Cymbron
ExercĂ­cios Netbeans - Vera Cymbroncymbron
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to HooksSoluto
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hypeMagdiel Duarte
 
생산적읞 개발을 위한 지속적읞 테슀튞
생산적읞 개발을 위한 지속적읞 테슀튞생산적읞 개발을 위한 지속적읞 테슀튞
생산적읞 개발을 위한 지속적읞 í…ŒìŠ€íŠžêž°ëŁĄ 낹
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio MartĂ­n
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Rx java2 - Should I use it?
Rx java2 - Should I use it?Rx java2 - Should I use it?
Rx java2 - Should I use it?Kamil Kucharski
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
Dynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeDynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeMagnify Analytic Solutions
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
Testing Hadoop jobs with MRUnit
Testing Hadoop jobs with MRUnitTesting Hadoop jobs with MRUnit
Testing Hadoop jobs with MRUnitEric Wendelin
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinDmitry Pranchuk
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Ignacio MartĂ­n
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptLoĂŻc Knuchel
 
Powering code reuse with context and render props
Powering code reuse with context and render propsPowering code reuse with context and render props
Powering code reuse with context and render propsForbes Lindesay
 

Was ist angesagt? (20)

Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
ExercĂ­cios Netbeans - Vera Cymbron
ExercĂ­cios Netbeans - Vera CymbronExercĂ­cios Netbeans - Vera Cymbron
ExercĂ­cios Netbeans - Vera Cymbron
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
 
생산적읞 개발을 위한 지속적읞 테슀튞
생산적읞 개발을 위한 지속적읞 테슀튞생산적읞 개발을 위한 지속적읞 테슀튞
생산적읞 개발을 위한 지속적읞 테슀튞
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Rx java2 - Should I use it?
Rx java2 - Should I use it?Rx java2 - Should I use it?
Rx java2 - Should I use it?
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Dynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using TimeDynamically Evolving Systems: Cluster Analysis Using Time
Dynamically Evolving Systems: Cluster Analysis Using Time
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Testing Hadoop jobs with MRUnit
Testing Hadoop jobs with MRUnitTesting Hadoop jobs with MRUnit
Testing Hadoop jobs with MRUnit
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on Kotlin
 
Django
Django Django
Django
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
I os 06
I os 06I os 06
I os 06
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
 
Powering code reuse with context and render props
Powering code reuse with context and render propsPowering code reuse with context and render props
Powering code reuse with context and render props
 

Ähnlich wie Testing in those hard to reach places

Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectAssignmentpedia
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectAssignmentpedia
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorNeeraj Kaushik
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Cdiscount
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
Performance tests - it's a trap
Performance tests - it's a trapPerformance tests - it's a trap
Performance tests - it's a trapAndrzej Ludwikowski
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Yao Yao
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Data mining with caret package
Data mining with caret packageData mining with caret package
Data mining with caret packageVivian S. Zhang
 
é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......
é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......
é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......hugo lu
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 

Ähnlich wie Testing in those hard to reach places (20)

How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation Project
 
Distributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation ProjectDistributed Radar Tracking Simulation Project
Distributed Radar Tracking Simulation Project
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)Parallel R in snow (english after 2nd slide)
Parallel R in snow (english after 2nd slide)
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Performance tests - it's a trap
Performance tests - it's a trapPerformance tests - it's a trap
Performance tests - it's a trap
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
Mini-lab 1: Stochastic Gradient Descent classifier, Optimizing Logistic Regre...
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Data mining with caret package
Data mining with caret packageData mining with caret package
Data mining with caret package
 
é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......
é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......
é—œæ–ŒæžŹè©ŠïŒŒæˆ‘èȘȘçš„ć…¶ćŻŠæ˜Ż......
 
Celery
CeleryCelery
Celery
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 

Mehr von dn

Code quality; patch quality
Code quality; patch qualityCode quality; patch quality
Code quality; patch qualitydn
 
How does this code work?
How does this code work?How does this code work?
How does this code work?dn
 
Python worst practices
Python worst practicesPython worst practices
Python worst practicesdn
 
Struggling to find an open source business model
Struggling to find an open source business modelStruggling to find an open source business model
Struggling to find an open source business modeldn
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyonddn
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testingdn
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Spotlight on Python
Spotlight on PythonSpotlight on Python
Spotlight on Pythondn
 

Mehr von dn (8)

Code quality; patch quality
Code quality; patch qualityCode quality; patch quality
Code quality; patch quality
 
How does this code work?
How does this code work?How does this code work?
How does this code work?
 
Python worst practices
Python worst practicesPython worst practices
Python worst practices
 
Struggling to find an open source business model
Struggling to find an open source business modelStruggling to find an open source business model
Struggling to find an open source business model
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Spotlight on Python
Spotlight on PythonSpotlight on Python
Spotlight on Python
 

KĂŒrzlich hochgeladen

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Christopher Logan Kennedy
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vĂĄzquez
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 

KĂŒrzlich hochgeladen (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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
 
+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...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 

Testing in those hard to reach places

  • 1. Testing in Hard to Reach Places Lee Begg Begg Digital
  • 2. Overview ● Goals ● The module ● Refactoring ● SqlAlchemy tricks ● Mocking hard things Code: http://github.com/llnz/kiwipycon2011testing Slides: http://www.beggdigital.com/media/kiwipycon2011testing.pdf
  • 3. Goals ● Make sure it works properly ● All the time ● In all conditions ● Unit testing to check ● Cover 100% ● Might still miss cases
  • 4. Example module def main(): '''Check the tripwire, email if the latest values have an RMS value over 2''' session = model.Session() values = session.query(model.MeasuredValue).order_by(model.MeasuredValue.desc()).limit(20).all() totalsq = 0 for value in values: totalsq += value.value**2 rms = math.sqrt(totalsq) if rms > 2: body = """Database trip wire has been tripped RMS value was: %s """ subject = "Tripwire report %s" % datetime.date.today() msg = MIMEText(body) msg['Subject'] = '[DBTW] %s' % subject msg['To'] = ','.join(settings.TO_ADDRESSES) msg['From'] = settings.FROM_ADDRESS server = smtplib.SMTP('localhost') result = server.sendmail(settings.FROM_ADDRESS, settings.TO_ADDRESSES, msg.as_string()) if len(result) != 0: print "sendmail failures: %s" % result server.quit()
  • 5. Refactoring ● Refactor out components to test class RMSTest(unittest.TestCase): '''Test the RMS calculations''' def testRMSCalc(self): def calcRMS(values): testvalues = [ totalsq = 0.0 ([0], 0), for value in values: ([1], 1), totalsq += value**2 ([2], 2), ([0, 0], 0), rms = math.sqrt(totalsq/len(values)) ([1, 1], 1), return rms ([0] * 20, 0), ([1] * 20, 1), ([0, 0, 0, 1], 0.5), ([3, 1, 3, 0, 1], 2), ] for values, expected in testvalues: result = tripwire.calcRMS(values) self.assertAlmostEqual(result, expected, msg='rmsCalc(%s) gave %s, expected %s' % (values, result, expected))
  • 6. SqlAlchemy Tricks ● Change the database in the unittest setUp method ● Done internally by Django #override database setting from dbtripwire import settings settings.DATABASE_URL = 'sqlite:///:memory:' from dbtripwire.model import initDatabase, dropDatabase
  • 7. SqlAlchemy Tricks class DatabaseTestSetup(object): '''Create the database in the setUp, and drop it in tearDown Used to abstract this away from all the unittests that use the Database. Must be the first class inherited from, or TestCase will override these methods, not the other way around. ''' def setUp(self): '''Initialise the database with the tables''' initDatabase() def tearDown(self): '''Drop the tables''' dropDatabase()
  • 8. SqlAlchemy Tricks class ModelTest(DatabaseTestSetup, unittest.TestCase): '''Test the model classes''' def testMeasuredValueTable(self): '''MeasuredValue table test''' session = model.Session() self.assertEqual(session.query(model.MeasuredValue).count(), 0) mv = model.MeasuredValue(5) self.assert_(mv) session.add(mv) session.commit() self.assertEqual(session.query(model.MeasuredValue).count(), 1) mv1 = session.query(model.MeasuredValue).one() self.assertEqual(mv1.id, 1) self.assertEqual(mv1.value, 5) #don't forget to test the __repr__ string self.assertEqual(repr(mv1), "<MeasuredValue(1, 5)>") session.delete(mv1) session.commit() self.assertEqual(session.query(model.MeasuredValue).count(), 0)
  • 9. Mock ● Creating fake “mock” objects/classes/modules ● Replace things you couldn't normally control ● A few frameworks available ● Very useful in replacing network connections ● Httplib for example ● Smtplib for another
  • 10. Mock example class SendEmailTest(unittest.TestCase): '''Test sending email''' def testSendEmail(self): tt = minimock.TraceTracker() smtpconn = minimock.Mock('smtplib.SMTP', tracker=tt) minimock.mock('smtplib.SMTP', mock_obj=smtpconn) smtpconn.mock_returns = smtpconn smtpconn.sendmail.mock_returns = {} tripwire.sendEmail(2.5, datetime.date(2011, 8, 16)) expected = r"""Called smtplib.SMTP('localhost') Called smtplib.SMTP.sendmail( 'lee@beggdigital.co.nz', ['lee@beggdigital.co.nz', 'llnz@paradise.net.nz'], 'Content-Type: text/plain; charset="us-ascii"nMIME-Version: 1.0nContent-Transfer-Encoding: 7bitnSubject: [DBTW] Tripwire Report 2011-08-16nTo: lee@beggdigital.co.nz, llnz@paradise.net.nznFrom: lee@beggdigital.co.nznnDatabase trip wire has been tripped.nnRMS value was: 2.5n') Called smtplib.SMTP.quit()""" self.assertTrue(tt.check(expected), tt.diff(expected)) minimock.restore()