单元测试 Python 个脚本
UnitTesting Python scripts
我是Python新手
是否可以在不将代码包装在函数中的情况下测试 Python 脚本/类?
假设我想用 UT 覆盖这个脚本 https://github.com/aws-samples/aws-glue-samples/blob/master/examples/join_and_relationalize.py
是否可以为它写一些 UT https://docs.python.org/3/library/unittest.html?
问题是:我无法在 AWS Glue 中 运行 methods/functions,但只有 script 是该框架的输入点。
https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python.html
Is that possible to test Python script without wrapping code in functions / classes?
您可以只创建 运行 脚本本身的单元测试(例如使用 subprocess
,检查它是否具有正确的 retval / 输出)。
The issue is: I can not run methods/functions in AWS Glue but only script is enter point for that Framework.
这实际上并不排除编写函数(甚至 类),除非 AWS Glue 特别禁止这样做(我认为这不太可能)。
Python 文件既是 运行 可用脚本又是可导入库是很常见的。您只需要“控制”脚本入口点:
def a_function():
print("a function")
def main():
a_function()
# magic!
if __name__ == '__main__':
main()
最后两行是魔法位:__name__
仅当文件 运行 作为脚本时才等于 "__main__"
。
这意味着如果你 运行 上面的文件它会立即打印“一个函数”,但是如果你 import
它,它不会做任何事情直到你调用 a_function()
(或main()
)。
我是Python新手
是否可以在不将代码包装在函数中的情况下测试 Python 脚本/类?
假设我想用 UT 覆盖这个脚本 https://github.com/aws-samples/aws-glue-samples/blob/master/examples/join_and_relationalize.py
是否可以为它写一些 UT https://docs.python.org/3/library/unittest.html?
问题是:我无法在 AWS Glue 中 运行 methods/functions,但只有 script 是该框架的输入点。
https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python.html
Is that possible to test Python script without wrapping code in functions / classes?
您可以只创建 运行 脚本本身的单元测试(例如使用 subprocess
,检查它是否具有正确的 retval / 输出)。
The issue is: I can not run methods/functions in AWS Glue but only script is enter point for that Framework.
这实际上并不排除编写函数(甚至 类),除非 AWS Glue 特别禁止这样做(我认为这不太可能)。
Python 文件既是 运行 可用脚本又是可导入库是很常见的。您只需要“控制”脚本入口点:
def a_function():
print("a function")
def main():
a_function()
# magic!
if __name__ == '__main__':
main()
最后两行是魔法位:__name__
仅当文件 运行 作为脚本时才等于 "__main__"
。
这意味着如果你 运行 上面的文件它会立即打印“一个函数”,但是如果你 import
它,它不会做任何事情直到你调用 a_function()
(或main()
)。