In this part of the assignment, you will write tests for your solutions in Part 1.
We use testing to help us feel confident that the programs we write are correct. Testing involves calling the functions you wrote with some input and comparing the output with some expected value.
We have provided a function called assert_equals
that takes an expected value and the value returned by your function, and compares them: if they don't match, the function will crash the program and tell you what was wrong. The starter file hw1_test.py
shows how to test a dummy-function we included in your starter file for hw1.py
using assert_equals
.
Here is the code that we want to test:
def funky_sum(a, b, mix):
"""
Returns a mixture between a and b.
If mix is 0, returns a. If mix is 1, returns b. Otherwise returns a linear
interpolation between them. If mix is outside the range of 0 and 1, it is
capped at those numbers.
"""
if mix < 0:
return a
elif mix > 1:
return b
else:
return (1 - mix) * a + mix * b
And the tests we provided:
def test_funky_sum():
"""
Tests the funky_sum function
"""
print('Testing funky_sum')
# Cases from the made up "spec" for this problem
assert_equals(1, hw1.funky_sum(1, 2, 0))
assert_equals(2, hw1.funky_sum(1, 2, 1))
assert_equals(1.5, hw1.funky_sum(1, 2, 0.5))
assert_equals(1.33, hw1.funky_sum(1, 2, 0.33))
# edge cases to test the 0 check
assert_equals(1, hw1.funky_sum(1, 2, -1))
assert_equals(1, hw1.funky_sum(1, 2, -0.1))
assert_equals(1.01, hw1.funky_sum(1, 2, 0.01))
# edge cases to test the 1 check
assert_equals(2, hw1.funky_sum(1, 2, 2))
assert_equals(2, hw1.funky_sum(1, 2, 2.1))
assert_equals(1.99, hw1.funky_sum(1, 2, 0.99))
def main():
test_funky_sum()
if __name__ == '__main__':
main()
We can't just call funky_sum
in this test file since they live in different files. Instead, we have to prefix it with hw1.funky_sum
so it knows which file to look at. You do not need to understand how imports work yet, just know that you will need to use this syntax to call the functions you define in your hw1.py
.
Notice that in the code for funky_sum
there is a condition about < 0
and > 1
. These give good indications of what you might want to test for since they are a "boundary condition" (i.e. a place where changing the input causes the program to execute differently). You can't possibly test all values, but testing these cases that are most likely to be wrong can be very helpful in helping you develop a good test suite. It's never a bad idea to leave in-line comments like we did above to make it easier for someone reading your tests to understand what each of the tests is trying to do.
For this part of the assignment, you are to add functions to hw1_test.py
to test all the functions that you wrote for Part 1.
For full credit, your hw1_test.py
must satisfy all of the following conditions:
hw1.py
that you were asked to write.assert_equals
.test_funky_sum
).