Capture-Replay Mocks Scandinavian Developer Conference 4 th April 2011 Geoff Bache.

Slides:



Advertisements
Similar presentations
Testing Relational Database
Advertisements

The map and reduce functions in MapReduce are easy to test in isolation, which is a consequence of their functional style. For known inputs, they produce.
Cosc 5/4765 Protecting against ssh attacks And is this secure?
Integration Testing When testing a module in isolation –Called modules need to be replaced –Tested module needs to be called A D ′ E ′ main driver module.
COEN 445 Communication Networks and Protocols Lab 4
Copyright 2004 Monash University IMS5401 Web-based Systems Development Topic 2: Elements of the Web (g) Interactivity.
Python Programming Chapter 1: The way of the program Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
LHCbPR V2 Sasha Mazurov, Amine Ben Hammou, Ben Couturier 5th LHCb Computing Workshop
Lesson 3 Remote Method Invocation (RMI) Mixing RMI and sockets Rethinking out tic-tac-toe game.
Introduction to Unix – CS 21 Lecture 5. Lecture Overview Lab Review Useful commands that will illustrate today’s lecture Streams of input and output File.
Mock Objects. What are Mock Objects  Any dummy object that stands in for a real object that is not available, or is difficult to use in a test case 
CVSQL 2 The Design. System Overview System Components CVSQL Server –Three network interfaces –Modular data source provider framework –Decoupled SQL parsing.
Games Development 2 Entity / Architecture Review CO3301 Week
Version Control with Subversion. What is Version Control Good For? Maintaining project/file history - so you don’t have to worry about it Managing collaboration.
Using a Simple Python Script to Download Data Rob Letzler Goldman School of Public Policy July 2005.
© Janice Regan, CMPT 128, Jan CMPT 128 Introduction to Computing Science for Engineering Students Creating a program.
Map Reduce: Simplified Data Processing On Large Clusters Jeffery Dean and Sanjay Ghemawat (Google Inc.) OSDI 2004 (Operating Systems Design and Implementation)
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Computing Science 1P Large Group Tutorial 17 Simon Gay Department of Computing Science University of Glasgow 2006/07.
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
Introduction to Python
Software Engineering 2003 Jyrki Nummenmaa 1 CASE Tools CASE = Computer-Aided Software Engineering A set of tools to (optimally) assist in each.
– Introduction to the Shell 10/1/2015 Introduction to the Shell – Session Introduction to the Shell – Session 2 · Permissions · Users.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Guidelines for Homework 6. Getting Started Homework 6 requires that you complete Homework 5. –All of HW5 must run on the GridFarm. –HW6 may run elsewhere.
Fixtures Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
M1G Introduction to Database Development 6. Building Applications.
CS 390- Unix Programming Environment CS 390 Unix Programming Environment Topics to be covered: Distributed Computing Fundamentals.
4/2/03I-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Software Architecture and Design Readings: Ambler, Chap. 7 (Sections to start.
FTP Client Application CSC 8560 Brian Jorgage 4/27/2004.
Java Introduction to JNI Prepared by Humaira Siddiqui.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Reusability and Effective Test Automation in Telecommunication System Testing Mikael Mattas Supervisor: Professor Sven-Gustav Häggman Instructor: B.Sc.
Python – Part 1 Python Programming Language 1. What is Python? High-level language Interpreted – easy to test and use interactively Object-oriented Open-source.
Problems with Send and Receive Low level –programmer is engaged in I/O –server often not modular –takes 2 calls to get what you want (send, followed by.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©
DEBUGGING. BUG A software bug is an error, flaw, failure, or fault in a computer program or system that causes it to produce an incorrect or unexpected.
Testing and Debugging Session 9 LBSC 790 / INFM 718B Building the Human-Computer Interface.
CE Operating Systems Lecture 3 Overview of OS functions and structure.
Unit Testing Maintaining Quality. How do you test? Testing to date…
Managing SX.e and TWL with MARC and Scripts Jeremiah Curtis
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
CS 4720 Dynamic Web Applications CS 4720 – Web & Mobile Systems.
Using Mock Objects with Test Driven Development Justin Kohlhepp
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Interface and Implementation Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Mock objects.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Mock Objects in Functional Testing Sven Rosvall. Dimension Data Cloud Business Unit.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
COMP3241 E-Commerce Technologies Richard Henson University of Worcester November 2014.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
Lecture 4 Mechanisms & Kernel for NOSs. Mechanisms for Network Operating Systems  Network operating systems provide three basic mechanisms that support.
The single most important skill for a computer programmer is problem solving Problem solving means the ability to formulate problems, think creatively.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
The Development Process Compilation. Compilation - Dr. Craig A. Struble 2 Programming Process Problem Solving Phase We will spend significant time on.
Event Management. EMU Graham Heyes April Overview Background Requirements Solution Status.
Lecture IX: Testing Web Services with Mocking CS 4593 Cloud-Oriented Big Data and Software Engineering.
Nguyen Thi Thanh Nha HMCL by Roelof Kemp, Nicholas Palmer, Thilo Kielmann, and Henri Bal MOBICASE 2010, LNICST 2012 Cuckoo: A Computation Offloading Framework.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
Five todos when moving an application to distributed HTC.
SOFTWARE TESTING TRAINING TOOLS SUPPORT FOR SOFTWARE TESTING Chapter 6 immaculateres 1.
Development Environment
Unit Testing.
Designing For Testability
PYTHON: AN INTRODUCTION
Mocking Your Objects with Impunity
SoarUnit Bob Marinier 11/29/2018.
Designing For Testability
Games Development 2 Entity / Architecture Review
Presentation transcript:

Capture-Replay Mocks Scandinavian Developer Conference 4 th April 2011 Geoff Bache

Copyright © 2008 Jeppesen Sanderson, Inc.Jeppesen Proprietary and ConfidentialSlide # Overview What is a “mock”? What do “coded mocks” look like? Introducing Capture-Replay mocks CaptureMock, with examples Demo

Copyright © 2008 Jeppesen Sanderson, Inc. What are “mocks”? “Simulated objects that mimic the behaviour of real objects in controlled ways” (Wikipedia) More strictly: “mocks” actively expect and assert behaviour “stubs” passively return hardcoded values “mocks and stubs” are collectively called “fakes” or “test doubles”. Terminology unfortunately not used consistently.

Copyright © 2008 Jeppesen Sanderson, Inc. Examples of when to use mocks/stubs When using the real code in your test would be  Hard to analyse (e.g. images created)  Too slow (e.g. databases)  Indeterministic (e.g. current time)  Hard/expensive to set up (e.g. network errors)  Impossible (because it doesn’t exist yet) As a design strategy (Behaviour-Driven Development)

Copyright © 2008 Jeppesen Sanderson, Inc. Mocking in Java (Mockito) //You can mock concrete classes, not only interfaces LinkedList mockedList = mock(LinkedList.class); //stubbing stub(mockedList.get(0)).toReturn("first"); stub(mockedList.get(1)).toThrow(new RuntimeException()); //following prints "first" System.out.println(mockedList.get(0)); //following throws runtime exception System.out.println(mockedList.get(1)); //following prints "null" because get(999) was not stubbed System.out.println(mockedList.get(999)); //Checks that we called “get(0)” at some point verify(mockedList).get(0);

Copyright © 2008 Jeppesen Sanderson, Inc. Mocking in Python (Mock) # Fix method return values and verify they were called from mock import Mock my_mock = Mock() my_mock.some_method.return_value = "value" assertEqual("value", my_mock.some_method()) my_mock.some_method.assert_called_once_with() # Set up expectation we will raise exceptions... my_mock.other_method.side_effect = SomeException("message") assertRaises(SomeException, my_mock.other_method())

Copyright © 2008 Jeppesen Sanderson, Inc. Stubbing in Python (“monkey patching”) # Example of ”monkey-patching” import time def hardcoded_asctime(): return 'Thu Mar 24 16:12: ' # We monkey-patch the standard library for our test time.asctime = hardcoded_asctime class ProductionClass: def method(self): print ”The time is”, time.asctime() real = ProductionClass() # Will print our faked, deterministic answer real.method()

Copyright © 2008 Jeppesen Sanderson, Inc. Problems with using mocks Involves writing sometimes complex code  Takes time to write  Has to be maintained Easy to create a lot of dependency on implementation details If the “real code” changes its behaviour :  The tests stay green  But the system doesn’t work any more...

Copyright © 2008 Jeppesen Sanderson, Inc. Capture-Replay Mocks Generate mocks by running the real code and capturing how it behaves Results in a normal test that can be run in two ways  using the stored mocks  or regenerating them from the real code No mock-code to write, just say what you want to capture Much easier to keep in synch with real code

Copyright © 2008 Jeppesen Sanderson, Inc. It's not “capture-replay” like EasyMock! # Some mock frameworks just use “capture-replay” as a syntax import mocker # We start in the “capture phase”... my_mock = mocker.mock() my_mock.some_method() mocker.result("value") # and then we “switch to replay” when we're ready to test mocker.replay() #... test code import mock my_mock = mock.Mock() my_mock.some_method.return_value = "value" #... test code Which is basically just a more verbose way to express:

Copyright © 2008 Jeppesen Sanderson, Inc. CaptureMock recording System under test 3rd party module CaptureMock Record traffic

Copyright © 2008 Jeppesen Sanderson, Inc. CaptureMock replay System under test 3rd party module CaptureMock

Copyright © 2008 Jeppesen Sanderson, Inc. CaptureMock : doing it in practice CaptureMock is a tool written in Python that can do this with  Python code (modules and attributes)  Command-line calls (subprocesses)  Plain-text messaging (over sockets) “Python code” part relies on Python’s dynamic features Other parts are language-independent Plain-text messaging assumes a synchronous model each socket sends one message and gets one reply.

Copyright © 2008 Jeppesen Sanderson, Inc. A Python CaptureMock test # test_ .py from capturemock import capturemock class ProductionClass: def method(self): # call some code resulting in being sent def test_ _sending(): real = ProductionClass() real.method() I can then run: $ env CAPTUREMOCK_MODE=1 test_ .py which will actually send the and record the interaction with smtplib to a file called ” _sending.mock”

Copyright © 2008 Jeppesen Sanderson, Inc. A CaptureMock recorded mock (Python) <-PYT:import smtplib <-PYT:smtplib.SMTP() ->RET:Instance('SMTP', 'smtp1') <-PYT:smtp1.connect('machine.site.com') ->RET:(220, 'machine.site.com ESMTP Sendmail; Tue, 9 Feb :32: ') ['tom', 'dick', 'harry'], '''From: To: tom,dick,harry Subject: Hi Guys! I love you all! ''') ->RET:{} <-PYT:smtp1.quit() When I run without CAPTUREMOCK_MODE, no will be sent and if the calls received differ from above, an exception will be thrown.

Copyright © 2008 Jeppesen Sanderson, Inc. A command-line CaptureMock test # update_and_build.sh # We update some code from CVS and then try to build it returned=`cvs update –dP /path/to/my/checkout` # logic using stuff written on stdout etc... make Here I put the following in.capturemockrc to tell it to capture calls to CVS [command line] intercepts = cvs which will perform the update for real and record to ”cvs_calls.mock” $ capturemock --record cvs_calls.mock update_and_build.sh and then run

Copyright © 2008 Jeppesen Sanderson, Inc. A recorded mock from a subprocess <-CMD:cvs update -dP /path/to/my/checkout ->FIL:checkout ->OUT:U subdir/myfile.txt ->ERR:cvs update: Updating. cvs update: Updating subdir Note the ”FIL” line refers to stored copies of the files changed by cvs. They are stored in a directory called ”cvs_calls.files”. To replay this, we run $ capturemock --replay cvs_calls.mock update_and_build.sh maybe on a machine where CVS isn't installed. CaptureMock will pretend to be CVS, reproducing the standard output, standard error, exit code and files written.

Copyright © 2008 Jeppesen Sanderson, Inc. A client-server CaptureMock test Assuming I have a client that sends strings to a server, which replies with how long they are, and a script that runs both together: $ capturemock --record communication.mock run_client_server.sh <-CLI:Here is a string ->SRV:Length was 16 <-CLI:Here is a longer string ->SRV:Length was 23 Something like this will appear in communication.mock: I can then use this data to test either the client or the server in isolation from the other.

Copyright © 2008 Jeppesen Sanderson, Inc. Demo : graphs and matplotlib

Copyright © 2008 Jeppesen Sanderson, Inc. Examples of when to use CaptureMock When using the real code in your test would be  Hard to analyse - yes  Too slow - yes  Indeterministic - yes, with care (record mode may fail)  Hard to set up - possibly (record mode still hard to set up)  Impossible because it doesn’t exist yet - no As a design strategy (Behaviour-Driven Development) - no

Copyright © 2008 Jeppesen Sanderson, Inc. Conclusions Existing mocking approaches – are labour-intensive when non-trivial code is mocked out – don't provide an easy means to verify the mock against real code CaptureMock – provides a means to (re-)generate mock information from the code – and two "modes" to select from each time tests are run