Skip to content
Book 4: Practical Programming

Book 4 · Chapter P4.4

Testing and evidence

§12.3AS skills Paper 4 builds onRegular · ≈ 3.8 m · →B4·4

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

For the whole chapter

§12.3 Program testing · Program maintenance

Short code B4·4·1

Testing on Paper 4

Short code B4·4·10

print("Start")
Level = 35
if Level < 40
    print("Water now")
The first line would print Start, but nothing at all is printed: Python reads the whole program before it runs a single line, and line 3 has no colon.

Output

ERROR (exit 1):     if Level < 40                  ^ SyntaxError: expected ':'
Run and checked before printing

Part A: choosing test data

Short code B4·4·11

def ValidLitres(Litres):
    return Litres >= 5 and Litres <= 25

for Litres in [15, 5, 4, 100]:
    print(str(Litres) + " " + str(ValidLitres(Litres)))
The first Mark Ladder's test plan, run against ValidLitres: every actual result matches the plan.

Output

15 True
5 True
4 False
100 False
Run and checked before printing
def ValidSeats(Seats):
    return Seats >= 1 and Seats <= 8

for Seats in [4, 8, 9, 20]:
    print(str(Seats) + " " + str(ValidSeats(Seats)))
The faded twin's test plan, run against ValidSeats.

Output

4 True
8 True
9 False
20 False
Run and checked before printing

A test plan you can run

Short code B4·4·12

def ValidTarget(Target):
    return Target >= 20 and Target <= 80

Tests = [50, 20, 80, 19, 81, -5, 150]
Expected = ["accepted", "accepted", "accepted", "rejected",
            "rejected", "rejected", "rejected"]
for Index in range(len(Tests)):
    Actual = "rejected"
    if ValidTarget(Tests[Index]):
        Actual = "accepted"
    Status = "pass"
    if Actual != Expected[Index]:
        Status = "FAIL"
    print("Test " + str(Index + 1) + ": " + str(Tests[Index]) + " " + Actual + " " + Status)
A test plan run by the program itself: each test value, the result the plan expected, and pass or FAIL.

Output

Test 1: 50 accepted pass
Test 2: 20 accepted pass
Test 3: 80 accepted pass
Test 4: 19 rejected pass
Test 5: 81 rejected pass
Test 6: -5 rejected pass
Test 7: 150 rejected pass
Run and checked before printing
def ValidTarget(Target):
    return Target > 20 and Target <= 80

Tests = [50, 20, 80, 19, 81, -5, 150]
Expected = ["accepted", "accepted", "accepted", "rejected",
            "rejected", "rejected", "rejected"]
for Index in range(len(Tests)):
    Actual = "rejected"
    if ValidTarget(Tests[Index]):
        Actual = "accepted"
    Status = "pass"
    if Actual != Expected[Index]:
        Status = "FAIL"
    print("Test " + str(Index + 1) + ": " + str(Tests[Index]) + " " + Actual + " " + Status)
The same plan against a faulty version, written Target > 20. Only Test 2, the extreme value 20, catches it.

Output

Test 1: 50 accepted pass
Test 2: 20 rejected FAIL
Test 3: 80 accepted pass
Test 4: 19 rejected pass
Test 5: 81 rejected pass
Test 6: -5 rejected pass
Test 7: 150 rejected pass
Run and checked before printing

Screenshot evidence

Short code B4·4·13

def GetTarget():
    Target = int(input("Target (20 to 80): "))
    while Target < 20 or Target > 80:
        print("Rejected " + str(Target) + ": out of range")
        Target = int(input("Target (20 to 80): "))
    return Target

Target = GetTarget()
print("Target set to " + str(Target))
The run behind a test screenshot. Inputs 85, 19, 20: each rejection names the value, so the screenshot proves which data was typed.

Output

Target (20 to 80): Rejected 85: out of range
Target (20 to 80): Rejected 19: out of range
Target (20 to 80): Target set to 20
Run and checked before printing

Part B: three kinds of error, in code

Short code B4·4·14

print("Start")
Total = 5
print(Totals)
Python: the misspelt Totals is found only when line 3 runs, as a run-time NameError. (Start is printed first; a captured run shows only the error.)

Output

ERROR (exit 1):     print(Totals)           ^^^^^^ NameError: name 'Totals' is not defined. Did you mean: 'Total'?
Run and checked before printing
public class Main {
    public static void main(String[] args) {
        System.out.println("Start");
        int Total = 5;
        System.out.println(Totals);
    }
}
Java: the same slip stops the compiler, so nothing runs, not even the first println.
Run and checked before printing
Module Program
    Sub Main()
        Console.WriteLine("Start")
        Dim Total As Integer = 5
        Console.WriteLine(Totals)
    End Sub
