try:
print "Encoded is '%s'" % translator.encode(message)
except KeyError:
- print 'The input should be a string of a-z, A-Z, 0-9 or space'
+ print "The input should be a string of a-z, A-Z, 0-9 or space"
Exception is caught by the `except` block.
Can `raise` an exception e.g.
except KeyError:
- raise ValueError('The input should be a string of a-z, A-Z, 0-9 or space')
+ raise ValueError("The input should be a string of a-z, A-Z, 0-9 or space")
## Exercise: add runtime test for decode
Still time-consuming.
def test(self):
- print "SOS is ", self.encode('SOS')
- print "...---... is ", self.decode('... --- ...')
+ print "sos is ", self.encode("sos")
+ print "... --- ... is ", self.decode("... --- ...")
+ print "OK"
Extend UI.
Automate checking.
def test(self):
- assert '... --- ...' == self.encode('SOS')
- assert 'sos' == self.decode('... --- ...')
+ assert "... --- ..." == self.encode("sos")
+ assert "sos" == self.decode("... --- ...")
print "OK"
`assert` checks whether condition is true and, if not, raises an exception.
def test(self):
translator = MorseTranslator()
- assert '... --- ...' == translator.encode('SOS')
- assert 'sos' == translator.decode('... --- ...')
+ assert "... --- ..." == translator.encode("SOS")
+ assert "sos" == translator.decode("... --- ...")
+ print "OK"
if __name__ == "__main__":
test_translator = TestMorseTranslator()
test_translator.test()
- print "OK"
Remove test code from `MorseTranslator`.
Verbose, but equivalent, version of `test_encode_sos`.
def test_encode_sos(self):
- expected = '... --- ...'
- actual = self.translator.encode('SOS')
+ expected = "... --- ..."
+ actual = self.translator.encode("SOS")
assert expected == actual
## `nose` - a Python test framework
Examples.
- encode('sos')
- encode('')
- decode('')
- encode('1 + 2 = 3')
- decode('...---...')
+ encode("sos")
+ encode("")
+ decode("")
+ encode("1 + 2 = 3")
+ decode("...---...")
## Exercise: implement examples
def test_encode_illegal(self):
try:
- self.translator.encode('1 + 2 = 3')
+ self.translator.encode("1 + 2 = 3")
assert False
except KeyError:
assert True
from nose.tools import assert_raises
def test_encode_illegal(self):
- assert_raises(KeyError, self.translator.encode, '1 + 2 = 3')
+ assert_raises(KeyError, self.translator.encode, "1 + 2 = 3")
Testing components together:
- assert 'sos' == decode(encode('sos'))
- assert '... --- ...' == encode(decode('... --- ...'))
+ assert "sos" == decode(encode("sos"))
+ assert "... --- ..." == encode(decode("... --- ..."))
## Testing in practice
[Muon Ion Cooling Experiment](http://www.mice.iit.edu/) (MICE) - Bazaar version control, Python tests, Jenkins, [published online](https://micewww.pp.rl.ac.uk/tab/show/maus).
+[Apache Hadoop Common Jenkins dashboard](https://builds.apache.org/job/Hadoop-Common-trunk/)
+
## When 1 + 1 = 2.0000001
Computers don't do floating point arithmetic too well.