Created
June 5, 2017 12:40
-
-
Save fhanspach/0dfa96a790b46d628ff3f6e055112670 to your computer and use it in GitHub Desktop.
This file contains 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
import unittest | |
# Will this do what I expect? | |
def fibonacci(n): | |
"""Generates the n-th Fibonacci number. | |
The Fibonacci Numbers are always the sum of the previous numbers: | |
fib(0) = 0 | |
fib(1) = 1 | |
fib(3) = fib(2) + fib(1) | |
.. = (fib(1) + fib(0)) + fib(1) | |
.. = (1 + 0) + 1 | |
.. = 2 | |
""" | |
if n < 0: | |
raise ValueError("n must not be negative") | |
if n == 0: | |
return 0 | |
if n == 1: | |
return 1 | |
return fibonacci(n - 1) + fibonacci(n - 2) | |
# The tests can be run in PyCharm via right-click on the class "Run unittests in TestFibonacci" | |
# Note that all values in the tests are "hard-coded" - it should be as simple as possible and no code from the tested | |
# function should be used in the test. Always use the function as black-box! | |
# This should best be in another file e.g. test.py | |
class TestFibonacci(unittest.TestCase): | |
def test_fist_number(self): | |
fib_0 = fibonacci(0) | |
assert fib_0 == 0, "The first fibonacci number should be 0 but was {}".format(fib_0) | |
def test_10th_number(self): | |
fib_10 = fibonacci(10) | |
expected = 55 | |
assert fib_10 == expected, "The first fibonacci number should be {expected} but was {value}".format( | |
expected=expected, value=fib_10) | |
# This is very important since its an edge-case for the function | |
def test_negative(self): | |
"""Test if the function raises a ValueError for a negative argument""" | |
with self.assertRaises(ValueError): | |
fibonacci(-1) | |
# The @unittest.skip prevents the test from running. if its removed the test will run quite long :) | |
@unittest.skip("test_big_number is skipped because: This will run a long time") | |
def test_big_number(self): | |
fib_100 = fibonacci(100) | |
expected = 354224848179261915075 | |
assert fib_100 == expected, "The first fibonacci number should be {expected} but was {value}".format( | |
expected=expected, value=fib_100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment