Skip to main content

How to test Functions before deploying [Cognite Official]

  • May 28, 2025
  • 0 replies
  • 77 views

Gaetan  Helness
MVP
Forum|alt.badge.img+1

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.

AD_4nXcP_mtzQXsLK4d1UScDgv8gdZo_ZpTFCZxfXo_Z8N9jKYTXwAmAiQ5QIXHK2USJhMphbbnF7KA0dHXc7NvFy_5TiGTUYsTJHvp2KSkhrd0NLXTQ04ycssSAlqyEASAt0RpCPift_g?key=xeqcflrPpQ0HK_r4K-1Rxg

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

AD_4nXcoNd4v9gqaf-8F4jmwiIibejAhU8pl0HaflKqFnBbSJU1FAjghzGAkwOKzZuj-23bo-kh9nR5R43crVHEZFSdo7ckmcg1G3n8GOCSqSFfUkgxrX3VdKvy7N0ikOSnDbZuG8QCHyQ?key=xeqcflrPpQ0HK_r4K-1Rxg

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! ---")

AD_4nXdpYr7kHoNKrM4RLfBi06zd6n-mrc867OQqXVk4M1T8mDwND7-JcUxgJChxvCMFPUteukHlUIV1Z216UK5TZssGm6FtD0tB9IObvup1LUccOavbihJFl1yvYWMzanqqTvIrzLAClw?key=xeqcflrPpQ0HK_r4K-1Rxg

 

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

AD_4nXfH5fdQeplpYYP8DeRRA3be4jyu7KyjpFSZFDOO_VnN2wJJWR0BMosFS0MPil-97bHya8eVNZiPIgBiIRnvOCV34dcXy8IdRnstVptgOOVKyEUTcBChQxEPAd2YeAZnNr6YMPb9?key=xeqcflrPpQ0HK_r4K-1Rxg

Create a test.py file 

Import the handler file and the libraries to create the Cognite Client

AD_4nXfYouYh9QL9JiOPMs6uoblWa4AyONlPhj-LvwIfV_y2nCo0xJc32dvitiy9GCEIzGyyJMWdrygNPNioab3xdcP9llSVF2oDClRqh77n_clfNTc-UB2u5eQYFKzYRjaTdprVpow3?key=xeqcflrPpQ0HK_r4K-1Rxg

 

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

AD_4nXcf7lRier6H51KKGYNvqcunQnGEpHXti29JmG1gpoSbqcxIOCDPn8NuuiMjtA_hT8Ahvfcl1FQq_35Je7CBebvSQA3l5giUU2p3YeHHmVXNnU_2G9L9RwLteaJWHQ2YAiw7E_AS?key=xeqcflrPpQ0HK_r4K-1Rxg

In your config.<env>.yaml file, refer to that module

environment:
name: publicdata
project: publicdata
validation-type: dev
selected:
- modules/common/guide

We will then use the run plugin

Make sure it is enabled in the cdf.toml file:

AD_4nXdr65LZ6lD-CM-SPT622QZnG7uagUr-cJ7Y9qMqt-JIfBPnErNRlRi9wyFdf3EjI_S8lVk2SsbB02I2pSz2c9yL_x93LsF0iaIiPiVq8B51Ual3ruHQx8vPgsBt_YBVUlbQVXQeUA?key=xeqcflrPpQ0HK_r4K-1Rxg

In your terminal, run the following

cdf run function local --env=<env>

Choose the function you want to run

AD_4nXf_xYlgrZP-cN_I6WYe6arYxYfw2bX_W4YroQ_LrXylRN6ftj7pSf0UcwInvwHg8sGaMVzArCWhnnvFGvJx5wf4e4w8EZiOuZQAmGlQdsOzGUfmurPPaR2lUiQnfKmRm8PkaU2z?key=xeqcflrPpQ0HK_r4K-1Rxg

 

AD_4nXfwOD6KgEli5vbu4ldPu9DLbM6HaXfwCa4zkGhAyCr0f7qTfmyInbt9nJ4oI3efZym2UAAmHFPjVcNARpgpeHs-jSOqd7fJZLGWKsZGfJW-DoTPRMNltEeI7fqj9bR0kyz_MWm3Gg?key=xeqcflrPpQ0HK_r4K-1Rxg

 

AD_4nXdsydm77GwP_yREAZ61FlfgFygv0MbVhDjgN-UAkdSD14X565jclu38oJis-8FMsShSd7PrKizfKrbJx6_DCEFd4cQWRrA6b6iIhMKy3LGdgBz81cMaRZWNApFmdUsqB2voEsCkrg?key=xeqcflrPpQ0HK_r4K-1Rxg

 

If we want to test with some data, we can add a schedule file to provide that input data

AD_4nXcvEnsrmWucoV32u1EpwZkSv2artCVHmC29DLtt1lCW85uOnR5lTMijc0PPX4JMSJrZ0fYbjZdshOyyU2WSQSG31OBOGiLBTBd0MIagSFUuxOsQWKeKO-Azkrepep9igVZOQ_jxjQ?key=xeqcflrPpQ0HK_r4K-1Rxg

 

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

AD_4nXeyb9Yg7zc57C5AS2xqIlF-cdmZw8EutTc6GuE2x22PRcoX9kKkw30OcRjWyrqVcieWmyXy0oF6F3w3qyZNUEos2J1Do_WrHuXpt3nWIhCdZv42TaDZPpzJb4RDw_68T57LTdbftA?key=xeqcflrPpQ0HK_r4K-1Rxg