This How-To guide will explain different ways that can be used to test Cognite functions.
Let’s use the code below as an example and see how we can test it through the various methods.
# The main function that Cognite Function will call
def handle(client, data):
"""
A simple Cognite Function that takes a name and returns a greeting.
Args:
client: The cognite client
data: The input for the function. Expected to have a "name" key.
Returns:
A dictionary with a "message" key and the number of functions on the project.
"""
# Get the name from the input data, default to "World" if not provided
name = data.get("name", "World")
# Create the greeting message
message = f"Hello, {name}!"
# List of the functions and count the number of functions
functions_list = client.functions.list()
functions_num = len(functions_list)
# Return the result as a dictionary
return {"message": message,"number of functions": functions_num}
In a python notebook in CDF
Navigate to Data Management > Build solutions > Jupyter notebook
The Cognite client is created automatically for you.
Create the data object
data={"name": "Gaetan"}Create the function
# The main function that Cognite will call
def handle(client, data):
"""
A simple Cognite Function that takes a name and returns a greeting.
Args:
client: The cognite client
data: The input for the function. Expected to have a "name" key.
Returns:
A dictionary with a "message" key and the number of functions on the project.
"""
# Get the name from the input data, default to "World" if not provided
name = data.get("name", "World")
# Create the greeting message
message = f"Hello, {name}!"
# List of the functions and count the number of functions
functions_list = client.functions.list()
functions_num = len(functions_list)
# Return the result as a dictionary
return {"message": message,"number of functions": functions_num}
Call the function
handle(client, data)See the output and check if it matches your expectations
Let's say we automate the behaviour, we can run the following cell to test our code, but this will be very specific to the code.
# Test case 1: With a provided name
test_data_1 = {"name": "TestUser"}
print(f"\nCalling with input: {test_data_1}")
result_1 = handle(client, test_data_1)
print(f"Result 1: {result_1}")
assert result_1["message"] == "Hello, TestUser!"
assert result_1["number of functions"] >= 0 # Expect a non-negative number
# Test case 2: Without a provided name (defaults to "World")
test_data_2 = {}
print(f"\nCalling with input: {test_data_2}")
result_2 = handle(client, test_data_2)
print(f"Result 2: {result_2}")
assert result_2["message"] == "Hello, World!"
assert result_2["number of functions"] >= 0
print("\n--- All local tests passed! ---")
In a python notebook locally
For a python notebook locally, we will use the same principle, except we have to create the Cognite Client as it is not provided to use automatically.
For example, you can do that through the following code, adapted to your environment and reuse the same code as in the python notebook on CDF.
from cognite.client import CogniteClient
import os
config = {
"client_name": "abcd",
"project": "cdf-project",
"base_url": "https://api.cognitedata.com/",
"credentials": {
"client_credentials": {
"client_id": "abcd",
"client_secret": os.environ["OAUTH_CLIENT_SECRET"],
"token_url": "https://login.microsoftonline.com/xyz/oauth2/v2.0/token",
"scopes": ["https://api.cognitedata.com/.default"],
},
},
}
client = CogniteClient.load(config)
In a python script locally
If you want to test it through a local python script, you can follow the same principles as above, but through a different method.
Create the handler.py file for the function that you want to test
Create a test.py file
Import the handler file and the libraries to create the Cognite Client
Create the rest of the file and run it to test your function code
from handler import handle
from cognite.client import CogniteClient, ClientConfig
from cognite.client.credentials import OAuthClientCredentials
#Create the Cognite client - to be edited according to your use
client = CogniteClient(
ClientConfig(
client_name=project_name,
base_url=base_url,
project=project_name,
credentials=OAuthClientCredentials(
token_url=token_url,
client_id=client_id,
client_secret=client_secret,
scopes=scopes,
),
)
)
data = {"name": "Gaetan"}
output = handle(client, data)
print(output)
# Test case 1: With a provided name
test_data_1 = {"name": "Gaetan"}
print(f"\nCalling with input: {test_data_1}")
result_1 = handle(client, test_data_1)
print(f"Result 1: {result_1}")
assert result_1["message"] == "Hello, Gaetan!"
assert result_1["number of functions"] >= 0 # Expect a non-negative number
# Test case 2: Without a provided name (defaults to "World")
test_data_2 = {}
print(f"\nCalling with input: {test_data_2}")
result_2 = handle(client, test_data_2)
print(f"Result 2: {result_2}")
assert result_2["message"] == "Hello, World!"
assert result_2["number of functions"] >= 0
print("\n--- All local tests passed! ---")
Through the CDF toolkit
The CDF toolkit function resource directory expects a specific setup for it to work. You can test it locally.
Create your module with a functions folder.
For example, I have set up my directories like this
In your config.<env>.yaml file, refer to that module
environment:
name: publicdata
project: publicdata
validation-type: dev
selected:
- modules/common/guideWe will then use the run plugin
Make sure it is enabled in the cdf.toml file:
In your terminal, run the following
cdf run function local --env=<env>Choose the function you want to run
If we want to test with some data, we can add a schedule file to provide that input data
When asked if we want to provide input data, it then asks for which schedule to run (ie from which Schedule file, should we use the data from
Check the
documentation
Ask the
Community
Take a look
at
Academy
Cognite
Status
Page
Contact
Cognite Support