SlideShare a Scribd company logo
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()

More Related Content

What's hot

Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
Christoffer Noring
 
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 Hooks
Soluto
 
React hooks beyond hype
React hooks beyond hypeReact hooks beyond hype
React hooks beyond hype
Magdiel Duarte
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트기룡 남
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
Ignacio 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 code
Dror 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 Time
Magnify Analytic Solutions
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
Sandeep Joshi
 
Testing Hadoop jobs with MRUnit
Testing Hadoop jobs with MRUnitTesting Hadoop jobs with MRUnit
Testing Hadoop jobs with MRUnit
Eric 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 Kotlin
Dmitry Pranchuk
 
Django
Django Django
Django
Toru Furukawa
 
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
Ignacio Martín
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
Loï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 props
Forbes Lindesay
 

What's hot (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 to Testing in those hard to reach places

How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
Rainer Schuettengruber
 
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 Tests
Tomek 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 code
Dror Helper
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
Adam Lowry
 
Celery with python
Celery with pythonCelery with python
Celery with python
Alexandre González Rodríguez
 
Performance tests - it's a trap
Performance tests - it's a trapPerformance tests - it's a trap
Performance tests - it's a trap
Andrzej Ludwikowski
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
Suraj Deshmukh
 
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 package
Vivian S. Zhang
 
關於測試,我說的其實是......
關於測試,我說的其實是......關於測試,我說的其實是......
關於測試,我說的其實是......
hugo lu
 
Celery
CeleryCelery
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
Haci Murat Yaman
 

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

More from dn

Code quality; patch quality
Code quality; patch qualityCode quality; patch quality
Code quality; patch quality
dn
 
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 practices
dn
 
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
dn
 
Automated testing in Python and beyond
Automated testing in Python and beyondAutomated testing in Python and beyond
Automated testing in Python and beyond
dn
 
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
dn
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Spotlight on Python
Spotlight on PythonSpotlight on Python
Spotlight on Python
dn
 

More from 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
 

Recently uploaded

Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

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