OBJECTIVES
- Introduce the different types of errors that occur when programming.
- Show how to use exceptions to catch defective behaviour.
- Show how to apply defensive programming techniques.
- Explain how to test individual parts of a solution through unit testing.
- Introduce emergent aspects of a solution and how to test them.
- Explain how to test your solution as a whole through system testing and acceptance testing.
- Show methods for locating errors in your solution using logging and debuggers.
INTRODUCTION TO PROGRAM TESTING AND EVALUATION
There are many aspects to evaluating programs. A large part of evaluation deals with whether a solution actually solves the original problem without making errors. This is often done via testing, which is covered by one half of this chapter.
The other part of evaluation deals with whether a solution does its work well. This answers questions like: Is it stable? Does it perform well? Does it prevent unauthorised access? The remainder of this chapter covers these aspects of evaluation.
In both cases, since we’re dealing with programming, the work of evaluation can be automated, meaning we can write code to test other code. Along the way, this chapter will show how you can do such work in Python.
ANTICIPATING BUGS
Many bugs creep into programs long before testing or even coding happens. Mistakes made when designing a solution account for a great many errors discovered during testing.
All non-trivial programs contain bugs, even those written by experienced professionals. However, the number of bugs introduced is inversely proportional to the programmer’s diligence. By following good practices, you’ll greatly reduce the number of problems encountered during testing.
Techniques for anticipating bugs during design were first discussed in the Chapter 5 section, ‘Designing out the bugs’.
Syntax vs semantic errors
Before dealing with coding errors, you should ensure that you’re familiar with the types of errors you’ll face. Broadly speaking, errors fall into one of two types.
Syntax errors occur when you write a malformed statement that cannot be understood by the computer. The syntax of a language (and this includes human languages too) describes the rules that statements in that language must follow. The sentence ‘Orange: me penguin the lady’s-under draws’ is syntactically nonsense because it breaks numerous rules of English syntax. Similarly, source code is considered nonsensical if it doesn’t obey syntax rules.
It’s important to respect Python’s syntax. If you make mistakes, your programs won’t run. Visit these online resources to read and learn more about it:
-
Code Academy: https://www.codecademy.com/courses/introduction
-to-python-6WeG3/0/1 -
Wikipedia 2017: https://en.wikipedia.org/wiki/Python_
syntax_and_semantics
Each line of Python code in the following snippet contains a syntax error:
class VendingMachine
Error: Missing colon after class name
machine_name = SuperVendor VX-9000’
Error: Missing opening quote mark
def __init__(self
Error: Missing closing parenthesis
3rd_compartment = get_compartment(3)
Error: Variable names cannot begin with a number
When the computer tries to run a program containing syntax errors, it will immediately stop and report the problem. For example:
Fortunately, such errors are often easily fixable and you’ll commit them with increasing rarity as you gain experience.
Semantic errors occur when you write something that follows the rules of a language, but which is, nevertheless, invalid. A sentence like ‘the peanut eats the elephant’ is syntactically correct – for example, it follows the subject-verb-object form of English – but it makes no semantic sense. Peanuts, to the best of my knowledge, can’t eat elephants. The same principle applies in programming languages.
For example, is this code semantically correct?
x = y / Z
It’s certainly syntactically correct, but we can’t determine the meaning of the code until it’s executed with actual values. After all, what if y=42 and z=0 ? Division by zero is mathematical nonsense.
Whereas syntax errors in a program can be detected before any code is executed, semantic errors in Python can’t usually be detected until the computer attempts to execute the offending line of code. This means that a program may run successfully up to a point, but then fail partway through. If it does, a semantic error will cause a program to crash and print an error message, for example:
ZeroDivisionError is actually the name of a class. In fact, all errors result in some kind of error object being instantiated. When the computer tried to divide by zero in this example, it encountered this particular type of error and so created a new instance of ZeroDivisionError . It used this object to make an error message and then halted the program.
Dealing with semantic errors will absorb a much greater amount of your effort when dealing with defects.
Avoiding defects
Since semantic errors are usually only recognisable during execution, you have to make provisions for dealing with them by adding extra code to your program. Such code tells the computer what to do should errors occur. It’s a form of ‘safety’ code: it doesn’t contribute to the overall solution, but exists to prevent defects.
There are several good strategies to follow.
Catching potential errors
Exception: an error detected during execution of a program.
The built-in mechanism for dealing with exceptions in Python is the try block. It’s used to isolate a piece of code that you suspect might encounter (aka raise) an exception under certain conditions. It also provides a way to deal with the problem if one occurs.
This is the basic form of a try block:
If any code inside a try block causes an exception, then execution moves immediately to the first line of the following except block. This is known as catching the exception. If no exception occurs, the code in the except block is ignored.
For example, if your program includes a division, then it’s vulnerable to a division-by-zero error. Should this occur, you can prevent it from crashing your program by catching the exception:
This is only the most basic form of exception-handling in Python. Other considerations mean that the basic try block can be extended in several ways.
Exception-handling with try blocks is an optimistic approach. Essentially, the programmer says, ‘this bit of code might cause a problem, but let’s try it anyway and deal with the problem if one arises’. Use it in cases where errors are unlikely to occur, but can be recovered from if they do.
What if several different types of error could occur? Your block of code might potentially cause several different types of problem. Different types of problem usually need handling in different ways, which means the basic try block would be insufficient. Instead, Python allows you to catch specific types of exceptions and handle them differently. The type of exception is identified by the name of the exception’s class. You can add this name to an except clause to match an exception type to specific error-handling code. You can include as many such except clauses as you need.
While multiple types of exception could occur, Python will only ever raise a maximum of one exception at a time. Therefore, only one except block will be visited in the case of an error.
How should I deal with results of a potentially erroneous piece of code? Obviously, you could only report efficiency if it was successfully calculated. Actions that should only happen when no exceptions were raised can be put into an else block.
How do I perform actions regardless of whether an error occurred or not? Sometimes, certain instructions need executing independently of whether an error occurred. Let’s say that any connection to the car’s sensor system must be closed explicitly after use. So, an attempt must always be made to close a connection, regardless of what happened in the try block. For this, Python provides the finally block.
Defensive programming
The motivation behind defensive programming was first discussed in the Chapter 5 , section, ‘Mitigating errors’.
Whereas try blocks are an optimistic approach to error handling, some cases merit a more pessimistic approach. I don’t mean to say you should be guided by your own personality. Some situations – regardless of whether you’re a glass-half-full person – are simply better suited to a pessimistic approach. Errors that should never happen (and can’t be recovered from if they do) should be treated in this way.
This is also termed a defensive approach. It advocates always checking certain conditions before even attempting potentially erroneous actions. For example, the following function takes a reading from a temperature sensor in degrees Celsius and converts it into degrees Fahrenheit.
Physics tells us that absolute zero is (approximately) -273 Celsius and so a temperature measurement cannot read lower than that. If the function is given a value for celsius lower than -273, then something has gone very wrong. There’s nothing left for the function to do other than throw up its hands and announce, ‘Sorry, I can’t do that!’
The means for doing that is the raise keyword, which creates a new exception object and immediately returns execution back to the place where the function was called. In this case, the raise keyword instantiates the built-in ValueError . By raising its own exception, this function is declaring that it has encountered an irrevocable problem. So long as the exception is not caught somewhere else, the program will immediately halt with an error message:
You can reuse built-in exception types. A complete list of them is available here: https://docs.python.org/3/library/exceptions.html
VERIFICATION AND VALIDATION
Evaluation of a software solution comes down to answering two questions:
- Have we built the product right? This is called verification .
- Have we built the right product? This is called validation .
Verification covers mainly technical considerations. In other words, verification tells you whether or not you’ve built a good, high-quality solution. Software has many aspects to its quality. This means you can ask a variety of different questions during evaluation: Is it error-free? Is it reliable? Is it secure? And so on. Verification can be a lot of effort, but not every conceivable quality aspect necessarily applies to a solution. Therefore, it’s important to know which aspects are most relevant in your case, so you can focus on the most important ones. For example, security is not a concern for a typical video game, but performance is essential.
The original problem specification should mandate which aspects of quality are important in the eventual solution.
Validation is matter of whether or not the solution actually solves the original problem and is normally carried out in cooperation with the user. After all, it’s the user who will be applying the solution to their problem, so it’s ultimately up to them to validate the final result. A solution can pass verification with flying colours but still fail validation, usually due to a misunderstanding of the original problem specification. After all, an engineer could construct a truly exquisite footbridge, but if the client originally asked for a railway bridge it will fail validation.
Verification and validation happen in several stages throughout the creation of a solution. Those stages are examined in detail in the following two sections. To introduce them, Figure 12.1 gives a simple overview. The successive activities involved in creating a solution are connected by the solid arrows. The dashed arrows depict which types of testing test which activity (the activity on the right of the arrow tests the results of the activity on the left).
Figure 12.1 Stages of creating a solution and their corresponding testing phases
TESTING THE PARTS
This section discusses how to evaluate the individual parts of your solution by writing test cases.
Bottom-up testing was discussed in the Chapter 5 section, ‘Testing’, subsection ‘Approach.’
Testing the individual parts of a solution is to apply a bottom-up approach, which means beginning by verifying the smallest units of functionality first before moving onto testing larger pieces. It helps you to show that each part works by itself as expected. A key benefit of this approach is that it’s easy to localise the problem quickly, if something doesn’t work. However, it also means you have to build some ‘temporary scaffolding’ that simulates the behaviour of other parts in the system.
Unit tests were first discussed theoretically in the Chapter 5 section, ‘Testing individual parts.’
In a Python program, we take ‘parts’ to mean small, self-contained units of functionality like a function or class method. A part is tested by writing a number of unit tests that each verify some aspect of its functionality. You can write them using the built-in unit testing framework called unittest .
The unittest library is described here: https://docs.python.org/3/library/unittest.html
To create unit tests, first create a new file to contain your tests, then do the following for each test:
- Set up any supporting objects that the unit requires during the course of its work.
- State the expected results of the unit doing its work.
- Command the unit to carry out its work.
- Verify that the actual results match with the expected results.
- Clean up (aka tear down) any supporting objects you created.
Each unit test in a test case should verify one distinct piece of functionality.
Let’s start with something very simple. The following example tests the functionality of Python’s in-built list type:
Some remarks on this example:
- When the line unittest.main() is executed, every test method in TestPythonList (that is, every method with a name beginning ‘test’) gets run automatically.
- When a class inherits from unittest.TestCase , it gains access to a series of assertion methods. These can be used to test outcomes in various ways (some of them are contained in Table 12.1 ). If an assertion method finds something unexpected, then that particular test is reported as a failure. If no assertions fail, the test passes.
- Steps 1 and 5 from the earlier list (setting up and tearing down supporting objects) don’t appear in the last example because the use of lists requires nothing to be set up.
Table 12.1 A partial list of assertion methods
Assertion method | Remarks |
assertEqual(a, b) | Verifies that objects a and b are equal. |
assertNotEqual(a, b) | Verifies that objects a and b are not equal. |
assertTrue(s) | Verifies that the logical expression s is true. |
assertFalse(s) | Verifies that the logical expression s is false. |
Running this example produces the following output:
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
It shows that both tests passed because none of the assertions failed and no exceptions were raised.
To demonstrate set up and tear down methods, we’ll use a different example: a student record system. Under normal operation, this system stores records in a database. However, under test conditions, there is no database. Hence, a temporary one has to be created for the purpose of testing the system and then deleted after testing finishes.
The setup and teardown achieve the following:
- Before each test is executed, the system must be put into some kind of beginning state. In this example, a new database is created in preparation for the test by the setUp method. This is done automatically before each test begins execution.
- After each test is run, any data left over from a test should be cleaned up. This prevents the results of one test affecting the execution of another test, and removes clutter from the computer’s hard drive. In this example, the database is deleted. The tearDown method is run automatically after each test is completed.
TESTING THE WHOLE
In addition to testing the individual parts, you can test the solution as a whole. At this level, you divide your activities between verification and validation. I introduced these two concepts earlier in this chapter, with the essential difference between them summarised as:
- Verification ensures you’ve built a high-quality solution (aka ‘have I built the product right?’)
- Validation ensures you’ve built a solution that actually solves the original problem (aka ‘have I built the right product?’).
Verification (system testing)
Unit testing is valuable and necessary, but it can only show that the individual elements of a solution work as expected. When testing the whole, the aim is to make sure that several cooperating units work together to successfully deliver the solution’s key functionality. This kind of verification is called system testing.
It’s possible to write system tests in Python using the unittest module. As an example, consider a system that has several key pieces of functionality. Among them is the ability to provide login functionality, which allows only authorised people to use the system. This could involve several parts:
- The user interface displays a form for entering a username and password.
- A validator checks that the username and password are well-formed (for example, usernames must be between 3 and 16 characters in length, passwords must be greater than 8 characters in length).
- The authorisation component verifies that the username and password match those stored in the database.
The following code provides a glance into the actual system and shows that the UserInterface class works in concert with several other components that each provide their own functionality.
Next, we see the corresponding test case. It doesn’t test small, individual functions. It carries out a key piece of system functionality – which involves several cooperating parts from the solution – and verifies it works according to the system’s requirements.
Writing system tests in code like this is very helpful because a whole suite of tests can potentially be executed in mere seconds.
However, no better way to perform system testing exists than to use the complete system itself in the manner a user would. To keep your testing systematic, you should write and follow a test plan, as explained in Chapter 6 .
Manual test plans were discussed in Chapter 6 , section ‘Is it correct?’
In addition to correctness, your system will have many other emergent properties that affect how it behaves, like performance, stability, scalability and so on. Which properties are relevant will vary from project to project, but, whichever they are, you must verify they perform acceptably.
Let’s take performance as an example. Web-based systems support multiple users accessing them over the internet. This makes performance an important consideration because as the number of users increases, the system has to do more work to serve all their requests. When too many users access the system, it can appear to an individual user to slow down. Specifications for web-based systems should state up front the anticipated number of concurrent users. That way, the programmer can later verify that the system functions acceptably when at least this number of users logs on. ‘Functions acceptably’ would need defining in concrete terms, for example: maximum response time for 100 users is 7 seconds. 67 This performance measure can be verified via load testing (see Table 12.2 ).
A discussion of all aspects verified by system testing lies far out of scope for this book. There are just too many of them. 68 Furthermore, Python usually doesn’t provide built-in means to write such tests. Instead, you normally have to obtain third-party tools (some are listed in Table 12.2 ). For the example of load testing, you can use a tool that simulates multiple concurrent users by instructing it to send a specific number of concurrent requests to your running system and then to report on the response times it experienced. This report can then be used to verify whether your performance requirements are being met.
Learning Python Testing (Arbuckle, 2014) discusses testing specifically for Python programs.
Validation (acceptance testing)
Validation is the flip side of testing at the system level. It answers the question of whether the solution actually solves the original problem. It’s usually referred to as acceptance testing .
Table 12.2 Some example system properties and how to test them
Property | Remarks |
Performance | Measures responsiveness. Load testing verifies system performance under normal usage. An example tool for this is Locust ( https://locust.io/ ). |
Stability | Checks system performance when used beyond normal operational capacity to find its breaking point (stress testing). An example tool for this is Funkload ( https://funkload.nuxeo.org/ ) |
Security | Ensures that information stored by a system is properly protected from unauthorised access or modification. An example tool is Scapy ( https://www.secdev.org/projects/scapy/ ) |
Validation is a separate concern from verification. In fact, it’s perfectly possible for a system to pass verification but fail validation. 69 The reason is that, while system testing links back to the formal problem specification, acceptance testing links back to something altogether less formal: the user’s initial needs. If the user finds a solution insufficient for solving their problem, there’s little point in arguing. You simply have to take their feedback, use it to refine your understanding of the problem, and then make improvements. The customer is, as they say, always right.
A system can fail acceptance testing because the original problem was poorly understood and the resultant solution didn’t accurately represent the problem.
Like system verification, acceptance testing can be done either manually or automatically. It’s most important for users to validate a system manually themselves to ensure it solves their problems or meets their needs acceptably. This could be done in a fairly ad hoc way, by gathering users together and letting them use the system in their own way. Alternatively, it could be more formal and users could follow a script similar to the test plan (see Chapter 6 , Figure 6.1 ).
Automatic tools exist to help with validation. Perhaps the most-used approach is to write executable test code in a behaviour-driven development (BDD) style. This style requires you to produce something extra during initial problem analysis (in addition to a formal specification): a statement from the user called a user scenario , describing how the eventual solution should solve their problem. Later, during acceptance testing, you can draw a link between parts of the user scenario and their implementation in code. It’s particularly suited to acceptance testing, since the user (who may be unable to write software) can collaborate with the programmer on writing tests because the descriptions are written in natural language (albeit language that follows certain conventions).
Python doesn’t provide support for BDD out of the box, but several BDD add-ons exist, one of which is called Behave. It conforms to the typical approach taken by BDD tools, namely that writing an acceptance test includes two parts:
- Write a step-by-step natural language description of how a feature should behave (the user’s job).
- Write source code that tests each step of the process (the programmer’s job).
Find out more on Behave here: https://pythonhosted.org/behave/
A description follows the following format:
A typical description might read something like this:
A test that validates this expectation would look something like this:
When the test runs, Behave matches each step in the description to the relevant function in the test. The context object holds data that persist throughout the course of the test and are passed automatically to each function. When you feed these test files to the Behave tool, it will produce output something like this:
If you want to automate part of your acceptance testing using Behave, I recommend you begin with the official tutorial: https://pythonhosted.org/behave/tutorial.html .
Don’t wait until the system is completed to perform acceptance testing. If your solution proves to be unacceptable, you may have a lot of rework to do in very little time. Having users test incomplete but working versions early (for example, via alpha and beta testing) will give you some validation and help to steer the work if necessary.
DEBUGGING
Chapter 5 described debugging as an activity carried out to locate the cause of defects in software and discussed several debugging strategies. This section focuses on the tools available for putting into practice some of those strategies.
Using logs
Logging was first discussed in the ‘Debugging’ section of Chapter 5 .
Logging allows you to instruct the computer to record messages at certain points throughout program execution. If you add such instructions at sensible points in the source code, the computer will automatically leave behind a trail of messages (that is, a log).
A log is intended for the programmer’s eyes rather than the user’s, so it can contain as much technical detail as you like.
Logs can’t tell you everything that happened. Like a detective following a trail of clues, you can follow a trail of log messages and reconstruct the circumstances of a program failure. With luck, you’ll solve the mystery.
Logs are particularly helpful in the following situations:
- recording the values of variables at certain points during execution;
- informing you whether certain instructions were actually executed or not;
- reporting information about an exception (you can put detailed log messages inside an except block);
- recording details of significant events, like updates to a database or failed login attempts.
When using Python, you should avoid using the print function to output log messages and you certainly shouldn’t bother creating your own logging solution. The standard logging module (called logging, staggeringly enough) should serve just fine.
The official guide to Python’s logging module is available here: https://docs.python.org/3/howto/logging.html .
For each log message, the logging module allows you to choose:
- its location;
- its severity.
With regards to location , Python prints log messages to the console by default. That usually suffices during initial development of the program, but later (after the completed program is given to the users) the programmer can’t be there to read the console output as it appears. If something goes wrong during usage, the user probably won’t know the cause, so it’ll be up to the programmer to work out what went wrong. Their detective work will be rendered so much easier by having the logs. For these situations, configure the logging module to write messages to a file instead (which can be recovered from the user’s computer in the event of a problem) like so:
import logging
logging.basicConfig(filename=’log.txt’)
Different events might merit different levels of concern. This is where severity comes in. For example, a user failing a password check three times in a row might be interesting, but is less severe than, say, a database failure. The logging module allows you to report each event at an appropriate level of severity. Table 12.3 shows the available levels.
Table 12.3 Debug levels and appropriate times to use them
Level | In which cases the level should be used |
DEBUG | Very detailed information, interesting only when diagnosing a problem. |
INFO | Events that confirm things are working as expected. |
WARNING | Things are working as expected, but something happened that might be problematic. |
ERROR | A problem occurred and the program was unable to carry out some specific piece of work. |
CRITICAL | A serious problem occurred, which probably means the program cannot continue running. |
Each level corresponds to an appropriately named method in the logging module. The following code includes examples of each level:
One thing to note: in the print_as_fahrenheit function, the call to logger.error includes the parameter exc_info=True . This automatically adds very detailed information about an exception to the log message, including the file name and line number where the problem occurred.
If your program prints a lot of log messages or runs for a long time, then the log will end up highly voluminous. Making your logger output the date and time of each message can help you to locate the message you want.
To do this, use the format parameter when configuring the logger, like so: logging.basicConfig(format=’%(asctime)s %(message)s’) .
This produces a log message like this: 10/11/2016 10:23 AM Less than 1 GB of disk space remaining!
Using a debugger
Logs leave a trail of clues behind. These messages can help you to form a hypothesis about what happened during a failure. Alternatively, using a debugger shows you a dynamic, moment-by-moment replay of what the computer did during a failure.
If using a log is like reading a newspaper account of a football match, debugging is like watching an interactive action replay. You get to see what happened, step by step, from a viewpoint of your own choosing, as often as you like. At any time, you can display key information about the things involved.
This section demonstrates the basics of a debugger using Python’s built-in debugger (called pdb ). While a debugger provides many features, we’ll focus on:
- starting the debugger with your own programs;
- executing a program step by step;
- displaying values at a certain point in execution.
The Python Debugger is described in Wiki Python, (2017). See: https://docs.python.org/3/library/pdb.html .
Let’s start simple and debug a very small program called my_ program.py :
x = 1
y = 2
x = x + y
print(x)
To start the program under control of the debugger, run it from the command prompt like so:
python -m pdb my_ program.py
Execution of my_ program.py begins but it immediately halts at the first line of code. The debugger is now waiting for you to tell it what to do. Whenever the debugger is waiting, the prompt looks something like this:
> /home/me/my_ program.py (1)<module>()
-> x = 1
(Pdb)
- The first line tells you which file the code currently being executed is in.
- The second line shows the next line to be executed.
- The third line is the prompt, telling you that the debugger is waiting for your command.
By itself, the second line might not give you much of a feel for where execution has reached. You can get a better feel by commanding the debugger to print the surrounding lines of code. Do this by typing ‘ l ’ (for ‘list’) and enter:
To execute the next line, type ‘ n ’ (for ‘next’) and enter:
(Pdb) n
> /home/me/my_ program.py (2)<module>()
-> y = 2
(Pdb)
As you can see, execution moved onto line 2. To be sure that x currently has its expected value, you can tell the debugger to print it out. Type ‘ p x ’ (‘ p ’ is short for ‘print’).
(Pdb) p x
1
(Pdb)
The variable y hasn’t yet been created at this point. If you try to print it out, the debugger would raise an exception:
(Pdb) p y
*** NameError: name ‘y’ is not defined
(Pdb)
But if we execute the next step and then print it out, we’ll have more luck:
(Pdb) n
> /home/me/my_ program.py (3)<module>()
-> x = x + y
(Pdb) p y
2
(Pdb)
For longer programs, you might potentially have to step through dozens or even hundreds of instructions to reach the ones you want to debug. Instead of slogging through all these instructions, you can instead instruct the debugger to execute a program normally up until a certain point (called a breakpoint ). When the debugger reaches this breakpoint, it will immediately pause execution and give you the (Pdb) prompt. To achieve this, you have to amend your program slightly.
For example, if you wish to skip over the first two instructions of the previous program and start debugging at line 3 ( x = x + y ), you need to establish this line as the breakpoint. To do this, alter the program like so:
import pdb # Import the debugger module.
x = 1
y = 2
pdb.set_trace() # Tell the debugger to pause at the following line.
x = x + y
print(x)
Since this module now imports the pdb module, you no longer need to include it when starting Python (hence, you can run it in the usual way):
$ python3 test.py
> /home/me/my_ program.py (6)<module>()
-> x = x + y
(Pdb)
The debugger has executed the first two lines as normal. After executing the line pdb.set_trace() , it has broken into debugger mode and is now awaiting your command.
Happy debugging!
During a debugging session, you can type help for a full list of debugger commands.
GUI-based debuggers exist, which beginners will find more user-friendly. For a list of debugging tools available see https://wiki.python.org/moin/PythonDebuggingTools
SUMMARY
Bugs are a fact of life in programming. Fortunately, as we’ve seen in this chapter, there are ways to combat them.
First, you can deal with them from within your program. You can anticipate them by using exceptions to catch errors before they manifest to the user. Or, you can be more conservative and apply defensive programming techniques to make sure your program executes only under strict preconditions.
Despite your efforts during coding, some bugs will remain. The approach then is to use testing to hunt the bugs down and remove the ones you find. You can test the individual parts of your program (unit testing) or test it as a whole (system testing). Logging and debuggers are tools to assist you in the hunt.
But bugs are just one aspect of testing. Your program doesn’t just have to work; it has to work well. These are the non-functional aspects of your system. Your problem dictates which aspects are the important ones to worry about.
EXERCISES
EXERCISE 1
Mark the following statements as true or false:
- A syntax error will not be reported until the line containing it is executed.
- Code in a finally block is always executed after the code in its corresponding try block.
- Validation determines whether or not a solution actually solves the original problem.
- The setUp function in a Python unit test is executed once before each individual test function.
- By default, Python prints log messages to a file called log.txt .
EXERCISE 2
Look back at your answer for Chapter 5 , Exercise 5 (write an algorithm for checking a number in the FizzBuzz game). Turn your algorithm into a Python program.
EXERCISE 3
Write a unit test for your FizzBuzz program. Make sure it tests all the equivalence classes identified in Chapter 5 (section ‘Testing individual parts’).
EXERCISE 4
The following code implements a very simple Hangman game:
When you play it, it should look something like this:
Enter a letter, or 0 to give up: u
u____u______
Enter a letter, or 0 to give up: e
u__e_u_____e
Enter a letter, or 0 to give up: t
u__e_ut____e
Enter a letter, or 0 to give up:
However, the code has a few bugs in it. Try the program out and, using a debugger and/or log messages, find and fix the problems.