Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,7 @@ node_modules
yarn-lock.json

.benchmarks

# Integration test build artifacts
tests/integration/.build/
tests/integration/.aws-sam/
3 changes: 3 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
variables:
SKIP_E2E_TESTS: "false"
# Opt-in pytest integration suite (integration-test-pytest jobs).
# TODO(APMSVLS-728): set back to "false" before merging.
RUN_PYTEST_INTEGRATION_TESTS: "true"

stages:
- pre
Expand Down
5 changes: 5 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ We love pull requests. For new features, consider opening an issue to discuss th
```bash
UPDATE_SNAPSHOTS=true DD_API_KEY=<your Datadog api key> ./scripts/run_integration_tests.sh
```
1. The pytest integration suite in `tests/integration` (replacing the snapshot suite) deploys a stack from a SAM template, so it needs the [SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html) (`pip install -r tests/integration/requirements-test.txt`):
```bash
BUILD_LAYERS=true PYTHON_VERSION=3.13 ARCH=amd64 DD_API_KEY=<your Datadog api key> ./scripts/run_integration_pytest.sh
```
The tests that use the Datadog Extension (with a mock intake) use the latest Extension layer; set `DD_EXTENSION_LAYER_VERSION` to pin a version, or to `none` to skip them. In CI this suite only runs in pipelines with `RUN_PYTEST_INTEGRATION_TESTS=true`. While iterating, set `KEEP_STACK=true` once, then `INTEGRATION_STACK_NAME=<stack>` to skip redeploying.
1. Push to your fork and [submit a pull request][pr].

[pr]: https://github.com/your-username/datadog-lambda-python/compare/DataDog:main...main
Expand Down
32 changes: 32 additions & 0 deletions ci/input_files/build.yaml.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,38 @@ integration-test ({{ $runtime.name }}-{{ $runtime.arch }}):
- RUNTIME_PARAM={{ $runtime.python_version }} ARCH={{ $runtime.arch }} ./scripts/run_integration_tests.sh
retry: 2

# Pytest + SAM replacement for the snapshot-based integration-test job above.
# Opt-in: only runs when the pipeline has RUN_PYTEST_INTEGRATION_TESTS=true (set it
# when running a pipeline, or as a CI/CD variable). Non-blocking until it has been
# green for a while; then the old job is removed.
integration-test-pytest ({{ $runtime.name }}-{{ $runtime.arch }}):
stage: test
tags: ["arch:amd64"]
image: registry.ddbuild.io/images/docker:29.4.0-noble-py3
allow_failure: true
rules:
- if: '$RUN_PYTEST_INTEGRATION_TESTS != "true"'
when: never
- if: '$SKIP_E2E_TESTS == "true"'
when: never
- when: on_success
needs:
- build-layer ({{ $runtime.name }}-{{ $runtime.arch }})
dependencies:
- build-layer ({{ $runtime.name }}-{{ $runtime.arch }})
before_script:
- *install-python-tools
- EXTERNAL_ID_NAME=integration-test-externalid ROLE_TO_ASSUME=sandbox-integration-test-deployer AWS_ACCOUNT=425362996713 source ./ci/get_secrets.sh
- pip install -r tests/integration/requirements-test.txt
script:
# Uses the latest Datadog Extension unless DD_EXTENSION_LAYER_VERSION pins one.
- PYTHON_VERSION={{ $runtime.python_version }} ARCH={{ $runtime.arch }} ./scripts/run_integration_pytest.sh --junitxml=integration-junit.xml
artifacts:
when: always
reports:
junit: tests/integration/integration-junit.xml
retry: 1

sign-layer ({{ $runtime.name }}-{{ $runtime.arch }}):
stage: sign
tags: ["arch:amd64"]
Expand Down
45 changes: 45 additions & 0 deletions scripts/run_integration_pytest.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/bin/bash

# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2026 Datadog, Inc.

# Runs the pytest integration suite in tests/integration (SAM-deployed stack).
#
# Usage, from the repo root:
# PYTHON_VERSION=3.13 ARCH=amd64 DD_API_KEY=XXXX \
# aws-vault exec sso-serverless-sandbox-account-admin -- ./scripts/run_integration_pytest.sh
#
# Optional:
# BUILD_LAYERS=true build the layer first
# DD_EXTENSION_LAYER_VERSION=N pin the Datadog Extension version (default: latest;
# "none" skips the extension / mock intake tests)
# INTEGRATION_STACK_NAME=... reuse a deployed stack (kept afterwards)
# KEEP_STACK=true keep the stack for debugging
# Extra arguments are passed to pytest, e.g. -k sqs

set -e

scripts_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo_dir=$(dirname "$scripts_dir")

for var in PYTHON_VERSION ARCH DD_API_KEY; do
if [ -z "${!var}" ]; then
echo "$var must be set"
exit 1
fi
done

if [ -n "$BUILD_LAYERS" ]; then
PYTHON_VERSION=$PYTHON_VERSION ARCH=$ARCH "$scripts_dir/build_layers.sh"
fi

