Created
December 13, 2018 15:38
-
-
Save Kukanani/51a36c7690eab3258c753c1c651e1141 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# License: BSD | |
# Copyright: Adam Allevato 2018 | |
# | |
# FizzBuzz example program and associated tests. | |
# | |
from cStringIO import StringIO | |
import sys | |
def main(): | |
fizz_buzz() | |
class Capturing(list): | |
""" | |
Captures command line output into a variable. Used for unit tests. See: | |
https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call | |
""" | |
def __enter__(self): | |
self._stdout = sys.stdout | |
sys.stdout = self._stringio = StringIO() | |
return self | |
def __exit__(self, *args): | |
self.extend(self._stringio.getvalue().splitlines()) | |
del self._stringio # free up some memory | |
sys.stdout = self._stdout | |
def fizz_buzz(): | |
""" | |
Print the numbers 1-100, but with multiples of 3 replaced by | |
"Fizz" and multiples of 5 replaced by "Buzz". | |
""" | |
for idx in range(100): | |
s = "" | |
i = idx + 1 | |
if i % 3 == 0: | |
s += "Fizz" | |
if i % 5 == 0: | |
s += "Buzz" | |
# if the string is empty, not divisible by 3 or 5, | |
# so print the number itself. | |
if s == "": | |
s += str(i) | |
print(s) | |
def test(): | |
""" | |
FizzBuzz unit tests. | |
""" | |
print("="*30) | |
print("running tests...") | |
with Capturing() as out: | |
fizz_buzz() | |
# note off-by one indices | |
assert(out[2] == "Fizz") # 3 | |
assert(out[98] == "Fizz") # 99 | |
assert(out[0] == "1") # etc. | |
assert(out[4] == "Buzz") | |
assert(out[14] == "FizzBuzz") | |
assert(out[99] == "Buzz") | |
assert(out[22] == "23") | |
print("all tests passed.") | |
print("="*30) | |
if __name__ == "__main__": | |
test() | |
print("press enter to run program") | |
_ = raw_input() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment