[英]Python: Correct way to test whether function/method signature has changed
I am currently developing an application ( my_app
) that uses logic from another python package ( internal_package
), that is being developed in parallel.我目前正在开发一个应用程序 (
my_app
),该应用程序使用来自另一个 python package ( internal_package
) 的逻辑,该应用程序正在并行开发。
Lets say I use a function func1
from internal_package
in my code.假设我在我的代码中使用了来自
internal_package
的 function func1
。 In internal_package
, it is defined like this:在
internal_package
中,它是这样定义的:
def func1(a, b):
# do something
...
However, If the function signature of func1
(ie the parameters with which the function is called) changes, lets say to但是,如果
func1
的 function 签名(即调用 function 的参数)发生变化,可以说
def func1(a, b, c):
# do something
...
My code would of course raise an Exception, since I did not pass parameter c
.我的代码当然会引发异常,因为我没有传递参数
c
。
To become aware of that immediately, I want to write a test in pytest.为了立即意识到这一点,我想在 pytest 中编写一个测试。 In my understanding, this kind of test is not a unit test, but an integration test.
在我的理解中,这种测试不是单元测试,而是集成测试。
My approach would be something like this:我的方法是这样的:
import inspect
import internal_package
def test_func1_signature():
expected_signature = ? # not sure how to correctly provide the expected signature here
actual_signature = inspect.signature(internal_package.func1)
assert actual_signature == expected_signature
I would expect this to be a common issue, but I was not able to find anything related.我希望这是一个常见问题,但我找不到任何相关内容。 What would be the most pythonic way of performing this sort of test?
执行此类测试的最 Pythonic 方式是什么?
In case anyone is interested, I ended up using getfullargspec
from the inbuilt inspect
library.如果有人感兴趣,我最终使用了内置
inspect
库中的getfullargspec
。 In the documentation it says:在文档中它说:
Get the names and default values of a Python function's parameters.
获取 Python 函数参数的名称和默认值。 A named tuple is returned:
FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
返回一个命名元组:
FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
As I am interested in in the args
part, I retrieve them from func1
as follows:因为我对
args
部分感兴趣,所以我从func1
中检索它们,如下所示:
inspect.getfullargspec(func1)[0]
Which then returns ['a', 'b']
.然后返回
['a', 'b']
。 I can then write a simple test in pytest like this:然后我可以像这样在 pytest 中编写一个简单的测试:
import pytest
import inspect
def test_func1_signature:
expected_signature = ['a', 'b'] # I specify what i expect
actual_signature = inspect.getfullargspec(func1)[0]
assert actual_signature == expected_signature
If anyone knows a better/more pythonic/more correct way, please let me know.如果有人知道更好/更pythonic/更正确的方法,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.