In this module, we will focus on testing our code.
Read the following articles from The Hitchhiker's Guide to Python:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO') # Edit FOO to see fail output
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5 #Fails, since inc(3) is 4, not 5
def square(x):
"""Return the square of x.
>>> square(2)
4
>>> square(-2)
4
"""
return x * x
if __name__ == '__main__':
import doctest
doctest.testmod() # Expect no output if everything passes
Here are more thorough examples using doctest
Sample exercises from CSC108:
Link to your code to show us something special you did with either encryption or testing or both!
Assignment 4: April 26 2019
This work and other materials under
github.com/ICS4U-ICS4C,
are licensed under Creative Commons Attribution 4.0 Int'l License.