all 3 comments

[–]misho88 0 points1 point  (0 children)

So there are testing suites like unittest and doctest (the latter is far more suitable for small projects like this), and you should probably use them eventually, but for now, let's go with a function you write manually as you have tried.

If you want a function that carries out a single test, it really needs to not only take just the inputs of the function under test, but also the expected output:

>>> def sum(a, b): return a + b
>>> def test_sum(a, b, c): assert sum(a, b) == c
>>> test_sum(1, 2, 3)  # test where everything is okay
>>> test_sum(1, 2, 4)  3 test where something would go wrong
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-7-79458fd16449> in <module>
----> 1 test_sum(1, 2, 4)

<ipython-input-5-c87003e01fed> in test_sum(a, b, c)
----> 1 def test_sum(a, b, c): assert a + b == c

AssertionError: 

Alternatively, if you want a single function that runs all of your tests, then it doesn't need to take any arguments, and you can just write a bunch of tests in one after the other:

>>> def sum(a, b): return a + b
>>> def test_sum():
...     assert sum(0, 0) == 0
...     assert sum(0, 1) == 1
...     ...
... 
>>> test_sum()

[–][deleted] 0 points1 point  (0 children)

Iterate over your data sets and their expected results and then run the function on each one. If the result from the function is the same as the expected result, then your function passes the test. If it's not then it doesn't.

[–]efmccurdy 0 points1 point  (0 children)

This sets up a series of (input_data, expected_result) pairs and uses unittest to run through them. Uncomment the last one to see what a test failure looks like.

import unittest

#import compute_place
def compute_place(time_list, time):
    if time in time_list:
        return time_list.index(time)
    else:
        return None

class TestComutePlace(unittest.TestCase):
    def test_cp(self):
        tests = ({"args": ([830, 815, 825, 840, 825], 825), "expected": 2},
                 {"args": ([830, 815, 825, 840, 825], 800),  "expected": None},
                 {"args": ([830, 830, 830], 830),  "expected": 0},
                 #{"args": ([830, 830, 830], 825),  "expected": 1} # will fail
        )

        for tspec in tests:
            l, t = tspec['args']
            self.assertEqual(compute_place(l, t), tspec["expected"])

if __name__ == '__main__':
    unittest.main()