Skip to content
Open
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
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,10 @@ node_modules
yarn-lock.json

.benchmarks

# Integration test build artifacts
tests/integration/.build/
tests/integration/.aws-sam/

# Generated from ci/input_files/build.yaml.tpl (regenerated by the CI generator job)
ci/build-pipeline.yaml
4 changes: 3 additions & 1 deletion .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -1,6 +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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Keep the replacement integration suite disabled by default

Without an explicit pipeline override, this enables two new integration jobs for each of eight Python runtimes and two architectures: 32 additional AWS stack deployments alongside the existing suite. That adds deployment costs and CI work despite the stated plan to keep the replacement suite disabled. Default this variable to false so the jobs remain opt-in.

Suggested change
RUN_PYTEST_INTEGRATION_TESTS: "true"
RUN_PYTEST_INTEGRATION_TESTS: "false"

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

stages:
- pre
- build
Expand Down
11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,17 @@ 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
```
`DD_API_KEY_SECRET_ARN=<secrets manager arn>` can stand in for `DD_API_KEY`. The deployed functions read the key from Secrets Manager, so their role must be allowed to read that secret.
Leave out `PYTHON_VERSION` to run every supported version, one after another.
The tests that use the Datadog Extension (with a mock intake) use the layer version pinned in `DEFAULT_EXTENSION_LAYER_VERSION` in `tests/integration/harness/settings.py` by default; set `DD_EXTENSION_LAYER_VERSION` to another version number, or to `none` to skip them. In CI this suite only runs in pipelines with `RUN_PYTEST_INTEGRATION_TESTS=true`, as two jobs per runtime: `integration-test-pytest` (library only, no Extension) and `integration-test-pytest-extension` (the Extension tests, using that same pinned version). While iterating, set `KEEP_STACK=true` once, then `INTEGRATION_STACK_NAME=<stack>` to skip redeploying.
1. The pytest suite compares every span tag, outgoing request header, and metric tag against structured snapshots in `tests/integration/expected/` (`<category>/<variant>/<function>/<event>.json`, where the variant is `default` or a runtime override such as `python38` or `python314-amd64`). Requests and metrics are condensed: every event emits the same metrics, so there is one file per function (`metrics/<variant>/<function>.json`), and requests have one file per function (`requests/<variant>/<function>.json`) plus an event file only where an event's requests differ (for example `appsync` on `default`, and the `zstd` `Accept-Encoding` on python314/315). python39 has no files of its own: its snapshots match python38's, so it falls back to them (`SHARED_RUNTIMES` in `tests/integration/harness/snapshots.py`). If the two ever diverge, `dedupe` fails and asks for the alias to be removed. The `cold_start` tag and the DynamoDB-only stream metric (value and tags) are asserted in `tests/integration/test_baseline.py` instead. Unexpected log output (warnings, prints, tracebacks) is not snapshotted: `test_no_unexpected_log_lines` in `tests/integration/test_baseline.py` requires it to be empty, and an intended new line goes on `ALLOWED_LOG_LINES` in that file (Lambda platform lines are filtered by `_PLATFORM_LINE_RES` in `tests/integration/harness/logs.py`). To update the snapshots after an intended change:
1. Run the suite with `UPDATE_EXPECTED=true`, locally (writes files for that runtime) or in CI with `RUN_PYTEST_INTEGRATION_TESTS=true UPDATE_EXPECTED=true` (each `integration-test-pytest` job saves `tests/integration/expected/` as an artifact; extract all of them into the repo).
1. Fold the per-run files into defaults plus overrides: `cd tests/integration && python -m harness.snapshots dedupe`.
1. Review the diff and commit it.
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
77 changes: 77 additions & 0 deletions ci/input_files/build.yaml.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ default:
- /opt/ci-python-tools/bin/pip install awscli
- export PATH="/opt/ci-python-tools/bin:$PATH"

# aws-sam-cli and awscli pin incompatible botocore versions, so the integration
# test dependencies get their own venv, ahead of the awscli one on PATH.
.install-integration-test-deps: &install-integration-test-deps
- python3 -m venv /opt/integration-test-venv
- /opt/integration-test-venv/bin/pip install -r tests/integration/requirements-test.txt
- export PATH="/opt/integration-test-venv/bin:$PATH"

# This is for serverless framework
.install-node: &install-node
- apt-get update
Expand Down Expand Up @@ -134,6 +141,76 @@ 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.
#
# Two jobs per runtime, so an Extension release cannot fail the library tests:
# integration-test-pytest the library alone (no Extension layer)
# integration-test-pytest-extension the library with the Datadog Extension layer
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 }})
variables:
# No Extension layer: skips the tests marked "extension".
DD_EXTENSION_LAYER_VERSION: "none"
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
- *install-integration-test-deps
script:
- PYTHON_VERSION={{ $runtime.python_version }} ARCH={{ $runtime.arch }} ./scripts/run_integration_pytest.sh --junitxml=integration-junit.xml
artifacts:
when: always
# With UPDATE_EXPECTED=true, the snapshots this job wrote (see CONTRIBUTING.md).
paths:
- tests/integration/expected/
reports:
junit: tests/integration/integration-junit.xml
retry: 1

integration-test-pytest-extension ({{ $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 }})
# The Extension layer version is DEFAULT_EXTENSION_LAYER_VERSION in
# tests/integration/harness/settings.py; change it there, not per pipeline.
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
- *install-integration-test-deps
script:
- PYTHON_VERSION={{ $runtime.python_version }} ARCH={{ $runtime.arch }} ./scripts/run_integration_pytest.sh -m extension --junitxml=integration-extension-junit.xml
artifacts:
when: always
reports:
junit: tests/integration/integration-extension-junit.xml
retry: 1

sign-layer ({{ $runtime.name }}-{{ $runtime.arch }}):
stage: sign
tags: ["arch:amd64"]
Expand Down
106 changes: 106 additions & 0 deletions scripts/run_integration_pytest.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/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:
# ARCH=amd64 DD_API_KEY=XXXX \
# aws-vault exec sso-serverless-sandbox-account-admin -- ./scripts/run_integration_pytest.sh
#
# DD_API_KEY_SECRET_ARN can stand in for DD_API_KEY. The deployed functions read
# the key from Secrets Manager themselves, so the role they run as must be
# allowed to read that secret.
#
# Runs every Python version in python_versions.yaml, one after another (each
# deploys its own stack), unless PYTHON_VERSION is set.
#
# Optional:
# PYTHON_VERSION=3.13 run one version only (shorthand like 13 works too)
# BUILD_LAYERS=true build the layer(s) first
# DD_EXTENSION_LAYER_VERSION=N Datadog Extension layer version (default: the pin in
# tests/integration/harness/settings.py;
# "none" skips the extension / mock intake tests)
# INTEGRATION_STACK_NAME=... reuse a deployed stack (kept afterwards); needs PYTHON_VERSION
# KEEP_STACK=true keep the stack(s) for debugging
# UPDATE_EXPECTED=true write snapshots instead of comparing (see CONTRIBUTING.md)
# Extra arguments are passed to pytest, e.g. -k sqs. With several versions,
# --junitxml=<file>.xml writes one <file>-<version>.xml per version.

set -e

scripts_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo_dir=$(dirname "$scripts_dir")
source "$scripts_dir/python_versions.sh"

if [ -z "$ARCH" ]; then
echo "ARCH must be set"
exit 1
fi

if [ -z "$DD_API_KEY" ] && [ -z "$DD_API_KEY_SECRET_ARN" ]; then
echo "DD_API_KEY or DD_API_KEY_SECRET_ARN must be set"
exit 1
fi

if [ -n "$PYTHON_VERSION" ]; then
if [[ "$PYTHON_VERSION" =~ ^[0-9]+$ ]]; then
PYTHON_VERSION="3.${PYTHON_VERSION}"
fi
if [[ ! " ${SUPPORTED_PYTHON_VERSIONS[*]} " =~ " ${PYTHON_VERSION} " ]]; then
echo "Python version $PYTHON_VERSION is not supported. Choose from: ${SUPPORTED_PYTHON_VERSIONS[*]}"
exit 1
fi
versions=("$PYTHON_VERSION")
else
if [ -n "$INTEGRATION_STACK_NAME" ]; then
echo "INTEGRATION_STACK_NAME reuses one runtime's stack; set PYTHON_VERSION too"
exit 1
fi
versions=("${SUPPORTED_PYTHON_VERSIONS[@]}")
echo "PYTHON_VERSION not set, running all versions: ${versions[*]}"
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

failed=()
for version in "${versions[@]}"; do
echo "=== Python $version ($ARCH) ==="

# One JUnit file per version, so runs don't overwrite each other.
pytest_args=()
for arg in "$@"; do
if [ ${#versions[@]} -gt 1 ] && [[ "$arg" == --junitxml=*.xml ]]; then
arg="${arg%.xml}-${version}.xml"
fi
pytest_args+=("$arg")
done

# Keep going after a failure, so one run covers every version.
set +e
(
set -e
if [ -n "$BUILD_LAYERS" ]; then
PYTHON_VERSION=$version ARCH=$ARCH "$scripts_dir/build_layers.sh"
fi
cd "$repo_dir/tests/integration"
PYTHON_VERSION=$version python -m pytest "${marker_args[@]}" "${pytest_args[@]}"
)
status=$?
set -e
if [ $status -ne 0 ]; then
failed+=("$version")
fi
done

if [ ${#versions[@]} -gt 1 ]; then
echo "=== Ran ${#versions[@]} versions on $ARCH; failed: ${failed[*]:-none} ==="
fi
[ ${#failed[@]} -eq 0 ]
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.
107 changes: 107 additions & 0 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"""Session fixtures: deploy the stack once, run the baseline invocations once.

Environment:
PYTHON_VERSION, ARCH, and one of DD_API_KEY or DD_API_KEY_SECRET_ARN required
DD_EXTENSION_LAYER_VERSION Datadog Extension layer version number (default:
the pinned version in harness/settings.py) 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 typing import Dict, Tuple

import pytest

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

from .harness.settings import BASELINE_FUNCTIONS, EVENT_NAMES, INPUT_EVENTS_DIR

CASES = [(fn, ev) for fn in BASELINE_FUNCTIONS for ev in EVENT_NAMES]


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:
# Report the deploy error first: a failing cleanup must not hide it.
print("Deploying %s failed: %s" % (s.stack_name, e), flush=True)
if not s.keep_stack:
try:
aws.delete(s)
except Exception as cleanup_error:
print(
"Deleting %s also failed, delete it manually: %s"
% (s.stack_name, cleanup_error),
flush=True,
)
# 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(params=CASES, ids=["%s-%s" % c for c in CASES])
def case(request, baseline_invocations):
"""(function key, event name, Invocation), once per baseline function and event."""
fn, event_name = request.param
return fn, event_name, baseline_invocations[(fn, event_name)]


@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"]
35 changes: 35 additions & 0 deletions tests/integration/expected/metrics/default/async-metrics.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
[
{
"m": "aws.lambda.enhanced.invocations",
"t": [
"account_id:<account_id>",
"cold_start:<bool>",
"datadog_lambda:<version>",
"dd_lambda_layer:datadog-<runtime_key>_<version>",
"functionname:<function_name>",
"memorysize:1024",
"region:eu-west-1",
"resource:<function_name>",
"runtime:<runtime>"
],
"v": 1
},
{
"m": "hello.dog",
"t": [
"dd_lambda_layer:datadog-<runtime_key>_<version>",
"role:hello",
"team:serverless"
],
"v": 1
},
{
"m": "tests.integration.count",
"t": [
"dd_lambda_layer:datadog-<runtime_key>_<version>",
"role:hello",
"test:integration"
],
"v": 21
}
]
Loading
Loading