Test Data Generators Lecture 5. Why Distinguish Instructions? Functions always give the same result for the same arguments Instructions can behave differently.

Slides:



Advertisements
Similar presentations
Modelling & Datatypes John Hughes. Software Software = Programs + Data.
Advertisements

Algebra Problems… Solutions
Modelling & Datatypes Koen Lindström Claessen. Software Software = Programs + Data.
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 7.9Arrays of Pointers Arrays can contain pointers For.
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
CSCI 6962: Server-side Design and Programming Input Validation and Error Handling.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 25 Thanks for Lecture Slides: Dr. Sadaf Tanveer Dr. Sadaf Tanveer,
Recursive Data Types Koen Lindström Claessen. Modelling Arithmetic Expressions Imagine a program to help school-children learn arithmetic, which presents.
MAT 103 Probability In this chapter, we will study the topic of probability which is used in many different areas including insurance, science, marketing,
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
Datastructures Koen Lindström Claessen (guest lecture by Björn Bringert)
Lesson 6 - Pointers Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators Calling Functions by Reference Using the const.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Modelling & Datatypes Koen Lindström Claessen. Software Software = Programs + Data.
An Inference Procedure
1 Lecture 7 Halting Problem –Fundamental program behavior problem –A specific unsolvable problem –Diagonalization technique revisited Proof more complex.
1 Lecture 7 Halting Problem –Fundamental program behavior problem –A specific unsolvable problem –Diagonalization technique revisited Proof more complex.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
CS510AP Quick Check Monads. QuickCheck Quick check is a Haskell library for doing random testing. You can read more about quickcheck at –
UNR, MATH/STAT 352, Spring Radar target detection How reliable is the signal on the screen? (Is it a target of a false alarm?)
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
VOCABULARY  Deck or pack  Suit  Hearts  Clubs  Diamonds  Spades  Dealer  Shuffle  Pick up  Rank  Draw  Set  Joker  Jack 
Refreshing Your Skills for Chapter 10.  If you flip a coin, the probability that it lands with heads up is 1/2.  If you roll a standard die, the probability.
Object Oriented Data Structures
Algorithms. What is an algorithm?  An algorithm is a clear, concise, and correct step- by-step sequence of actions.
Erlang/QuickCheck Thomas Arts, IT University John Hughes, Chalmers University Gothenburg.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 10 Program Organization (continued)
Data Structures and Algorithm Analysis Hashing Lecturer: Jing Liu Homepage:
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
Two Way Tables Venn Diagrams Probability. Learning Targets 1. I can use a Venn diagram to model a chance process involving two events. 2. I can use the.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Testing and Debugging (Depuração em Haskell) Complementa as seções anteriores Original autorizado por: John Hughes Adaptado.
Can’t provide fast insertion/removal and fast lookup at the same time Vectors, Linked Lists, Stack, Queues, Deques 4 Data Structures - CSCI 102 Copyright.
16. STRUCTURES, UNIONS, AND ENUMERATIONS. Declaring Structures A structure is a collection of one or more components (members), which may be of different.
Review Homework pages Example: Counting the number of heads in 10 coin tosses. 2.2/
C Lecture Notes 1 Structures & Unions. C Lecture Notes Introduction Structures –Collections of related variables (aggregates) under one name Can.
Function Definition by Cases and Recursion Lecture 2, Programmeringsteknik del A.
Draw 3 cards without replacement from a standard 52 card deck. What is the probability that: 1.They are all red ? 2.At least one is black ? 3.They are.
+ Chapter 5 Overview 5.1 Introducing Probability 5.2 Combining Events 5.3 Conditional Probability 5.4 Counting Methods 1.
The Practice of Statistics, 5th Edition Starnes, Tabor, Yates, Moore Bedford Freeman Worth Publishers CHAPTER 5 Probability: What Are the Chances? 5.2.
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
Overview of Previous Lesson(s) Over View 3  CLR Programming  Common Language Runtime (CLR) is a programming, that manages the execution of programs,
Statistics 16 Random Variables. Expected Value: Center A random variable assumes a value based on the outcome of a random event. –We use a capital letter,
Probability and statistics - overview Introduction Basics of probability theory Events, probability, different types of probability Random variable, probability.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
Test Data Generators. Why Distinguish Instructions? Functions always give the same result for the same arguments Instructions can behave differently on.
Polymorphic Functions
PROGRAMMING IN HASKELL
Section 2 – CSE341 Patrick Larson, Spring 2013.
Test Data Generators.
PROGRAMMING IN HASKELL
Koen Lindström Claessen
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Section 2 – CSE341 Konstantin Weitz.
Nicholas Shahan Spring 2016
Introduction to Primitive Data types
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
CSE 341 PL Section 2 Justin Harjanto.
Type & Typeclass Syntax in function
Spencer Pearson Spring 2017
CSE 341 Section 2 Nick Mooney Spring 2017
CS2013 Lecture 7 John Hurley Cal State LA.
Homework Due Friday.
PROGRAMMING IN HASKELL
Introduction to Primitive Data types
Presentation transcript:

Test Data Generators Lecture 5

Why Distinguish Instructions? Functions always give the same result for the same arguments Instructions can behave differently on different occasions Confusing them (as in most programming languages) is a major source of bugs –This concept a major breakthrough in programming languages in the 1990s –How would you write doTwice in C?

Monads = Instructions What is the type of doTwice? Main> :i doTwice doTwice :: Monad a => a b -> a (b,b) Whatever kind of result argument produces, we get a pair of them Even the kind of instructions can vary! Different kinds of instructions, depending on who obeys them. IO means operating system.

Instructions for Test Data Generation Generate different test data every time –Hence need ”instructions to generate an a” –Instructions to QuickCheck, not the OS –Gen a  IO a Generating data of different types? QuickCheck> :i Arbitrary -- type class class Arbitrary a where arbitrary :: Gen a coarbitrary :: a -> Gen b -> Gen b

Sampling We provide Sample.hs, defining sample to print some sampled values: sample :: Gen a -> IO () Example: Sample> sample (arbitrary :: Gen Integer) Fix the type we generate Prints (fairly small) test data QuickCheck might generate

Sampling Booleans Sample> sample (arbitrary :: Gen Bool) True False True

Sampling Doubles Sample> sample (arbitrary :: Gen Double)

Sampling Lists Sample> sample (arbitrary :: Gen [Integer]) [-15,-12,7,-13,6,-6,-2,4] [3,-2,0,-2,1] [] [-11,14,2,8,-10,-8,-7,-12,-13,14,15,15,11,7] [-4,10,18,8,14]

Writing Generators Write instructions using do and return: Sample> sample (return True) True

Writing Generators Write instructions using do and return: Main> sample (doTwice (arbitrary :: Gen Integer)) (12,-6) (5,5) (-1,-9) (4,2) (13,-6) It’s important that the instructions are followed twice, to generate two different values.

Writing Generators Write instructions using do and return: Main> sample evenInteger evenInteger :: Gen Integer evenInteger = do n <- arbitrary return (2*n)

Generation Library QuickCheck provides many functions for constructing generators Main> sample (choose (1,10) :: Gen Integer)

Generation Library QuickCheck provides many functions for constructing generators Main> sample (oneof [return 1, return 10]) oneof :: [Gen a] -> Gen a

Generating a Suit Main> sample suit Spades Hearts Diamonds Clubs data Suit = Spades | Hearts | Diamonds | Clubs deriving (Show,Eq) suit :: Gen Suit suit = oneof [return Spades, return Hearts, return Diamonds, return Clubs] QuickCheck chooses one set of instructions from the list

Generating a Rank Main> sample rank Numeric 4 Numeric 5 Numeric 3 Queen King data Rank = Numeric Integer | Jack | Queen | King | Ace deriving (Show,Eq) rank = oneof [return Jack, return Queen, return King, return Ace, do r <- choose (2,10) return (Numeric r)]

Generating a Card Main> sample card Card Ace Hearts Card King Diamonds Card Queen Clubs Card Ace Hearts Card Queen Clubs data Card = Card Rank Suit deriving (Show,Eq) card = do r <- rank s <- suit return (Card r s)

Generating a Hand Main> sample hand Add (Card Jack Clubs) (Add (Card Jack Hearts) Empty) Empty Add (Card Queen Diamonds) Empty Empty data Hand = Empty | Add Card Hand deriving (Eq, Show) hand = oneof [return Empty, do c <- card h <- hand return (Add c h)]

Making QuickCheck Use Our Generators QuickCheck can generate any type of class Arbitrary: Main> :i Arbitrary -- type class class Arbitrary a where arbitrary :: Gen a coarbitrary :: a -> Gen b -> Gen b -- instances: instance Arbitrary () instance Arbitrary Bool instance Arbitrary Int … This tells QuickCheck how to generate values

Making QuickCheck Use Our Generators QuickCheck can generate any type of class Arbitrary So we have to make our types instances of this class instance Arbitrary Suit where arbitrary = suit Make a new instance …of this class… …for this type… …where this method… …is defined like this.

Datatype Invariants We design types to model our problem – but rarely perfectly –Numeric (-3) ?? Only certain values are valid This is called the datatype invariant – should always be True validRank :: Rank -> Bool validRank (Numeric r) = 2<=r && r<=10 validRank _ = True

Testing Datatype Invariants Generators should only produce values satisfying the datatype invariant: Stating the datatype invariant helps us understand the program, avoid bugs Testing it helps uncover errors in test data generators! prop_Rank r = validRank r Testing code needs testing too!

