SlideShare una empresa de Scribd logo
1 de 10
Descargar para leer sin conexión
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()

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar a 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
 
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
 

Similar a 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
 

Más de 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
 

Más de 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
 

Último

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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 DevelopmentsTrustArc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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 WorkerThousandEyes
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 

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