Skip to content

Instantly share code, notes, and snippets.

@dbgarf
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbgarf/9898103 to your computer and use it in GitHub Desktop.
Save dbgarf/9898103 to your computer and use it in GitHub Desktop.
# re is the python regular expression module. its very powerful and worth learning.
import re
# unittest is the built in testing module. good for simple use cases like this.
from unittest import TestCase, TestLoader, TestResult
# compiling the regex pattern ahead of time, which adds significant speed
vowel_pattern = re.compile(r'[AEIOUaeiou]')
def is_vowel(char):
# raising errors for invalid input is a good idea
# pythonic design principle: let the thing crash early and often, and with a helpful error message
if len(char) > 1:
raise ValueError('char had length greater than 1')
if vowel_pattern.match(char):
return True
return False
def remove_vowels(string):
return re.sub(vowel_pattern, '', string)
class VowelTestCase(TestCase):
def test_is_vowel(self):
vowels = 'AEIOUaeiou'
consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
not_letters = ";?<%&"
# positive test
for letter in vowels:
self.assertTrue(is_vowel(letter))
# negative test
for letter in consonants:
self.assertFalse(is_vowel(letter))
# strange test
# sometimes its a good idea to test against weird inputs that are outside of what you would normally use the function for
# strictly speaking though only the positive and negative test are necessary
for letter in not_letters:
self.assertFalse(is_vowel(letter))
def test_remove_vowels(self):
string_with_vowels = "The quick brown fox jumped over the lazy brown dog."
string_without_vowels = "Th qck brwn fx jmpd vr th lzy brwn dg."
# positive test
self.assertEqual(remove_vowels(string_with_vowels), string_without_vowels)
# negative test
self.assertNotEqual(remove_vowels(string_with_vowels), string_with_vowels)
# __name__ called at the module level refers to the name of the module itself, i.e. the filename
# a python file called from the command line automatically gets the name "__main__"
# this if __name__ == "__main__" construct is a common way to make a Python script executable from the shell
# e.g. user@host$: python script.py
if __name__ == "__main__":
# this is a simple way to set up a unit test runner
result = TestResult()
suite = TestLoader().loadTestsFromTestCase(VowelTestCase)
suite.run(result)
# console output stuff
print "TESTS: %d" % (result.testsRun)
print "ERRORS: %d" % len(result.errors)
for error in result.errors:
print error
print "FAILURES: %d" % len(result.failures)
for failure in result.failures:
print failure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment