在本地测试 Code Engine 函数

IBM Cloud® Code Engine 函数是通过代码片段创建的,因此在本地测试它们并不像在本地测试应用程序或工作那样简单。 通过为代码片段创建包装器,然后在本地运行函数,可以在本地测试函数的一种方法。

要使用包装器测试代码,请遵循以下常规步骤。

  1. 创建一个名为 test-local 的目录。
  2. 创建名为 func 的子目录。
  3. 将函数代码复制到 func 子目录中。
  4. 将 Python 或 Node.js 包装程序代码复制到父目录中。
  5. 创建配置文件作为 JSON 对象,类似于 Code Engine 在调用时传递到 函数的内容
  6. 将配置文件作为参数运行包装程序代码。

您可以使用以下包装器或创建自己的包装器。

Python 包装程序

# syntax: python wrapper.py params.json

# import the Code Engine function: func/__main__.py
from func.__main__ import main
import sys, json

if __name__ == "__main__":
    # open file, read JSON config
    with open(str(sys.argv[1])) as confFile:
        params=json.load(confFile)
    # invoke the Code Engine function and print the result
    print(main(params))

Node.js 包装器

// syntax: node wrapper.js params.json

// require the Code Engine function: func/main.js
var func=require('./func/main.js')

// read the file with function parameters
const fs = require("fs");
const data = fs.readFileSync(process.argv[2]);

// invoke the Code Engine function and log the result
console.log(func.main(JSON.parse(data)));