marker_args=()
if [ "$DD_EXTENSION_LAYER_VERSION" = "none" ]; then
echo "DD_EXTENSION_LAYER_VERSION=none, skipping extension tests"
marker_args=(-m "not extension")
fi

cd "$repo_dir/tests/integration"
python -m pytest "${marker_args[@]}" "$@"
4 changes: 4 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

from datadog_lambda.config import config

# tests/integration deploys AWS resources; it runs from its own directory
# (cd tests/integration && pytest), never as part of the unit tests.
collect_ignore = ["integration"]


@pytest.fixture(autouse=True)
def reset_config():
Expand Down
Empty file added tests/integration/__init__.py
Empty file.
96 changes: 96 additions & 0 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Session fixtures: deploy the stack once, run the baseline invocations once.

Environment:
PYTHON_VERSION, ARCH, DD_API_KEY required
DD_EXTENSION_LAYER_VERSION Datadog Extension layer version: a number, "latest"
(default) or "none" (no extension tests)
INTEGRATION_STACK_NAME reuse a deployed stack (it is kept afterwards)
KEEP_STACK=true don't delete the stack at the end
INTEGRATION_REGION default eu-west-1
"""

from __future__ import annotations

import json
import secrets
from pathlib import Path
from typing import Dict, List, Tuple

import pytest

from .harness import aws
from .harness import settings as settings_mod

INPUT_EVENTS_DIR = Path(__file__).parent / "input_events"
# Sorted, so the first invocation of each function (the cold start) is always
# the same event.
EVENT_NAMES: List[str] = sorted(p.stem for p in INPUT_EVENTS_DIR.glob("*.json"))
BASELINE_FUNCTIONS = {
"async-metrics": "AsyncMetricsFunctionName",
"sync-metrics": "SyncMetricsFunctionName",
}


def load_event(name: str):
return json.loads((INPUT_EVENTS_DIR / (name + ".json")).read_text())


@pytest.fixture(scope="session")
def run_settings() -> settings_mod.Settings:
return settings_mod.load()


@pytest.fixture(scope="session")
def stack(request, run_settings) -> Dict[str, str]:
"""Deploy the stack and return its outputs."""
s = run_settings
if not s.existing_stack:
# Stream deploy output (pip, sam) live instead of capturing it.
capture = request.config.pluginmanager.getplugin("capturemanager")
with capture.global_and_fixture_disabled():
print("\nIntegration test stack: %s" % s.stack_name, flush=True)
try:
aws.deploy(s, mock_intake_api_key=secrets.token_hex(16))
except Exception as e:
if not s.keep_stack:
aws.delete(s)
# Every test needs the stack; stop with one error, not one per test.
pytest.exit("Deploying %s failed: %s" % (s.stack_name, e), returncode=1)
try:
yield aws.stack_outputs(s)
finally:
if not s.keep_stack:
aws.delete(s)


@pytest.fixture(scope="session")
def baseline_invocations(run_settings, stack) -> Dict[Tuple[str, str], aws.Invocation]:
"""Invoke each baseline function once per input event, in sorted order,
and attach the parsed logs. Keyed by (function key, event name)."""
results: Dict[Tuple[str, str], aws.Invocation] = {}
for key, output in BASELINE_FUNCTIONS.items():
function_name = stack[output]
if run_settings.existing_stack:
# A reused stack may be warm; the first invocation must be a cold start.
aws.force_cold_start(run_settings.region, function_name)
invocations = [
aws.invoke(run_settings.region, function_name, load_event(name))
for name in EVENT_NAMES
]
logs = aws.wait_for_logs(
run_settings.region, function_name, [i.request_id for i in invocations]
)
for name, inv in zip(EVENT_NAMES, invocations):
inv.logs = logs[inv.request_id]
results[(key, name)] = inv
return results


@pytest.fixture(scope="session")
def extension_function(run_settings, stack) -> str:
if "ExtensionFunctionName" not in stack:
pytest.fail(
"Stack has no extension function (DD_EXTENSION_LAYER_VERSION=none); "
'deselect these tests with -m "not extension"'
)
return stack["ExtensionFunctionName"]
38 changes: 38 additions & 0 deletions tests/integration/functions/baseline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import requests

from datadog_lambda.metric import lambda_metric
from datadog_lambda.wrapper import datadog_lambda_wrapper


@datadog_lambda_wrapper
def handle(event, context):
# Parse request ID and record IDs out of the event to include in the response
request_id = event.get("requestContext", {}).get("requestId")
event_records = event.get("Records", [])

record_ids = []
for record in event_records:
# SQS
if record.get("messageId"):
record_ids.append(record["messageId"])
# SNS
if record.get("Sns", {}).get("MessageId"):
record_ids.append(record["Sns"]["MessageId"])

# Generate custom metrics
lambda_metric("hello.dog", 1, tags=["team:serverless", "role:hello"])
lambda_metric(
"tests.integration.count", 21, tags=["test:integration", "role:hello"]
)

# Make HTTP calls to test ddtrace instrumentation
requests.get("https://datadoghq.com")

return {
"statusCode": 200,
"body": {
"message": "hello, dog!",
"request_id": request_id,
"event_record_ids": record_ids,
},
}
Empty file.
Loading
Loading