Testing. UW CSE 160 Winter 2016

Similar documents
CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 15 Testing

Testing. Prof. Clarkson Fall Today s music: Wrecking Ball by Miley Cyrus

Regression testing. Whenever you find a bug. Why is this a good idea?

Announcements. Testing. Announcements. Announcements

Software Testing Lecture 1. Justin Pearson

Testing and Debugging

Who is our rival? Upcoming. Testing. Ariane 5 rocket (1996) Ariane 5 rocket 3/8/18. Real programmers need no testing!

Chapter 5 Errors. Bjarne Stroustrup

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

Chapter 2.6: Testing and running a solution

What is a Fraction? Fractions. One Way To Remember Numerator = North / 16. Example. What Fraction is Shaded? 9/16/16. Fraction = Part of a Whole

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

Lecture 9: July 14, How to Think About Debugging

CSE 403: Software Engineering, Fall courses.cs.washington.edu/courses/cse403/16au/ Unit Testing. Emina Torlak

Repetition Through Recursion

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

Comparing procedure specifications

Steps for project success. git status. Milestones. Deliverables. Homework 1 submitted Homework 2 will be posted October 26.

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Text Input and Conditionals

Assertions, pre/postconditions

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

COMP-202 Unit 4: Programming with Iterations

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

Unit Testing as Hypothesis Testing

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

5) I want to get this done fast, testing is going to slow me down.

C07: Testing and JUnit

Manuel Oriol, CHCRC-C, Software Testing ABB

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Lecture 15 Software Testing

Last time. Reasoning about programs. Coming up. Project Final Presentations. This Thursday, Nov 30: 4 th in-class exercise

Reasoning about programs

Errors. And How to Handle Them

Divisibility Rules and Their Explanations

Therac-25 radiation therapy machine

Our First Programs. Programs. Hello World 10/7/2013

Software Engineering Testing and Debugging Testing

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

Summer May 11, 2010

Topics in Software Testing

Racket Style Guide Fall 2017

Testing. CMSC 433 Programming Language Technologies and Paradigms Spring A Real Testing Example. Example (Black Box)?

People tell me that testing is

Object-Oriented Design Lecture 5 CSU 370 Fall 2008 (Pucella) Friday, Sep 26, 2008

Chapter 7 Control Statements Continued

6.170 Lecture 6 Procedure specifications MIT EECS

Programming in the Real World. Dr. Baldassano Yu s Elite Education

Intro. Scheme Basics. scm> 5 5. scm>

CSE 331 Software Design & Implementation

Functions and abstraction. Ruth Anderson UW CSE 160 Winter 2017

(Refer Slide Time 6:48)

Control structure: Repetition - Part 2

Testing. CSE 331 University of Washington. Michael Ernst

Python lab session 1

Thread Synchronization: Foundations. Properties. Safety properties. Edsger s perspective. Nothing bad happens

Problem Solving for Intro to Computer Science

INTRODUCTION TO SOFTWARE ENGINEERING

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

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

CS 161 Computer Security

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Difference Between Dates Case Study 2002 M. J. Clancy and M. C. Linn

CS 520 Theory and Practice of Software Engineering Fall 2018

Red-Black trees are usually described as obeying the following rules :

How to approach a computational problem

Software Design Models, Tools & Processes. Lecture 6: Transition Phase Cecilia Mascolo

Writing better code Loop invariants Correctness. John Edgar 2

Lab 10: OCaml sequences, comparators, stable sorting 12:00 PM, Nov 12, 2017

Testing and Debugging

Verification and Validation

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Testing! The material for this lecture is drawn, in part, from! The Practice of Programming (Kernighan & Pike) Chapter 6!

Motivation. Both human- and computer-generated programs sometimes contain data-flow anomalies.

Chapter 11, Testing. Using UML, Patterns, and Java. Object-Oriented Software Engineering

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

Testing and Debugging Lecture 11

Types, Expressions, and States

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Algorithms and Programming I. Lecture#12 Spring 2015

CSE 15L Midterm Summer 2011

Software Engineering

Lecture Notes on Contracts

Intermediate Programming, Spring 2017*

Lecture 20: SW Testing Presented by: Mohammad El-Ramly, PhD

CSE 331 Midterm Exam Sample Solution 2/13/12

Exceptions and assertions

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Program Verification! Goals of this Lecture! Words from the Wise! Testing!

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

CS 115 Lecture 4. More Python; testing software. Neil Moore

(See related materials in textbook.) CSE 435: Software Engineering (slides adapted from Ghezzi et al & Stirewalt

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CSCE 121 ENGR 112 List of Topics for Exam 1

Loop structures and booleans

Transcription:

Testing UW CSE 160 Winter 2016 1

Testing Programming to analyze data is powerful It s useless (or worse!) if the results are not correct Correctness is far more important than speed 2

Famous examples Ariane 5 rocket Therac-25 radiation therapy machine 3

Testing does not prove correctness Edsger Dijkstra: Program testing can be used to show the presence of bugs, but never to show their absence! Testing can only increase our confidence in program correctness. 4

Testing your program How do you know your program is right? Compare its output to a correct output How do you know a correct output? Real data is big You wrote a computer program because it is not convenient to compute it by hand Use small inputs so you can compute the expected output by hand We did this in HW2 and HW3 with small data sets 5

Testing debugging Testing: determining whether your program is correct Doesn t say where or how your program is incorrect Debugging: locating the specific defect in your program, and fixing it 2 key ideas: divide and conquer the scientific method 6

Testing parts of your program Often called unit testing Testing that the output of individual functions is correct. 7

What is a test? A test consists of: an input (sometimes called test data ) expected output Example test for sum: input: [1, 2, 3] expected output: result is 6 write the test as: sum([1, 2, 3]) == 6 Example test for sqrt: input: 3.14 expected output: result is within 0.00001 of 1.772 ways to write the test: sqrt(3.14) 1.772 < 0.00001 and sqrt(3.14) 1.772 > -0.00001-0.00001 < sqrt(3.14) 1.772 < 0.00001 math.abs(sqrt(3.14) 1.772) < 0.00001 8

Test results The test passes if the boolean expression evaluates to True The test fails if the boolean expression evaluates to False Use the assert statement: assert sum([1, 2, 3]) == 6 assert math.abs(sqrt(3.14) 1.772) < 0.00001 assert True does nothing assert False crashes the program and prints a message 9

Where to write test cases At the top level: is run every time you load your program def hypotenuse(a, b): body of hypotenuse assert hypotenuse(3, 4) == 5 assert hypotenuse(5, 12) == 13 (As in HW 4) In a test function: is run when you invoke the function def hypotenuse(a, b): body of hypotenuse def test_hypotenuse(): assert hypotenuse(3, 4) == 5 assert hypotenuse(5, 12) == 1 (As in HW 3 and HW5) 10

Assertions are not just for test cases Use assertions throughout your code Documents what you think is true about your algorithm Lets you know immediately when something goes wrong The longer between a code mistake and the programmer noticing, the harder it is to debug 11

Assertions make debugging easier Common, but unfortunate, course of events: Code contains a mistake (incorrect assumption or algorithm) Intermediate value (e.g., in local variable, or result of a function call) is incorrect That value is used in other computations, or copied into other variables Eventually, the user notices that the overall program produces a wrong result Where is the mistake in the program? It could be anywhere. Suppose you had 10 assertions evenly distributed in your code When one fails, you can localize the mistake to 1/10 of your code (the part between the last assertion that passes and the first one that fails) 12

Where to write assertions Function entry: are arguments of expected type/size/value/shape? Place blame on the caller before the function fails Function exit: is result correct? Places with tricky or interesting code Assertions are ordinary statements; e.g., can appear within a loop: for n in mynumbers: assert type(n) == int or type(n) == float 13

Where not to write assertions Don t clutter the code (Same rule as for comments) Don t write assertions that are certain to succeed The existence of an assertion tells a programmer that it might possibly fail Don t need to write an assertion if the following code would fail informatively: assert type(name) == str print "Hello, " + name Write assertions where they may be useful for debugging 14

What to write assertions about Results of computations Correctly-formed data structures assert 0 <= index < len(mylist) assert len(list1) == len(list2) 15

When to write tests Two possibilities: Write code first, then write tests Write tests first, then write code It s best to write tests first If you write the code first, you remember the implementation while writing the tests You are likely to make the same mistakes that you made in the implementation (e.g. assuming that negative values would never be present) If you write the tests first, you will think more about the functionality than about a particular implementation You might notice some aspect of behavior that you would have made a mistake about, some special case of input that you would have forgotten to handle 16

Write the whole test A common mistake: 1. Write the function 2. Make up test inputs 3. Run the function 4. Use the result as the expected output BAD!! You didn t write a full test: only half of a test! Created the tests inputs, but not the expected output The test does not determine whether the function is correct Only determines that it continues to be as correct (or incorrect) as it was before 17

Tests outside of function body are for behavior described in the specification def roots(a, b, c): """Returns a list of the two roots of ax**2 + bx + c."""... Body of roots S Tests implementation-specific behavior outside of function body: (BAD) assert roots(1, 0, -1) == [-1, 1] Does the specification imply that this should be the order these two roots are returned? Assertions inside a routine can be used for implementation-specific behavior 18

Tests prevent you from introducing errors when you modify a function body Abstraction: the implementation details do not matter As long as the specification of the function remains the same, tests of the external behavior of the function should still apply. Preventing introducing errors when you make a change is called regression testing 19

Coming up with good test cases Think about and test corner cases Numbers: Lists: 20

Coming up with good test cases Think about and test corner cases Numbers: int vs. float values (remember not to test for equality with floats) Zero Negative values Lists: Empty list Lists containing duplicate values (including all the same value) Lists in ascending order/descending order Mix of types in list (if specification does not rule out) 21

Testing Approaches Black box testing - Choose test data without looking at implementation, just test behavior mentioned in the specification Glass box (white box, clear box) testing - Choose test data with knowledge of implementation (e.g. test that all paths through your code are exercised and correct) 22

def isprime(x): """Assumes x is a nonnegative int Returns True if x is prime; False otherwise""" if x <= 2: return False for i in range(2, x): if x % i == 0: return False return True 23

Tests might not reveal an error def mean(numbers): """Returns the average of the argument list. The argument must be a non-empty list of numbers.""" return sum(numbers)/len(numbers) # Tests assert mean([1, 2, 3, 4, 5]) == 3 assert mean([1, 2.1, 3.2]) == 2.1 This implementation is elegant, but wrong! mean([1,2,3,4]) 24

Don t write meaningless tests def mean(numbers): """Returns the average of the argument list. The argument must be a non-empty list of numbers.""" return sum(numbers)/len(numbers) Unnecessary tests. Don t write these: mean([1, 2, "hello"]) mean("hello") mean([]) 25