Book 4 · Chapter P4.4
Testing and evidence
B4·4This 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.
For the whole chapter
- Topic pageSoftware Development
B4·4·T - QuizSoftware Development
B4·4·Q1 - LabStructure charts
B4·4·X1 - LabState-transition diagrams
B4·4·X2 - LabTest data, validation & check digits
B4·4·X3
§12.3 Program testing · Program maintenance
Short code B4·4·1
- FlashcardsFlashcards §12.3: Testing, errors & maintenance
B4·4·F1 - Past-paper questionsPast-paper questions §12.3 (program-testing)
- Past-paper questionsPast-paper questions §12.3 (program-maintenance)
Testing on Paper 4
Short code B4·4·10
print("Start")
Level = 35
if Level < 40
print("Water now")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 ':'
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)))ValidLitres: every actual result matches the plan.Output
15 True 5 True 4 False 100 False
def ValidSeats(Seats):
return Seats >= 1 and Seats <= 8
for Seats in [4, 8, 9, 20]:
print(str(Seats) + " " + str(ValidSeats(Seats)))ValidSeats.Output
4 True 8 True 9 False 20 False
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)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
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)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
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))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
Part B: three kinds of error, in code
Short code B4·4·14
print("Start")
Total = 5
print(Totals)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'?
public class Main {
public static void main(String[] args) {
System.out.println("Start");
int Total = 5;
System.out.println(Totals);
}
}println.Module Program
Sub Main()
Console.WriteLine("Start")
Dim Total As Integer = 5
Console.WriteLine(Totals)
End Sub
End ModuleSyntax 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");
}
}
}= in a condition is an assignment, and an int cannot be a condition.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);
}
}for loop's closing brace is missing (after line 5), but the compiler reports line 8, the last line of the file.Module Program
Sub Main()
Dim Level As Integer = 35
If Level < 40 Then
Console.WriteLine("Water now")
End Sub
End ModuleIf with no End If. The message points at the If on line 4, not at the place the End If belongs.Run-time errors
Short code B4·4·16
Readings = [40, 35, 52]
for Index in range(4):
print(Readings[Index])Output
ERROR (exit 1): print(Readings[Index]) ~~~~~~~~^^^^^^^ IndexError: list index out of range
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]);
}
}
}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)
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 ModuleDim 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).Target = int(input("Target: "))
print("Target set to " + str(Target))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'Total = 0
Count = 0
print("Mean: " + str(Total / Count))Output
ERROR (exit 1): print("Mean: " + str(Total / Count)) ~~~~~~^~~~~~~ ZeroDivisionError: division by zeroModule Program
Sub Main()
Dim Total As Integer = 0
Dim Count As Integer = 0
Console.WriteLine("Mean: " & Total / Count)
End Sub
End Module/ 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
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))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
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)))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
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
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]))Output
0
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]))Output
61
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));
}
}LowestReading), run on the same readings.Output
12
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()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
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())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
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))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
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
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 ModuleInteger.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
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()))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
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());
}
}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
Module Program
Sub Main()
Dim Value As Integer
Console.WriteLine(CInt("7.5"))
Console.WriteLine(Integer.TryParse("7.5", Value))
End Sub
End ModuleCInt rounds a decimal without a word (7.5 becomes 8), while Integer.TryParse refuses it.Output
8 False
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());
}
}
}int, so Integer.parseInt still throws NumberFormatException.Output
true For input string: "99999999999"
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")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
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.


