Hacking Secret Ciphers with Python

(Ann) #1
Chapter 10 – Programming a Program to Test Our Program 151

Line 29 tests if message and decrypted are equal. If they aren’t, we want to display an error
message on the screen. We print the key, message, and decrypted values. This information
could help us figure out what happened. Then we will exit the program.


Normally our programs exit once the execution reaches the very bottom and there are no more
lines to execute. However, we can make the program exit sooner than that by calling the
sys.exit() function. When sys.exit() is called, the program will immediately end.


But if the values in message and decrypted are equal to each other, the program execution
skips the if statement’s block and the call to sys.exit(). The next line is on line 34, but you
can see from its indentation that it is the first line after line 9 ’s for loop.


This means that after line 29’s if statement’s block, the program execution will jump back to
line 23’s for loop for the next iteration of that loop. If it has finished looping, then instead the
execution jumps back to line 9’s for loop for the next iteration of that loop. And if it has
finished looping for that loop, then it continues on to line 34 to print out the string
'Transposition cipher test passed.'.


transpositionTest.py



  1. If transpositionTest.py is run (instead of imported as a module) call




  2. the main() function.



  3. if name == 'main':

  4. main()


Here we do the trick of checking if the special variable name is set to 'main' and if
so, calling the main() function. This way, if another program imports transpositionTest.py, the
code inside main() will not be executed but the def statements that create the main()
function will be.


Testing Our Test Program


We’ve written a test program that tests our encryption programs, but how do we know that the
test program works? What if there is a bug with our test program, and it is just saying that our
transposition cipher programs work when they really don’t?


We can test our test program by purposefully adding bugs to our encryption or decryption
functions. Then when we run the test program, if it does not detect a problem with our cipher
program, then we know that the test program is not correctly testing our cipher programs.


Change transpositionEncrypt.py’s line 36 from this:


transpositionEncrypt.py
Free download pdf