I tried to initiate myself with unit testing the simplest way I can. What do you think of this way to begin with? Is it a clean way to proceed? Are there any major caveats to avoid?
NB:
- Since I want to test a small script for each leetcode problem, I preferred to have the
Test
inside the script to be tested (and not in a different file). - I decided to use
f
as a global variable inside the main scope (I could have defined it inTest
as a class variable and useself.f
). - I create a function test for each case.
import unittest
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if __name__ == '__main__':
import unittest
f = Solution().islandPerimeter
class Test(unittest.TestCase):
def test_multiple_path(self):
self.assertEqual(f( [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]), 16)
def test_one_square(self):
self.assertEqual(f( [[1]]), 4)
unittest.main()
tests
in your project's root. This way, tools likepytest
will automagically find and run appropriate tests. \$\endgroup\$doctest
to embed the tests within the function's docstring. \$\endgroup\$