Test Data Distribution We don’t see the test cases when quickCheck succeeds Important to know what kind of test data is being used prop_Rank r = collect r (validRank r) This property means the same as validRank r, but when tested, collects the values of r

Distribution of Ranks Main> quickCheck prop_Rank OK, passed 100 tests. 26% King. 25% Queen. 19% Jack. 17% Ace. 7% Numeric 9. 2% Numeric 7. 1% Numeric 8. 1% Numeric 6. 1% Numeric 5. 1% Numeric 2. We see a summary, showing how often each value occured Face cards occur much more frequently than numeric cards!

Fixing the Generator rank = frequency [(1,return Jack), (1,return Queen), (1,return King), (1,return Ace), (9, do r <- choose (2,10) return (Numeric r))] Each alternative is paired with a weight determining how often it is chosen. Choose number cards 9x as often.

Distribution of Hands Collecting each hand generated produces too much data—hard to understand Collect a summary instead—say the number of cards in a hand numCards :: Hand -> Integer numCards Empty = 0 numCards (Add _ h) = 1 + numCards h

Distribution of Hands Main> quickCheck prop_Hand OK, passed 100 tests. 53% 0. 25% 1. 9% 2. 5% 3. 4% 4. 2% 9. 2% 5. prop_Hand h = collect (numCards h) True Nearly 80% have no more than one card!

Fixing the Generator Returning Empty 20% of the time gives average hands of 5 cards hand = frequency [(1,return Empty), (4, do c <- card h <- hand return (Add c h))] Main> quickCheck prop_Hand OK, passed 100 tests. 22% 0. 13% 2. 13% 1. 12% 5. 12% 3. 6% 4. 4% 9. 4% 8. …

Datatype Invariant? Are there properties that every hand should have? prop_Hand h = collect (numCards h) True We’re not testing any particular property of Hands

Testing Algorithms

Testing insert insert x xs—inserts x at the right place in an ordered list Main> insert 3 [1..5] [1,2,3,3,4,5] The result should always be ordered prop_insert :: Integer -> [Integer] -> Bool prop_insert x xs = ordered (insert x xs)

Testing insert Main> quickCheck prop_insert Falsifiable, after 2 tests: 3 [0,1,-1] prop_insert :: Integer -> [Integer] -> Property prop_insert x xs = ordered xs ==> ordered (insert x xs) Of course, the result won’t be ordered unless the input is Testing succeeds, but…

Testing insert Let’s observe the test data… prop_insert :: Integer -> [Integer] -> Property prop_insert x xs = collect (length xs) $ ordered xs ==> ordered (insert x xs) Main> quickCheck prop_insert OK, passed 100 tests. 41% 0. 38% 1. 14% 2. 6% 3. 1% 5. Why so short???

What’s the Probability a Random List is Ordered? LengthOrdered? % 50% 17% 4%

Generating Ordered Lists Generating random lists and choosing ordered ones is silly Better to generate ordered lists to begin with—but how? One idea: –Choose a number for the first element –Choose a positive number to add to it for the next –And so on

The Ordered List Generator orderedList :: Gen [Integer] orderedList = do n <- arbitrary listFrom n where listFrom n = frequency [(1, return []), (5, do i <- arbitrary ns <- listFrom (n+abs i) return (n:ns))]

Trying it Main> sample orderedList [10,21,29,31,40,49,54,55] [3,5,5,7,10] [0,1,2] [7,7,11,19,28,36,42,51,61] []

Making QuickCheck use a Custom Generator Can’t redefine arbitrary: the type doesn’t say we should use orderedList Make a new type data OrderedList = Ordered [Integer] A new type with a datatype invariant

Making QuickCheck use a Custom Generator Make a new type Make an instance of Arbitrary data OrderedList = Ordered [Integer] instance Arbitrary OrderedList where arbitrary = do xs <- orderedList return (Ordered xs)

Testing insert Correctly prop_insert x (Ordered xs) = ordered (insert x xs) Main> quickCheck prop_insert OK, passed 100 tests. prop_insert :: Integer -> OrderedList -> Bool

Collecting Data prop_insert x (Ordered xs) = collect (length xs) $ ordered (insert x xs) Main> quickCheck prop_insert OK, passed 100 tests. 17% 1. 16% 0. 12% 3. 12% 2…. Wide variety of lengths

Some Tips Using GHC(i): instance Arbitrary MyType where arbitrary = … Aap.hs:5:0: Warning: No explicit method nor default method for `coarbitrary' In the instance declaration for `Arbitrary Char' Add a flag: -fno-warn-missing-methods

So... Starting GHC(i) Linux> ghci -fno-warn-missing-methods

Reading About I/O: Chapter 18 of the text book About QuickCheck: read the manual linked from the course web page. –There are also several research papers about QuickCheck, and advanced tutorial articles.