End Module
VB.NET: the same slip stops the build.
Run and checked before printing

Syntax errors: reading the message

Short code B4·4·15

public class Main {
    public static void main(String[] args) {
        int Level = 35;
        int Target = 40;
        if (Level = Target) {
            System.out.println("On target");
        }
    }
}
Java: a single = in a condition is an assignment, and an int cannot be a condition.
Run and checked before printing
public class Main {
    public static void main(String[] args) {
        int Count = 0;
        for (int I = 1; I <= 3; I++) {
            Count = Count + I;
        System.out.println(Count);
    }
}
Java: the for loop's closing brace is missing (after line 5), but the compiler reports line 8, the last line of the file.
Run and checked before printing
Module Program
    Sub Main()
        Dim Level As Integer = 35
        If Level < 40 Then
            Console.WriteLine("Water now")
    End Sub
End Module
VB.NET: an If with no End If. The message points at the If on line 4, not at the place the End If belongs.
Run and checked before printing

Run-time errors

Short code B4·4·16

Readings = [40, 35, 52]
for Index in range(4):
    print(Readings[Index])
Python: the loop asks for index 3 of a list with indexes 0 to 2. The readings 40, 35 and 52 are printed first; the run then stops.

Output

ERROR (exit 1):     print(Readings[Index])           ~~~~~~~~^^^^^^^ IndexError: list index out of range
Run and checked before printing
public class Main {
    public static void main(String[] args) {
        int[] Readings = {40, 35, 52};
        for (int Index = 0; Index <= 3; Index++) {
            System.out.println(Readings[Index]);
        }
    }
}
Java: the same fault. The message names the bad index, the array's length and the line.

Output

ERROR (exit 1): Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 	at Main.main(Main.java:5)
Run and checked before printing
Module Program
    Sub Main()
        Dim Readings() As Integer = {40, 35, 52}
        For Index As Integer = 0 To 3
            Console.WriteLine(Readings(Index))
        Next
    End Sub

    ' Not part of the program being tested: these lines print the run-time
    ' error as the IDE shows it, with the file name but no folder names.
    Sub New()
        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf Report
    End Sub

