Dynamic Analysis Techniques Part 2

Similar documents
Assertions, pre/postconditions

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Test-Driven Development (a.k.a. Design to Test) CSE260, Computer Science B: Honors Stony Brook University

a correct statement? You need to know what the statement is supposed to do.

Assertions. Assertions - Example

Tutorial 3: Unit tests and JUnit

CSCE 747 Unit Testing Laboratory Name(s):

Inheritance (Part 5) Odds and ends

n Specifying what each method does q Specify it in a comment before method's header n Precondition q Caller obligation n Postcondition

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen

Inheritance and Interfaces

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Adding Contracts to C#

Programming with assertions Oracle guidelines

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

17. Assertions. Outline. Built-in tests. Built-in tests 3/29/11. Jelle Slowack, Bart Smets, Glenn Van Loon, Tom Verheyen

Chapter 15. Software Testing The assert Statement

Introduction to Java

17. Assertions. Jelle Slowack, Bart Smets, Glenn Van Loon, Tom Verheyen

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

CSE 331 Summer 2016 Final Exam. Please wait to turn the page until everyone is told to begin.

UC Santa Barbara. CS189A - Capstone. Christopher Kruegel Department of Computer Science UC Santa Barbara

Welcome to Informatik 2!

JAVA BASICS II. Example: FIFO

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

The Contract Pattern. Design by contract

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

3. Design by Contract

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Binghamton University. CS-140 Fall Unit Testing

Advanced JML Erik Poll Radboud University Nijmegen

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

Binghamton University. CS-140 Fall Unit Testing

Catching Defects: Design or Implementation Phase? Design-by-Contract (Dbc) Test-Driven Development (TDD) Motivation of this Course

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Object Oriented Program Correctness with OOSimL

Practical Unit Testing junit. Atul Prakash

Introduc)on to tes)ng with JUnit. Workshop 3

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Design by Contract: An Overview

Verifying and Documenting ADTs: Javadoc, Java Assertions and JUnits

The following topics will be covered in this course (not necessarily in this order).

Problem other classes messing with my stuff!

Chapter 5 Object-Oriented Programming

CS201 - Assignment 3, Part 1 Due: Friday February 28, at the beginning of class

Java Fundamentals (II)

CSE 331 Final Exam 3/16/15 Sample Solution

Object Oriented Issues in VDM++

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

VIRTUAL FUNCTIONS Chapter 10

CSC Advanced Object Oriented Programming, Spring Specification

Fortgeschrittene objektorientierte Programmierung (Advanced Object-Oriented Programming)

Black Box Testing. EEC 521: Software Engineering. Specification-Based Testing. No Source Code. Software Testing

Another IS-A Relationship

hwu-logo.png 1 class Rational { 2 int numerator ; int denominator ; 4 public Rational ( int numerator, int denominator ) {

OOP Design by Contract. Carsten Schuermann Kasper Østerbye IT University Copenhagen

CS/ENGRD 2110 FALL Lecture 2: Objects and classes in Java

CS159. Nathan Sprague. September 30, 2015

Code Contracts in C#

Getting It Right COMS W4115. Prof. Stephen A. Edwards Spring 2007 Columbia University Department of Computer Science

CMSC 331 Second Midterm Exam

Levels of Testing Testing Methods Test Driven Development JUnit. Testing. ENGI 5895: Software Design. Andrew Vardy

Contracts. Dr. C. Constantinides. June 5, Department of Computer Science and Software Engineering Concordia University Montreal, Canada 1/71

Final Exam. Final Exam Review. Ch 1: Introduction: Object-oriented analysis, design, implementation. Exam Format

Levels of Testing Testing Methods Test Driven Development JUnit. Testing. ENGI 5895: Software Design. Andrew Vardy

CS 11 java track: lecture 3

Chapter 10 Classes Continued. Fundamentals of Java

Object-Oriented Concepts

15CS45 : OBJECT ORIENTED CONCEPTS

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Use the scantron sheet to enter the answer to questions (pages 1-6)

Chapter 4 Defining Classes I

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

What This Course Is About Design-by-Contract (DbC)

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

AP Computer Science A Elevens Lab Student Guide

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Chapter 14. Exception Handling and Event Handling ISBN

School of Informatics, University of Edinburgh

Automatic Black-Box Method-Level Test Case Generation Based on Constraint Logic Programming

No Source Code. EEC 521: Software Engineering. Specification-Based Testing. Advantages

Program Correctness and Efficiency. Chapter 2

Software LEIC/LETI. Lecture 5

Java: advanced object-oriented features

Chapter 4.!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1

Inheritance. OOP: Inheritance 1

In this lab we will practice creating, throwing and handling exceptions.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Data Abstraction: The Walls

Exception-Handling Overview

The Java Modeling Language JML

Java for Non Majors Spring 2018

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

Transcription:

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 1 Software Design (F28SD2) Dynamic Analysis Techniques Part 2 Andrew Ireland School of Mathematical & Computer Sciences Heriot-Watt University Edinburgh

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 2 Review Functional testing: Equivalence partitioning Boundary value analysis State based testing Structural testing: Code coverage analysis Data definition-use testing Hybrid testing: Error guessing Assertion based testing

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 3 Error Guessing Error guessing is driven by experience and will typically cover both functional and structural perspectives. To illustrate, given a software component to test that exploits dynamic storage allocation, then an experienced tester will typically focus upon the correct use of resource deallocation, e.g. seek out memory leakage defects. By its very nature, error guessing is hard to teach. However, check lists designed around language features and related defects can play a useful role in the transfer of experience.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 4 Assertion Based Testing An assertion is a boolean valued expression, i.e. evaluates to true or false. Assertions allow a programmer to express what they believe should be true at given points within their code. Note that here we only consider assertions within the context of dynamic analysis, i.e. assertions that are executed. Assertions will be represented differently depending upon your implementation language we will focus upon assertions within Java.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 5 Assertion Based Object Oriented Testing Encapsulation: gaining access to states and hidden instance variables is crucial if effective testing is to be conducted. Inheritance and polymorphism: overriding does not mean local testing is enough. That is, an inherited method that has be fully tested within the superclass must be re-tested within the context of the subclass. Unit testing: treating methods as the basis for unit testing will not work in general, a class perspective is called for, i.e. class states, class modality etc.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 6 Design by Contract Strong analogy with legal contracts, i.e. an explicit statement about the benefits (rights) and obligations that exist between a client and supplier. Each supplier method has an associated precondition assertion that checks the correctness of client requests client responsible for establishing precondition. Each supplier method has an associated postcondition assertion that checks the correctness of the supplier s: response to the client and suppliers state after the response is calculated. supplier responsible for establishing postcondition. Note: intermediate method assertions may also be desirable, e.g. loop invariants.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 7 Obligations and Benefits Obligations Benefits Client Must ensure May benefit from preconditions, e.g. postconditions, e.g. Ensure space in table Obtain new table for given key/value updated with given pair key/value pair Supplier Must ensure May assume postconditions, e.g. preconditions, e.g. Ensure given key/value No need to consider pair has been correctly if table is full added to the table

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 8 Java Support for Assertions J2SE (Java 2 Platform, Standard Edition) 1.4 and above supports a simple assertion facility: new keyword, i.e. assert new class, i.e. AssertionError some additional methods added to java.lang.classloader J2SE 1.6 is the default on the departmental Linux PCs.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 9 Java Assertions: Syntax & Semantics Syntax: assert statements come in 2 forms: assert expression1; assert expression1 : expression2; where expression1 and expression2 must be of type boolean and String respectively. Semantics: execution requires evaluation of expression1: If expression1 evaluates to true then no effect. If expression1 evaluates to false then default AssertionError constructor invoked (if no expression2). otherwise evaluate expression2 and use result with single-parameter AssertionError constructor.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 10 A Simple Example class Foo public static void even(int value) assert 0 <= value; if (value % 2 == 0) System.out.println("Even"); else System.out.println("Odd"); public static void main(string[] args) throws IOException even(2); even(3); even(-1);

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 11 Compilation and Execution By default the Java run-time system ignores assertions, so again a command line option to enable assertions is required, e.g. java -enableassertions Foo fortunately this can be abbreviated to: java -ea Foo Note that default behaviour a little backward, developers are being very cautious.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 12 Compile: $ javac Foo.java Example Revisited Execute with assertions disabled: $ java Foo Even Odd Odd Execute with assertions enabled: $ java -ea Foo Even Odd Exception in thread "main" java.lang.assertionerror at Foo.even(Foo.java:12) at Foo.main(Foo.java:23)

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 13 Assertion Messages class Foo public static void even(int value) assert 0 <= value : "Value must not be negative: value= " + value;...... $ javac Foo.java $ java -ea Foo Even Odd Exception in thread "main" java.lang.assertionerror: Value must not be negative: value= -1 at Foo.even(Foo.java:12) at Foo.main(Foo.java:23)

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 14 A More Interesting Example class Book class Entry String key; String value; Entry(String key, String value) this.key = key; this.value = value;...

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 15 A More Interesting Example...... private int capacity; private int index; private Entry [] book; public Book(int capacity) this.book = new Entry [capacity]; this.capacity = capacity; this.index = 0;

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 16 Specification via Comments public void insertdata(string key, String data) // assume data count is less than capacity... your array insertion algorithm goes here... // book now contains given data and // is associated with the given key and // data count has been increased by 1

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 17 Specification via Assertions public void insertdata(string key, String data) int initialcount = count(); assert initialcount < capacity... your array insertion algorithm goes here... assert contains(data) && iskey(data) == key && count() == initialcount + 1

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 18 Specification & Implementation public void insertdata(string key, String data) int initialcount = count(); assert initialcount < capacity Entry e = new Entry(key, data); book[index] = e; index++; assert contains(data) && iskey(data) == key && count() == initialcount + 1

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 19 Auxiliary Methods boolean contains(string data) int i=0; boolean found = false; while (i < index &&!found) if (book[i].value == data) found = true; else i++; return found; Exercise: Define the count and iskey methods.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 20 Class Invariant for Book boolean BookClassInvariant() int cnt = count(); return cnt >= 0 && cnt <= capacity; public Book(int capacity)... code... assert BookClassInvariant() public void insertdata(string key, String data) assert BookClassInvariant()... code... assert BookClassInvariant()

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 21 Design by Contract (more) Each class has an associated invariant assertion that characterizes the space of correct instance variable values for the class. Invariant assertions are checked when method precondition and postcondition assertions are checked. Class contracts must be consistent across subclass/superclass definitions, i.e. a subcontractor (supplier) that is employed to perform a specialized task takes on part of the responsibility of the main contractor (supplier): Preconditions of subclass method must be the same (or weaker) than the associated superclass method. Postconditions of subclass method must be the same (or stronger) than the associated superclass method. Subclass invariant must be the same (or stronger) than the superclass invariant.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 22 Contracts, Inheritance and Robustness Contract consistency across subclass/superclass definitions is not mechanized within Java, i.e. needs to be checked off-line by hand. The Eiffel object-oriented programming language provides greater support for the Design-by-Contract approach - see http://www.eiffel.com/ Input validation checks should not be confused with assertions, i.e. Input validation checks are about robustness Assertions are about correctness Input validation checks and assertions are complementary.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 23 JUnit: A Framework for Unit Testing JUnit provides a unit testing framework for Java applications. Users write test cases, i.e. inputs and expected results. JUnit automates the execution and presentation of the results. Typically promoted in the extreme programming community, i.e. testing and coding should go hand-in-hand, with test case generation leading the way. Standalone: Text; AWT; Swing. IDE: Eclipse; JBuilder;... The basic approach has be adopted by others, e.g. PHP (PHPUnit), Python (PyUnit), C++ (CPPUnit),...

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 24 What is a JUnit Test? Unit tests are represented by test classes, and can be viewed as drivers. For example, consider a Book class: Class Book has new, insertdata, lookupdata,... Class TestBook has testemptybook, testaddonebook, testintegritybook Unit tests are expressed in terms of assertions, i.e. asserttrue, assertfalse, assertnull, assertnotnull, assertequals, assertsame, assertnotsame

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 25 JUnit Testing of the Book Class Consider some tests: A new Book has zero entries. A new Book which has been updated with one entry, has only one entry! Given an entry with key X and value Y, then looking up X will retrieve Y. Now let s see how to implement them as JUnit tests...

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 26 package mybook.tests; import junit.framework.*; import junit.extensions.*; import mybook.*; A Test Case Class public class BookTest extends TestCase public void testemptybook() assertequals(0, new Book(3).index);... Note that TestCase is a JUnit class that you extend.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 27 A Test Case Class [ more ] package mybook.tests;... public class BookTest extends TestCase... public void testaddonebook() Book bk = new Book(1); bk.insertdata("micky", "Disney"); assertequals(1, bk.index); public void testingerityposbook() Book bk = new Book(1); bk.insertdata("micky", "Disney"); assertequals("address-name missmatch", "Disney", bk.lookupdata("micky"));

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 28 Running JUnit Tests [ partial success ] java -cp.:/usr/local/java/bluej/lib/junit.jar \ junit.textui.testrunner \ mybook.tests.booktest...f Time: 0.018 There was 1 failure: 1) testingerityposbook(mybook.tests.booktest) junit.framework.comparisonfailure: address-name missmatch expected:<disney> but was:<failure>... FAILURES!!! Tests run: 3, Failures: 1, Errors: 0 Note: cp = class search path for directories and zip/jar files.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 29 lookupdata [ buggy ] public String lookupdata(string k) int i=0; boolean found = false; while (i < index &&!found) if (book[i].value == k) found = true; else i++; if (found) return book[i].value; else return "Failure"; Note: book[i].value returns that value associated with entry i, and not the key.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 30 lookupdata [ patched ] public String lookupdata(string k) int i=0; boolean found = false; while (i < index &&!found) if (book[i].key == k) found = true; else i++; if (found) return book[i].value; else return "Failure";

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 31 Running JUnit Tests [ success ] java -cp.:/usr/local/java/bluej/lib/junit.jar \ junit.textui.testrunner \ mybook.tests.booktest... Time: 0.03 OK (3 tests)

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 32 Summary The importance of error guessing. The value of executable assertions active comments. Assertions within the context of object-oriented programming and Java in particular. Design by Contract. Unit testing with assertions via JUnit. Note: Assertions can be buggy!

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 33 References Testing Object-Oriented Systems, Binder, R.V. Addison-Wesley, 1999. Design By Contract, Meyer, B. IEEE Computer 25(10):40-51, 1992. Software Testing, Hambling, B. (Editor), British Computer Society Publication, 2008.

oftware Design (F28SD2): Dynamic Analysis Techniques Part 2 34 References Java assertions http://java.sun.com/developer/ technicalarticles/javalp/assertions/ JUnit http://www.junit.org AssertMate a code assertion system for Java, RST Corp: http://www.cigital.com/products/ Test Coverage Tool Venders: http://www.iplbath.com http://www.reflex-tech.co.uk