Way to implement CI test to check if function argument is valid?

Let 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

If this makes sense so far

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 and am doing this from Travis-CI, is there anyway we can successfully do this from 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 possibly a fourth.

Where your pythonFunction.py file is, where your

foo(input) d dict 

Is inside. In that wrkDir create a file called tests.py:

import unittest

class TestPythonFunction(unittest.TestCase):
    ALL_DICT_REQUIREMENTS_ =(
        ('a', 1), 
        ('b', 2), 
        ('c', 3)
    )
   
    def test_dictFoo(self):
        from pythonFunction import foo
        for pattern in TestPythonFunction.ALL_DICT_REQUIREMENTS_:
            key = pattern[0]
            value = pattern[1]
            self.assertIs(foo(key), value)
        with self.assertRaises((KeyError)):
            foo('nonsenseKey')
    
if __name__ == '__main__':
    unittest.main()

In wrkDir run:

python tests.py

You may have to make sure the permissions are clear so run:

chmod u+x tests.py

The expected output from all this is:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

You’ll notice the above output is a lot like running a nosetest.

The tests.py exit code is 0 (all tests succeeded), or none 0 if some test failed, so you can control your Travis CI task accordingly:

python tests.py && git push || echo "Check tests for an error"

Another way is you could try as I stated earlier, using a nosetest via (this is from the top of my head):

install: "pip install coverage unittest2"
script: "nosetests --with-coverage --cover-package=pyiterable"

With this, you should be able to implement a CI job that checks to see if a function argument is valid.

-Montana
Travis CI Staff

thanks @Montana as usual, nose tests was an interesting way/angle of figuring this out

Imprint