    Sub Report(Sender As Object, E As UnhandledExceptionEventArgs)
        Dim Ex As Exception = CType(E.ExceptionObject, Exception)
        Console.WriteLine("Unhandled exception. " & Ex.GetType().FullName & ": " & Ex.Message)
        For Each Frame As Diagnostics.StackFrame In New Diagnostics.StackTrace(Ex, True).GetFrames()
            If Frame.GetFileName() <> Nothing Then
                Console.WriteLine("   at " & Frame.GetMethod().Name & " in " & IO.Path.GetFileName(Frame.GetFileName()) & ":line " & Frame.GetFileLineNumber())
                Exit For
            End If
        Next
        Environment.Exit(134)
    End Sub
End Module
VB.NET: Dim Readings() … {40, 35, 52} has indexes 0 to 2, so To 3 is one too many. The program stops at line 5 (the lines after End Sub only print the message without this computer's folder names).
Run and checked before printing
Target = int(input("Target: "))
print("Target set to " + str(Target))
Python: the user typed fifty, which int() cannot convert.

Output

ERROR (exit 1):   File "<string>", line 1, in <module>     Target = int(input("Target: ")) ValueError: invalid literal for int() with base 10: 'fifty'
Run and checked before printing
Total = 0
Count = 0
print("Mean: " + str(Total / Count))
Python: a mean of no readings divides by zero.

Output

ERROR (exit 1):     print("Mean: " + str(Total / Count))                          ~~~~~~^~~~~~~ ZeroDivisionError: division by zero
Run and checked before printing
Module Program
    Sub Main()
        Dim Total As Integer = 0
        Dim Count As Integer = 0
        Console.WriteLine("Mean: " & Total / Count)
    End Sub
End Module
VB.NET does not stop here: / always works in real numbers, and 0 / 0 is NaN ('not a number'). Only \ (whole-number division) by zero stops the run.

Output

Mean: NaN
Run and checked before printing

Logic errors and trace output

Short code B4·4·17

def CountDry(Readings, Limit):
    Count = 0
    for Index in range(1, len(Readings)):
        if Readings[Index] < Limit:
            Count = Count + 1
        print("TRACE", Index, Readings[Index], Count)
    return Count

Readings = [28, 45, 12, 30, 61, 25]
print("Dry readings:", CountDry(Readings, 30))
Trace output added to the faulty CountDry. The first trace line is for index 1: index 0 (the reading 28) was never visited.

Output

TRACE 1 45 0
TRACE 2 12 1
TRACE 3 30 1
TRACE 4 61 1
TRACE 5 25 2
Dry readings: 2
Run and checked before printing
DEBUG = True

def CountDry(Readings, Limit):
    Count = 0
    for Index in range(0, len(Readings)):
        if Readings[Index] < Limit:
            Count = Count + 1
        if DEBUG:
            print("TRACE", Index, Readings[Index], Count)
    return Count

Readings = [28, 45, 12, 30, 61, 25]
print("Dry readings: " + str(CountDry(Readings, 30)))
The corrected CountDry, with its trace output behind a DEBUG constant: set it to false and the trace lines disappear without deleting any code.

Output

TRACE 0 28 1
TRACE 1 45 1
TRACE 2 12 2
TRACE 3 30 2
TRACE 4 61 2
TRACE 5 25 3
Dry readings: 3
Run and checked before printing

Using a debugger

Short code B4·4·18

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Find, fix and test again

Short code B4·4·19

def HighestReading(Readings):
    Highest = 0
    for Index in range(0, len(Readings) + 1):
        if Readings[Index] < Highest:
            Highest = Readings[Index]
    return Highest

print(HighestReading([28, 45, 12, 61, 30]))
HighestReading with only the colon added: it now translates, and stops at run time on index 5.

Output

ERROR (exit 1):     if Readings[Index] < Highest:        ~~~~~~~~^^^^^^^ IndexError: list index out of range
Run and checked before printing
def HighestReading(Readings):
    Highest = 0
    for Index in range(0, len(Readings)):
        if Readings[Index] < Highest:
            Highest = Readings[Index]
    return Highest

print(HighestReading([28, 45, 12, 61, 30]))
With the range corrected too, it runs to the end and returns 0. The logic error is still there.

Output

0
Run and checked before printing
def HighestReading(Readings):
    Highest = 0
    for Index in range(0, len(Readings)):
        if Readings[Index] > Highest:
            Highest = Readings[Index]
    return Highest

print(HighestReading([28, 45, 12, 61, 30]))
All three faults corrected: the highest of 28, 45, 12, 61 and 30 is 61.

Output

61
Run and checked before printing
public class Main {
    static int LowestReading(int[] Readings) {
        int Lowest = Readings[0];
        for (int Index = 1; Index < Readings.length; Index++) {
            if (Readings[Index] < Lowest) {
                Lowest = Readings[Index];
            }
        }
        return Lowest;
    }

    public static void main(String[] args) {
        int[] Readings = {28, 45, 12, 61, 30};
        System.out.println(LowestReading(Readings));
    }
}
The faded twin corrected (LowestReading), run on the same readings.

Output

12
Run and checked before printing

Part C: stubs and incremental testing

Short code B4·4·20

def ReadMoisture(Hour):
    # STUB: the sensor module is not written yet
    TestLevels = [45, 30, 29, 80]
    return TestLevels[Hour]

def WaterPlant():
    # STUB: the pump module is not written yet
    print("  STUB: WaterPlant called")

def NeedsWater(Level, Target):
    return Level < Target

for Hour in range(4):
    Level = ReadMoisture(Hour)
    print("Hour " + str(Hour) + ": level " + str(Level))
    if NeedsWater(Level, 30):
        WaterPlant()
Two stubs stand in for modules that do not exist yet. ReadMoisture returns planned test levels; WaterPlant only reports that it was called.

Output

Hour 0: level 45
Hour 1: level 30
Hour 2: level 29
  STUB: WaterPlant called
Hour 3: level 80
Run and checked before printing

Validation: presence and length checks

Short code B4·4·21

def GetPlantCode():
    while True:
        Code = input("Plant code: ")
        if Code == "":
            print("Nothing entered")
        elif len(Code) != 5:
            print("Must be 5 characters, not " + str(len(Code)))
        else:
            return Code

print("Accepted " + GetPlantCode())
Presence check, then length check, repeated until both pass. Inputs: nothing, AB12, ROSE12, ROSE1.

Output

Plant code: Nothing entered
Plant code: Must be 5 characters, not 4
Plant code: Must be 5 characters, not 6
Plant code: Accepted ROSE1
Run and checked before printing

Validation: type and range checks

Short code B4·4·22

def GetWholeNumber(Low, High):
    while True:
        Text = input("Enter " + str(Low) + " to " + str(High) + ": ")
        if Text == "":
            print("Nothing entered")
        elif not Text.isdigit():
            print("Not a whole number")
        elif int(Text) < Low or int(Text) > High:
            print("Out of range")
        else:
            return int(Text)

Target = GetWholeNumber(20, 80)
print("Target set to " + str(Target))
Presence, type and range checks in order. Inputs: nothing, fifty, 12.5, 85, 45.

Output

Enter 20 to 80: Nothing entered
Enter 20 to 80: Not a whole number
Enter 20 to 80: Not a whole number
Enter 20 to 80: Out of range
Enter 20 to 80: Target set to 45
Run and checked before printing
for Text in ["45", "-5", "12.5", ""]:
    print("[" + Text + "] " + str(Text.isdigit()))
isdigit() is true only when every character is a digit: a minus sign or a decimal point makes it false, and so does an empty string.

Output

[45] True
[-5] False
[12.5] False
[] False
Run and checked before printing
Module Program
    Sub Main()
        Dim Value As Integer
        For Each Text As String In {"45", "-5", "12.5", "fifty"}
            Console.WriteLine("[" & Text & "] " & Integer.TryParse(Text, Value))
        Next
    End Sub
End Module
VB.NET's Integer.TryParse accepts a minus sign, so -5 reaches the range check; it refuses 12.5 and fifty.

Output

[45] True
[-5] True
[12.5] False
[fifty] False
Run and checked before printing
def GetMinutes():
    while True:
        Text = input("Minutes (1 to 120): ")
        if Text == "" or not Text.isdigit():
            print("Enter a whole number")
        elif int(Text) < 1 or int(Text) > 120:
            print("Out of range")
        else:
            return int(Text)

print("Minutes: " + str(GetMinutes()))
The validation Mark Ladder's GetMinutes(). Inputs: nothing, ten, 0, 121, 90.

Output

Minutes (1 to 120): Enter a whole number
Minutes (1 to 120): Enter a whole number
Minutes (1 to 120): Out of range
Minutes (1 to 120): Out of range
Minutes (1 to 120): Minutes: 90
Run and checked before printing
import java.util.Scanner;

public class Main {
    static Scanner In = new Scanner(System.in);

    static int GetPercent() {
        while (true) {
            System.out.print("Percent (0 to 100): ");
            String Text = In.nextLine();
            if (!Text.matches("[0-9]+")) {
                System.out.println("Enter a whole number");
            } else if (Integer.parseInt(Text) > 100) {
                System.out.println("Out of range");
            } else {
                return Integer.parseInt(Text);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Percent: " + GetPercent());
    }
}
The faded twin's GetPercent(). Inputs: nothing, ten, 101, 0.

Output

Percent (0 to 100): Enter a whole number
Percent (0 to 100): Enter a whole number
Percent (0 to 100): Out of range
Percent (0 to 100): Percent: 0
Run and checked before printing
Module Program
    Sub Main()
        Dim Value As Integer
        Console.WriteLine(CInt("7.5"))
        Console.WriteLine(Integer.TryParse("7.5", Value))
    End Sub
End Module
VB.NET's CInt rounds a decimal without a word (7.5 becomes 8), while Integer.TryParse refuses it.

Output

8
False
Run and checked before printing
public class Main {
    public static void main(String[] args) {
        String Text = "99999999999";
        System.out.println(Text.matches("[0-9]+"));
        try {
            System.out.println(Integer.parseInt(Text));
        } catch (NumberFormatException E) {
            System.out.println(E.getMessage());
        }
    }
}
Java: eleven digits pass the digit test, but the number is too big for an int, so Integer.parseInt still throws NumberFormatException.

Output

true
For input string: "99999999999"
Run and checked before printing

Amending a program

Short code B4·4·23

Rejected = 0    # global INTEGER: inputs refused so far

def GetTarget():
    global Rejected
    Target = int(input("Target (20 to 80): "))
    while Target < 20 or Target > 80:
        Rejected = Rejected + 1
        print("Rejected " + str(Target) + ": out of range")
        Target = int(input("Target (20 to 80): "))
    return Target

Target = GetTarget()
print("Target set to " + str(Target) + " after " + str(Rejected) + " rejected")
The amended GetTarget() counts the inputs it refuses. The earlier test data is run again: the old lines are unchanged and the new count is right.

Output

Target (20 to 80): Rejected 85: out of range
Target (20 to 80): Rejected 19: out of range
Target (20 to 80): Target set to 20 after 2 rejected
Run and checked before printing

Command-word coach

Short code B4·4·24

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Workbook 4: Testing and evidence

Short code W4·4 · Practical Programming Task Book

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Starter files

Short code W4·4·K

Data files and skeleton code in Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.

Ask Z about Testing and evidence
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook