Best practices in software engineering

Final exercise

We've now covered all the topics on this course so to finish off, work through this final exercise. It is designed to give you a chance to practise what you've learned on some new code.

Make a new directory called crypto. In the Terminal change to that directory with cd crypto and in the Python Console change there with %cd crypto. In that directory make two new files called and
# A lookup dictionary which, given a letter will return the morse code equivalent
_letter_to_morse = {'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 
                   'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 
                   'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
                   'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
                   '0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
                   '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
                   ' ':'/'}

# This will create a dictionary that can go from the morse back to the letter
_morse_to_letter = {}
for letter in _letter_to_morse:
    morse = _letter_to_morse[letter]
    _morse_to_letter[morse] = letter

def encode(message):
    morse = []

    for letter in message:
        letter = letter.lower()

    # We need to join together Morse code letters with spaces
    morse_message = " ".join(morse)
    return morse_message

def decode(message):
    english = []

    # Now we cannot read by letter. We know that morse letters are
    # separated by a space, so we split the morse string by spaces
    morse_letters = message.split(" ")

    for letter in morse_letters:

    # Rejoin, but now we don't need to add any spaces
    english_message = "".join(english)
    return english_message
from morse import encode, decode

def test_encode():
    assert encode("SOS") == "... --- ..."

This module is designed to convert message to and from Morse code. It provides one function which takes an English message and converts it to a Morse code string, separated by spaces and another function which takes the Morse code string and converts it to English.


  • Add documentation to the morse module and to the encode and decode functions. Make sure you detail the inputs, outputs and give an example of their usage. Look at the tests to get an idea of how it works or try importing morse in the Python Console and have a play with the functions to understand them.



  • Add a test for the decode function to and check it passes with pytest
  • Parametrise both tests to give several examples
    • Make sure you include upper and lower case letters as well as checking what happens if you pass in empty strings
  • Make sure to use --doctest-modules to run the documentation examples that you added in the last exercise
  • Hint: When writing doctests, it cares whether your test output uses single or double quotes (' or "). Use single quotes for doctest outputs.



  • What happens if you pass in the string "Don't forget to save us" to encode?
    • Hint: The problem is caused by the ' in the string
  • Edit to raise a ValueError in this situation instead.
  • Write a test to make sure that the ValueError is raised when a string with a ' is passed in.
  • Parametrise that test with some other examples including the & and £ characters.


Another cypher

Let's add another text cypher to our crypto package. This time we will implement the Caesar Cipher or ROT13. Once more the module will provide encode and decode functions:
import string

_lower_cipher = string.ascii_lowercase[13:] + string.ascii_lowercase[:13]
_upper_cipher = string.ascii_uppercase[13:] + string.ascii_uppercase[:13]

def encode(message):
    output = []
    for letter in message:
        if letter in string.ascii_lowercase:
            i = string.ascii_lowercase.find(letter)
        elif letter in string.ascii_uppercase:
            i = string.ascii_uppercase.find(letter)
    return "".join(output)

def decode(message):
    output = []
    for letter in message:
        if letter in _lower_cipher:
            i = _lower_cipher.find(letter)
        elif letter in _upper_cipher:
            i = _upper_cipher.find(letter)
    return "".join(output)


  • Add documentation for the rot13 module.


This time the tests are provided for you. Copy this into a new file called
import pytest

from rot13 import encode, decode

@pytest.mark.parametrize("message, expected", [
    ("SECRET", "FRPERG"),
    ("secret", "frperg"),
def test_encode(message, expected):
    assert encode(message) == expected

@pytest.mark.parametrize("message, expected", [
    ("FRPERG", "SECRET"),
    ("frperg", "secret"),
def test_decode(message, expected):
    assert decode(message) == expected

def test_encode_spaces_error():
    with pytest.raises(ValueError):
        encode("Secret message for you")

When we run these tests with pytest we see that there are some passes and some failures:

pytest -v
=================== test session starts ====================
platform linux -- Python 3.8.5, pytest-6.0.1, py-1.9.0, pluggy-0.13.1 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /home/matt/projects/courses/software_engineering_best_practices
plugins: requests-mock-1.8.0
collected 5 items                                  [SECRET-FRPERG] PASSED     [ 20%][secret-frperg] PASSED     [ 40%][FRPERG-SECRET] PASSED     [ 60%][frperg-secret] FAILED     [ 80%] FAILED       [100%]

========================= FAILURES =========================
________________ test_decode[frperg-secret] ________________

message = 'frperg', expected = 'secret'

    @pytest.mark.parametrize("message, expected", [
        ("FRPERG", "SECRET"),
        ("frperg", "secret"),
    def test_decode(message, expected):
>       assert decode(message) == expected
E       AssertionError: assert 'SECRET' == 'secret'
E         - secret
E         + SECRET AssertionError
_________________ test_encode_spaces_error _________________

    def test_encode_spaces_error():
        with pytest.raises(ValueError):
>           encode("Secret message for you")
E           Failed: DID NOT RAISE <class 'ValueError'> Failed
================= short test summary info ==================
FAILED[frperg-secret] - Assert...
FAILED - Failed: ...
=============== 2 failed, 3 passed in 0.10s ================


There are two failing tests:

  1.[frperg-secret] is failing due to a bug in the code. Find the bug in and fix it so that the test passes.
  2. is failing due to a missing feature in our code. At the moment any spaces in the string are ignored. Change encode and decode in so that they raise an error if any letter in the message is not found in the lookup string.
    • Hint: You should add an else to the if/elif blocks



  • Add a test to both and which checks for "round-tripping". That is, check that a valid message which is passed to encode and then the output of that is passed to decode gets you back the original message.
  • What types of messages do not round-trip correctly in morse? What could you do to the test to make it pass?