Reputation: 165
Let's say I have a python function and dictionary as follows:
d = {"a": 1, "b": 2, "c": 3}
def foo(input):
return d[input]
Is there a way when I push my code to GitHub (presumably with some sort of continuous integration) to check that all calls of foo
only use one of the keys of d
as the input
argument, and if there is a call with an invalid argument, to flag it or raise an alert?
For example:
foo("a") # no flag
foo("d") # flag/alert
I know how I would raise an exception or ValueError
at runtime, but I'm looking for a CI solution to include in our GitHub workflow. Right now we are using Travis-CI for our custom tests and the standard CodeQL tests provided by LGTM. I looked into using custom CodeQL via LGTM, but I couldn't quite figure it out. I'd be fine implementing it in either of those continuous integrations or implementing a third.
Upvotes: 0
Views: 251
Reputation: 361
we are in your wrkDir where your pythonFunction.py is, where your foo(input), d dict is inside. In that wrkDir create file tests.py:
import unittest
class TestPythonFunction(unittest.TestCase):
# define here all required cases
ALL_DICT_REQUIREMENTS_ =(
('a', 1),
('b', 2),
('c', 3)
)
def test_dictFoo(self):
# pythonFunction reflects to your pythonFunction.py
from pythonFunction import foo
# test all required patterns
for pattern in TestPythonFunction.ALL_DICT_REQUIREMENTS_:
key = pattern[0]
value = pattern[1]
self.assertIs(foo(key), value)
# test function is raising error if key doesn't exists
with self.assertRaises((KeyError)):
foo('nonsenseKey')
if __name__ == '__main__':
unittest.main()
In wrkDir run
python tests.py
expexted output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
The tests.py exit code is 0 (all tests succeeded), or none 0 if some test failed, so you can control your CI task accordingly,
python tests.py && git push || echo "Bad, check tests for error"
Upvotes: 0