0

假设我有一个 python 函数和字典,如下所示:

d = {"a": 1, "b": 2, "c": 3}
def foo(input):
    return d[input]

当我将代码推送到 GitHub 时(可能是某种持续集成),有没有办法检查所有调用是否foo仅使用 的一个键d作为input参数,如果有调用带有无效参数,则标记它还是发出警报?

例如:

foo("a") # no flag
foo("d") # flag/alert

我知道如何ValueError在运行时引发异常,但我正在寻找一个 CI 解决方案以包含在我们的 GitHub 工作流程中。现在我们正在使用 Travis-CI 进行自定义测试和 LGTM 提供的标准 CodeQL 测试。我研究过通过 LGTM 使用自定义 CodeQL,但我不太明白。我会很好地在这些持续集成中实现它或实现第三个。

4

1 回答 1

0

我们在您的 wrkDir 中,您的 pythonFunction.py 所在的位置,您的 foo(input), d dict 所在的位置。在那个 wrkDir 中创建文件 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()
    

在 wrkDir 中运行

python tests.py

预期输出:

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

OK

tests.py 退出代码为 0(所有测试成功),如果某些测试失败,则为无 0,因此您可以相应地控制 CI 任务,

python tests.py && git push || echo "Bad, check tests for error"
于 2020-09-09T16:27:13.250 回答