Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: harness base completed
=2997dcdae867
diff --git a/tests/.gitignore b/tests/.gitignorenew file mode 100644index 0000000000..308ae80196--- /dev/null+++ b/tests/.gitignore@@ -0,0 +1,4 @@+# Container logs, written unconditionally so you can tail one while a test hangs.+.logs/+# Materialized Docker build context for the test image.+.build-context/diff --git a/tests/Makefile b/tests/Makefilenew file mode 100644index 0000000000..5c486190cc--- /dev/null+++ b/tests/Makefile@@ -0,0 +1,28 @@+# The module pins go 1.27, which GOTOOLCHAIN=auto fetches. A bare `gofmt` on PATH is+# whatever Go is installed system-wide and will reject generic methods, so always use+# the toolchain's own.+GOFMT := $(shell go env GOROOT)/bin/gofmt++.PHONY: fmt lint test test-unit++fmt:+ $(GOFMT) -w .++lint:+ @out="$$($(GOFMT) -l .)"; \+ if [ -n "$$out" ]; then echo "gofmt needed:"; echo "$$out"; exit 1; fi+ go vet ./...++# Unit tests only: no Docker, no containers, runs in under a second.+test-unit:+ go test ./infra/... ./internal/... -count=1++test: lint test-unit++# Container tests. Needs Docker. `inf down` if a run is interrupted.+test-docker:+ INFRA_DOCKER_TESTS=1 go test ./infra/... -count=1++down:+ @docker rm -f $$(docker ps -aq --filter label=inf.scope) 2>/dev/null || true+ @docker network rm inf-net 2>/dev/null || truediff --git a/tests/go.mod b/tests/go.modnew file mode 100644index 0000000000..0c6f0e4d56--- /dev/null+++ b/tests/go.mod@@ -0,0 +1,58 @@+module github.com/Infisical/infisical/tests++go 1.27.0++require github.com/testcontainers/testcontainers-go v0.44.0++require (+ dario.cat/mergo v1.0.2 // indirect+ github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect+ github.com/Microsoft/go-winio v0.6.2 // indirect+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect+ github.com/cespare/xxhash/v2 v2.3.0 // indirect+ github.com/containerd/errdefs v1.0.0 // indirect+ github.com/containerd/errdefs/pkg v0.3.0 // indirect+ github.com/containerd/log v0.1.0 // indirect+ github.com/containerd/platforms v0.2.1 // indirect+ github.com/cpuguy83/dockercfg v0.3.2 // indirect+ github.com/davecgh/go-spew v1.1.1 // indirect+ github.com/distribution/reference v0.6.0 // indirect+ github.com/docker/go-connections v0.7.0 // indirect+ github.com/docker/go-units v0.5.0 // indirect+ github.com/ebitengine/purego v0.10.1 // indirect+ github.com/felixge/httpsnoop v1.1.0 // indirect+ github.com/go-logr/logr v1.4.3 // indirect+ github.com/go-logr/stdr v1.2.2 // indirect+ github.com/go-ole/go-ole v1.3.0 // indirect+ github.com/google/uuid v1.6.0 // indirect+ github.com/klauspost/compress v1.18.6 // indirect+ github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect+ github.com/magiconair/properties v1.8.10 // indirect+ github.com/moby/docker-image-spec v1.3.1 // indirect+ github.com/moby/go-archive v0.2.0 // indirect+ github.com/moby/moby/api v1.55.0 // indirect+ github.com/moby/moby/client v0.5.0 // indirect+ github.com/moby/patternmatcher v0.6.1 // indirect+ github.com/moby/sys/sequential v0.7.0 // indirect+ github.com/moby/sys/user v0.4.0 // indirect+ github.com/moby/sys/userns v0.1.0 // indirect+ github.com/moby/term v0.5.2 // indirect+ github.com/opencontainers/go-digest v1.0.0 // indirect+ github.com/opencontainers/image-spec v1.1.1 // indirect+ github.com/pmezard/go-difflib v1.0.0 // indirect+ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect+ github.com/shirou/gopsutil/v4 v4.26.6 // indirect+ github.com/sirupsen/logrus v1.9.4 // indirect+ github.com/stretchr/testify v1.11.1 // indirect+ github.com/tklauser/go-sysconf v0.4.0 // indirect+ github.com/tklauser/numcpus v0.12.0 // indirect+ github.com/yusufpapurcu/wmi v1.2.4 // indirect+ go.opentelemetry.io/auto/sdk v1.2.1 // indirect+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect+ go.opentelemetry.io/otel v1.44.0 // indirect+ go.opentelemetry.io/otel/metric v1.44.0 // indirect+ go.opentelemetry.io/otel/trace v1.44.0 // indirect+ golang.org/x/crypto v0.54.0 // indirect+ golang.org/x/sys v0.47.0 // indirect+ gopkg.in/yaml.v3 v3.0.1 // indirect+)diff --git a/tests/go.sum b/tests/go.sumnew file mode 100644index 0000000000..ccb4f78537--- /dev/null+++ b/tests/go.sum@@ -0,0 +1,135 @@+dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=+dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=+github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=+github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=+github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=+github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=+github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=+github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=+github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=+github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=+github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=+github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=+github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=+github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=+github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=+github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=+github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=+github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw=+github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=+github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=+github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=+github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=+github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=+github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=+github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=+github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=+github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=+github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=+github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=+github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=+github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=+github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=+github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=+github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=+github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=+github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=+github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=+github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=+github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=+github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=+github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=+github.com/moby/go-archive v0.2.0 h1:zg5QDUM2mi0JIM9fdQZWC7U8+2ZfixfTYoHL7rWUcP8=+github.com/moby/go-archive v0.2.0/go.mod h1:mNeivT14o8xU+5q1YnNrkQVpK+dnNe/K6fHqnTg4qPU=+github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=+github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=+github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=+github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=+github.com/moby/patternmatcher v0.6.1 h1:qlhtafmr6kgMIJjKJMDmMWq7WLkKIo23hsrpR3x084U=+github.com/moby/patternmatcher v0.6.1/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=+github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=+github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=+github.com/moby/sys/user v0.4.0 h1:jhcMKit7SA80hivmFJcbB1vqmw//wU61Zdui2eQXuMs=+github.com/moby/sys/user v0.4.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=+github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=+github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=+github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=+github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=+github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=+github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=+github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=+github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=+github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=+github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=+github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=+github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=+github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=+github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=+github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=+github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=+github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=+github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=+github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=+github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=+github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=+github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=+github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=+go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=+go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=+go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=+go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=+go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=+go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=+go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=+go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=+go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=+go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=+golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=+golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=+golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=+gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=+pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=+pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=diff --git a/tests/infra/container.go b/tests/infra/container.gonew file mode 100644index 0000000000..1c7b51276b--- /dev/null+++ b/tests/infra/container.go@@ -0,0 +1,60 @@+package infra++import "context"++// File is copied into a container before it starts.+type File struct {+ Src string // path on the host+ Dst string // absolute path in the container+ Mode int64 // 0 means 0644+}++// ReadyFunc decides when a container is usable. Implementations live in ready.go.+type ReadyFunc func(ctx context.Context, c Container) error++// ContainerSpec is what a module asks for. Everything a module needs to say about a+// container, and nothing about how it gets created.+type ContainerSpec struct {+ Name string // from ContainerName; this is the adopt-or-create identity+ Image string+ Command []string+ Env map[string]string+ Ports []int+ Alias string // network alias, which becomes the Internal host+ Files []File+ Labels map[string]string+ Ready ReadyFunc+}++// Container is a started container, as seen by a module.+type Container struct {+ ID string+ Name string+ Adopted bool // true when an existing container was reused rather than created+ endpoint func(Mode, int) Endpoint+ stop func(context.Context) error+ exec func(context.Context, []string) (int, string, error)+ logs func(context.Context) (string, error)+}++func (c Container) Endpoint(m Mode, port int) Endpoint { return c.endpoint(m, port) }+func (c Container) Stop(ctx context.Context) error { return c.stop(ctx) }+func (c Container) Logs(ctx context.Context) (string, error) { return c.logs(ctx) }++// Exec runs a command inside the container and returns its exit code and combined+// output. Used by readiness checks such as pg_isready.+func (c Container) Exec(ctx context.Context, cmd []string) (int, string, error) {+ return c.exec(ctx, cmd)+}++// Runner creates or adopts containers. The single seam over the container engine.+//+// Modules never touch testcontainers directly, which is what keeps a module about+// thirty lines and lets the adopt mechanism be swapped. That matters here:+// testcontainers documents reuse-by-name as experimental and says the API is+// "subject to change for a more robust implementation that is not based on+// container names".+type Runner interface {+ Run(ctx context.Context, spec ContainerSpec) (Container, error)+ Network(ctx context.Context, name string) error+}diff --git a/tests/infra/endpoint.go b/tests/infra/endpoint.gonew file mode 100644index 0000000000..2e797922ca--- /dev/null+++ b/tests/infra/endpoint.go@@ -0,0 +1,45 @@+package infra++import (+ "fmt"+ "net"+ "strconv"+)++// Mode selects which address of a container you get back.+//+// Handing an Internal address to the test process, or an External one to another+// container, is the most common way to misuse a container harness. There is+// deliberately no bare URL() accessor, so every call site has to say which it means.+type Mode int++const (+ // Internal is the network alias plus the container port. Use it when one+ // container needs to reach another, for example Infisical dialling Postgres.+ Internal Mode = iota++ // External is the host plus the ephemeral mapped port. Use it when the Go test+ // process needs to reach a container.+ External+)++func (m Mode) String() string {+ if m == Internal {+ return "internal"+ }+ return "external"+}++// Endpoint is a reachable host and port in one mode.+type Endpoint struct {+ Host string+ Port int+}++func (e Endpoint) HostPort() string {+ return net.JoinHostPort(e.Host, strconv.Itoa(e.Port))+}++func (e Endpoint) URL(scheme string) string {+ return fmt.Sprintf("%s://%s", scheme, e.HostPort())+}diff --git a/tests/infra/labels.go b/tests/infra/labels.gonew file mode 100644index 0000000000..22ea894968--- /dev/null+++ b/tests/infra/labels.go@@ -0,0 +1,36 @@+package infra++import "time"++// Label keys. Nothing parses a container NAME; names are for humans reading+// `docker ps`. Structured data lives here, so adding a dimension later does not+// require a naming change that orphans everyone's containers.+const (+ LabelScope = Prefix + ".scope"+ LabelModule = Prefix + ".module"+ LabelInstance = Prefix + ".instance"+ LabelFingerprint = Prefix + ".fingerprint"+ LabelWorkspace = Prefix + ".workspace"+ LabelCreated = Prefix + ".created"+)++// Labels builds the label set for a container.+//+// workspace is recorded but is NOT part of identity. It exists so `inf status` can+// tell you which checkout created the container you are about to reap, which matters+// because shared containers are shared across worktrees on the same machine.+func Labels(p NameParts, workspace string) map[string]string {+ l := map[string]string{+ LabelScope: p.Scope.String(),+ LabelModule: p.Module,+ LabelWorkspace: workspace,+ LabelCreated: time.Now().UTC().Format(time.RFC3339),+ }+ if p.Instance != "" {+ l[LabelInstance] = p.Instance+ }+ if p.Fingerprint != "" {+ l[LabelFingerprint] = p.Fingerprint+ }+ return l+}diff --git a/tests/infra/lifetime.go b/tests/infra/lifetime.gonew file mode 100644index 0000000000..f821bbc8dd--- /dev/null+++ b/tests/infra/lifetime.go@@ -0,0 +1,36 @@+package infra++// Scope is who owns a container's lifetime. The rule the whole design rests on:+// a container is stopped by whoever created it, and a test binary never stops one+// it adopted.+type Scope int++const (+ // Shared containers are adopted by every test binary and deliberately outlive+ // the run, so a second `go test` is fast. Only `inf down` stops them.+ Shared Scope = iota++ // Package containers belong to one test binary and are stopped when it exits.+ Package++ // Test containers belong to one test function and are stopped by t.Cleanup.+ Test+)++func (s Scope) String() string {+ switch s {+ case Shared:+ return "shared"+ case Package:+ return "pkg"+ case Test:+ return "test"+ default:+ return "unknown"+ }+}++// LongerLivedThan reports whether s outlives other. A container may not depend on+// anything shorter lived than itself, because it reads its configuration once at+// start and cannot be repointed when that dependency goes away.+func (s Scope) LongerLivedThan(other Scope) bool { return s < other }diff --git a/tests/infra/logger.go b/tests/infra/logger.gonew file mode 100644index 0000000000..c3ae40ef18--- /dev/null+++ b/tests/infra/logger.go@@ -0,0 +1,34 @@+package infra++import (+ "fmt"+ "os"+ "time"+)++// Logger writes the lifecycle lines. One line per container decision, always on,+// because "why did that take four minutes" should need no investigation.+type Logger interface {+ Decision(action, name string, e Endpoint, took time.Duration, note string)+ Infof(format string, args ...any)+}++type stderrLogger struct{}++// NewLogger returns the default stderr logger.+func NewLogger() Logger { return stderrLogger{} }++func (stderrLogger) Decision(action, name string, e Endpoint, took time.Duration, note string) {+ line := fmt.Sprintf("infra: %-6s %-40s %s", action, name, e.HostPort())+ if took > 0 {+ line += fmt.Sprintf(" %.1fs", took.Seconds())+ }+ if note != "" {+ line += " " + note+ }+ fmt.Fprintln(os.Stderr, line)+}++func (stderrLogger) Infof(format string, args ...any) {+ fmt.Fprintf(os.Stderr, "infra: "+format+"\n", args...)+}diff --git a/tests/infra/module.go b/tests/infra/module.gonew file mode 100644index 0000000000..d4d04c7464--- /dev/null+++ b/tests/infra/module.go@@ -0,0 +1,209 @@+package infra++import (+ "context"+ "fmt"+ "sort"+ "strings"+)++// Key identifies a module for lookup. A module that can appear more than once+// qualifies its key with the instance name, so postgres.Module(postgres.Named(+// "rotation")) is "postgres:rotation" and does not collide with "postgres".+type Key string++// Module is a container the harness can start. Implementations live in+// infra/<name> and are about thirty lines each, because Deps.Run does the work.+type Module interface {+ Key() Key++ // Name is the identity-bearing part of the container name. The harness supplies+ // scope and scope id; a module supplies its own module name, instance, and a+ // fingerprint if and only if staleness would be silent for it.+ Name() NameParts++ // Requires lists modules this one cannot start without. Validated before+ // anything starts, so a missing dependency fails immediately rather than as a+ // connection timeout ninety seconds later.+ Requires() []Key++ // Optional lists modules this one consumes if present and ignores if not.+ Optional() []Key++ Start(context.Context, Deps) (Handle, error)+}++// Handle is a started container.+type Handle interface {+ Endpoint(Mode) Endpoint+ Stop(context.Context) error+}++// Deps is what a module sees during Start: every module that has already started,+// plus the network they share.+type Deps struct {+ handles map[Key]Handle+ network string+ workspace string+ name NameParts+ runner Runner+}++func (d Deps) Network() string { return d.network }++// Run starts this module's container. Name, alias and labels are filled in from the+// resolved scope, so a module never computes its own identity and cannot get the+// naming convention subtly wrong.+func (d Deps) Run(ctx context.Context, spec ContainerSpec) (Container, error) {+ if spec.Name == "" {+ spec.Name = ContainerName(d.name)+ }+ if spec.Alias == "" {+ spec.Alias = spec.Name+ }+ if spec.Labels == nil {+ spec.Labels = Labels(d.name, d.workspace)+ }+ return d.runner.Run(ctx, spec)+}++// NewDeps builds the Deps handed to one module's Start.+func NewDeps(handles map[Key]Handle, network, workspace string, name NameParts, r Runner) Deps {+ return Deps{handles: handles, network: network, workspace: workspace, name: name, runner: r}+}++// Get returns a typed handle, or false when the module was not declared.+//+// A generic method rather than a package function, which Go 1.27 allows. Modules+// still wrap it (wiremock.From, postgres.MustFrom) so call sites read as prose.+func (d Deps) Get[H Handle](k Key) (H, bool) {+ h, ok := d.handles[k]+ if !ok {+ var zero H+ return zero, false+ }+ typed, ok := h.(H)+ return typed, ok+}++// Plan is a validated, ordered set of modules ready to start.+type Plan struct {+ modules []Module+ scopes map[Key]Scope+}++func (p Plan) Modules() []Module { return p.modules }+func (p Plan) Scope(k Key) Scope { return p.scopes[k] }+func (p Plan) Declared(k Key) bool { _, ok := p.scopes[k]; return ok }++// Resolve validates a module set and returns it in dependency order.+//+// Everything here runs before a single container starts, so every failure below is+// instant and names the fix.+func Resolve(modules []Module, scopes map[Key]Scope) (Plan, error) {+ byKey := make(map[Key]Module, len(modules))+ for _, m := range modules {+ if _, dup := byKey[m.Key()]; dup {+ return Plan{}, fmt.Errorf("infra: module %q declared twice; use Named() to run a second instance", m.Key())+ }+ byKey[m.Key()] = m+ }++ for _, m := range modules {+ for _, dep := range m.Requires() {+ if _, ok := byKey[dep]; !ok {+ return Plan{}, fmt.Errorf("infra: %s requires %s, which was not declared", m.Key(), dep)+ }+ }+ if err := checkLifetimes(m, scopes, byKey); err != nil {+ return Plan{}, err+ }+ }++ ordered, err := topoSort(modules, byKey)+ if err != nil {+ return Plan{}, err+ }+ return Plan{modules: ordered, scopes: scopes}, nil+}++// checkLifetimes rejects a module that depends on something shorter lived than+// itself. This is not hypothetical: a Shared Infisical takes HTTP_PROXY at container+// start, so pointing it at a Package-scoped WireMock breaks every other package the+// moment that one finishes.+func checkLifetimes(m Module, scopes map[Key]Scope, byKey map[Key]Module) error {+ mine, ok := scopes[m.Key()]+ if !ok {+ return fmt.Errorf("infra: no scope declared for %s", m.Key())+ }+ for _, dep := range append(append([]Key{}, m.Requires()...), m.Optional()...) {+ if _, declared := byKey[dep]; !declared {+ continue // optional and absent+ }+ theirs := scopes[dep]+ if theirs.LongerLivedThan(mine) || theirs == mine {+ continue+ }+ return fmt.Errorf(+ "infra: %s is %s-scoped but depends on %s which is %s-scoped.\n"++ "A container reads its configuration once at start, so it cannot point at something that dies first.\n"++ "Either widen %s to %s, or narrow %s to %s.",+ m.Key(), mine, dep, theirs, dep, mine, m.Key(), theirs)+ }+ return nil+}++func topoSort(modules []Module, byKey map[Key]Module) ([]Module, error) {+ const (+ unvisited = iota+ inProgress+ done+ )+ state := make(map[Key]int, len(modules))+ out := make([]Module, 0, len(modules))+ var path []Key++ var visit func(m Module) error+ visit = func(m Module) error {+ switch state[m.Key()] {+ case done:+ return nil+ case inProgress:+ return fmt.Errorf("infra: dependency cycle: %s -> %s", joinKeys(path), m.Key())+ }+ state[m.Key()] = inProgress+ path = append(path, m.Key())++ deps := append(append([]Key{}, m.Requires()...), m.Optional()...)+ sort.Slice(deps, func(i, j int) bool { return deps[i] < deps[j] })+ for _, k := range deps {+ if dep, ok := byKey[k]; ok {+ if err := visit(dep); err != nil {+ return err+ }+ }+ }++ path = path[:len(path)-1]+ state[m.Key()] = done+ out = append(out, m)+ return nil+ }++ sorted := append([]Module{}, modules...)+ sort.Slice(sorted, func(i, j int) bool { return sorted[i].Key() < sorted[j].Key() })+ for _, m := range sorted {+ if err := visit(m); err != nil {+ return nil, err+ }+ }+ return out, nil+}++func joinKeys(ks []Key) string {+ s := make([]string, len(ks))+ for i, k := range ks {+ s[i] = string(k)+ }+ return strings.Join(s, " -> ")+}diff --git a/tests/infra/module_test.go b/tests/infra/module_test.gonew file mode 100644index 0000000000..2c68810d5c--- /dev/null+++ b/tests/infra/module_test.go@@ -0,0 +1,179 @@+package infra++import (+ "context"+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/internal/spec"+)++type fakeModule struct {+ key Key+ requires []Key+ optional []Key+}++func (f fakeModule) Key() Key { return f.key }+func (f fakeModule) Name() NameParts {+ return NameParts{Module: string(f.key)}+}+func (f fakeModule) Requires() []Key { return f.requires }+func (f fakeModule) Optional() []Key { return f.optional }+func (f fakeModule) Start(context.Context, Deps) (Handle, error) {+ return nil, nil+}++func mods(m ...Module) []Module { return m }++func TestResolve(t *testing.T) {+ t.Parallel()++ t.Run("ok/orders dependencies before dependents", func(t *testing.T) {+ t.Parallel()+ plan, err := Resolve(+ mods(+ fakeModule{key: "infisical", requires: []Key{"postgres", "redis"}},+ fakeModule{key: "postgres"},+ fakeModule{key: "redis"},+ ),+ map[Key]Scope{"infisical": Shared, "postgres": Shared, "redis": Shared},+ )+ if err != nil {+ t.Fatalf("Resolve() = %v", err)+ }+ got := keysOf(plan.Modules())+ if got[len(got)-1] != "infisical" {+ t.Fatalf("infisical must start last, got order %v", got)+ }+ })++ t.Run("ok/an optional dependency that is absent is not an error", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Infisical consumes wiremock and smtp if present and ignores them if not,+ which is what lets a suite opt out of stubbing without a second code path.`)++ _, err := Resolve(+ mods(fakeModule{key: "infisical", optional: []Key{"wiremock"}}),+ map[Key]Scope{"infisical": Shared},+ )+ if err != nil {+ t.Fatalf("Resolve() = %v", err)+ }+ })++ t.Run("invalid/a missing required dependency names the fix", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `This has to fail before any container starts. Otherwise it surfaces as a+ connection timeout ninety seconds later, pointing at the wrong thing.`)++ _, err := Resolve(+ mods(fakeModule{key: "infisical", requires: []Key{"postgres"}}),+ map[Key]Scope{"infisical": Shared},+ )+ if err == nil {+ t.Fatal("expected an error")+ }+ if !strings.Contains(err.Error(), "requires postgres") {+ t.Fatalf("error should name the missing module, got: %v", err)+ }+ })++ t.Run("invalid/a module may not depend on something shorter lived", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `A Shared Infisical takes HTTP_PROXY at container start. Pointing it at a+ Package-scoped WireMock breaks every other package the moment that one finishes.+ This is the shape the first draft of the design had, which is why it is checked.`)++ _, err := Resolve(+ mods(+ fakeModule{key: "infisical", optional: []Key{"wiremock"}},+ fakeModule{key: "wiremock"},+ ),+ map[Key]Scope{"infisical": Shared, "wiremock": Package},+ )+ if err == nil {+ t.Fatal("expected an error")+ }+ for _, want := range []string{"infisical is shared-scoped", "wiremock which is pkg-scoped", "Either widen"} {+ if !strings.Contains(err.Error(), want) {+ t.Fatalf("error should contain %q, got: %v", want, err)+ }+ }+ })++ t.Run("ok/a shorter lived module may depend on a longer lived one", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `An Isolated package starts its own Infisical but still adopts the shared+ Mailpit, which is the whole reason mixed scopes inside one package must work.`)++ _, err := Resolve(+ mods(+ fakeModule{key: "infisical", optional: []Key{"mailpit"}},+ fakeModule{key: "mailpit"},+ ),+ map[Key]Scope{"infisical": Package, "mailpit": Shared},+ )+ if err != nil {+ t.Fatalf("Resolve() = %v", err)+ }+ })++ t.Run("invalid/the same module declared twice points at Named", func(t *testing.T) {+ t.Parallel()+ _, err := Resolve(+ mods(fakeModule{key: "postgres"}, fakeModule{key: "postgres"}),+ map[Key]Scope{"postgres": Shared},+ )+ if err == nil || !strings.Contains(err.Error(), "Named()") {+ t.Fatalf("error should point at Named(), got: %v", err)+ }+ })++ t.Run("invalid/a dependency cycle is reported with its path", func(t *testing.T) {+ t.Parallel()+ _, err := Resolve(+ mods(+ fakeModule{key: "a", requires: []Key{"b"}},+ fakeModule{key: "b", requires: []Key{"a"}},+ ),+ map[Key]Scope{"a": Shared, "b": Shared},+ )+ if err == nil || !strings.Contains(err.Error(), "cycle") {+ t.Fatalf("expected a cycle error, got: %v", err)+ }+ })+}++func TestDepsGet(t *testing.T) {+ t.Parallel()++ type pgHandle struct{ Handle }+ deps := Deps{handles: map[Key]Handle{"postgres": pgHandle{}}}++ t.Run("ok/a declared module comes back typed", func(t *testing.T) {+ t.Parallel()+ if _, ok := deps.Get[pgHandle]("postgres"); !ok {+ t.Fatal("declared module was not found")+ }+ })++ t.Run("notfound/an absent optional module reports false rather than panicking", func(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Optional dependencies are the whole reason a suite can opt out of WireMock+ or SMTP without a second code path. If an absent one panicked, every consumer would+ need a nil check and the option would stop being optional.`)++ if _, ok := deps.Get[pgHandle]("redis"); ok {+ t.Fatal("absent module reported as present")+ }+ })+}++func keysOf(ms []Module) []Key {+ out := make([]Key, len(ms))+ for i, m := range ms {+ out[i] = m.Key()+ }+ return out+}diff --git a/tests/infra/names.go b/tests/infra/names.gonew file mode 100644index 0000000000..9780d2fe6b--- /dev/null+++ b/tests/infra/names.go@@ -0,0 +1,67 @@+package infra++import (+ "regexp"+ "strings"+)++// Prefix is on every container and network the harness creates. Short on purpose:+// `docker ps` truncates the NAMES column and these appear constantly.+const Prefix = "inf"++// NetworkName is the single network. Package-scoped containers join it too, so an+// Isolated suite can still reach the shared Mailpit. It holds no state.+const NetworkName = Prefix + "-net"++var unsafeNameChars = regexp.MustCompile(`[^a-zA-Z0-9_.-]+`)++// NameParts is everything that can appear in a container name.+//+// A container's name is its identity: adopt-or-create matches on it. So a name must+// carry exactly what should force a fresh container and nothing that varies for any+// other reason. Put something per-process in here and nothing ever adopts.+type NameParts struct {+ Scope Scope+ ScopeID string // package path for Package, a short random for Test, empty for Shared+ Module string // "postgres", "infisical"+ Instance string // from Named(), empty when there is only ever one++ // Fingerprint forces a new container when the thing it identifies changes.+ //+ // Only set it where staleness would be SILENT. Infisical carries its Docker image+ // ID, because a stale app container runs your previous code and every test still+ // passes. Postgres does not: a schema mismatch makes the app exit at boot with a+ // migration error, which is loud, diagnosable, and fixed by `inf down`.+ Fingerprint string+}++// ContainerName renders a name of the form:+//+// inf-shared-postgres+// inf-shared-postgres-rotation+// inf-shared-infisical-9f8e7d6c+// inf-pkg-suites-instance-postgres+// inf-test-a1b2-infisical+func ContainerName(p NameParts) string {+ segments := []string{Prefix, p.Scope.String()}+ if p.ScopeID != "" {+ segments = append(segments, Sanitize(p.ScopeID))+ }+ segments = append(segments, Sanitize(p.Module))+ if p.Instance != "" {+ segments = append(segments, Sanitize(p.Instance))+ }+ if p.Fingerprint != "" {+ segments = append(segments, Sanitize(p.Fingerprint))+ }+ return strings.Join(segments, "-")+}++// Sanitize maps arbitrary text into what Docker accepts in a name. Docker allows+// [a-zA-Z0-9][a-zA-Z0-9_.-]* so a package path like "suites/instance" has to fold to+// "suites-instance".+func Sanitize(s string) string {+ s = unsafeNameChars.ReplaceAllString(s, "-")+ s = strings.Trim(s, "-._")+ return strings.ToLower(s)+}diff --git a/tests/infra/names_test.go b/tests/infra/names_test.gonew file mode 100644index 0000000000..b78a59c88f--- /dev/null+++ b/tests/infra/names_test.go@@ -0,0 +1,84 @@+package infra++import (+ "testing"++ "github.com/Infisical/infisical/tests/internal/spec"+)++func TestContainerName(t *testing.T) {+ t.Parallel()++ for _, tc := range []struct {+ name string+ why string+ in NameParts+ want string+ }{+ {+ name: "ok/shared module has no scope id",+ in: NameParts{Scope: Shared, Module: "postgres"},+ want: "inf-shared-postgres",+ },+ {+ name: "ok/a Named instance is distinct from the default",+ why: "The rotation suites need a target database separate from the app's own.",+ in: NameParts{Scope: Shared, Module: "postgres", Instance: "rotation"},+ want: "inf-shared-postgres-rotation",+ },+ {+ name: "ok/infisical carries its image id",+ why: `A stale app container runs your previous code and every test still passes, ` ++ `so this is the one place staleness is silent and needs a fingerprint.`,+ in: NameParts{Scope: Shared, Module: "infisical", Fingerprint: "9f8e7d6c"},+ want: "inf-shared-infisical-9f8e7d6c",+ },+ {+ name: "ok/package scope is qualified by package path",+ why: `Two Isolated packages running under -p 4 must not adopt each other's ` ++ `containers, which is the precise opposite of what Isolated means.`,+ in: NameParts{Scope: Package, ScopeID: "suites/instance", Module: "postgres"},+ want: "inf-pkg-suites-instance-postgres",+ },+ {+ name: "ok/test scope carries a unique id",+ in: NameParts{Scope: Test, ScopeID: "a1b2", Module: "infisical"},+ want: "inf-test-a1b2-infisical",+ },+ {+ name: "ok/unsafe characters fold to hyphens",+ why: "Docker accepts [a-zA-Z0-9][a-zA-Z0-9_.-]* only, so a package path has to fold.",+ in: NameParts{Scope: Package, ScopeID: "Suites/PKI v2", Module: "postgres"},+ want: "inf-pkg-suites-pki-v2-postgres",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ spec.Why(t, tc.why)+ if got := ContainerName(tc.in); got != tc.want {+ t.Fatalf("ContainerName() = %q, want %q", got, tc.want)+ }+ })+ }+}++func TestContainerName_ScopesDoNotCollide(t *testing.T) {+ t.Parallel()+ spec.Why(t, `Names are identity under adopt-or-create. If a Package-scoped container can+ land on the same name as a Shared one, an Isolated suite silently adopts the shared+ stack and stops being isolated, which is the one thing it exists to guarantee.`)++ postgres := func(s Scope, id string) string {+ return ContainerName(NameParts{Scope: s, ScopeID: id, Module: "postgres"})+ }++ shared := postgres(Shared, "")+ pkgA := postgres(Package, "suites/instance")+ pkgB := postgres(Package, "suites/sso")++ for _, pair := range [][2]string{{shared, pkgA}, {shared, pkgB}, {pkgA, pkgB}} {+ if pair[0] == pair[1] {+ t.Errorf("names collide: %q", pair[0])+ }+ }+}diff --git a/tests/infra/postgres/postgres.go b/tests/infra/postgres/postgres.gonew file mode 100644index 0000000000..0f1885003e--- /dev/null+++ b/tests/infra/postgres/postgres.go@@ -0,0 +1,123 @@+// Package postgres runs a Postgres container for the harness.+package postgres++import (+ "context"+ "fmt"++ "github.com/Infisical/infisical/tests/infra"+)++const (+ // Key is the default instance. A Named() instance qualifies it, so+ // postgres.Module(postgres.Named("rotation")) is "postgres:rotation" and cannot+ // collide with the app's own database.+ Key = infra.Key("postgres")++ port = 5432+ user = "infisical"+ password = "infisical"+)++type module struct {+ instance string+ image string+ database string+ command []string+}++type Option func(*module)++// Named runs a second, independent Postgres. The rotation suites need a target+// database separate from the application's own.+func Named(name string) Option { return func(m *module) { m.instance = name } }++func WithDatabase(db string) Option { return func(m *module) { m.database = db } }+func WithImage(img string) Option { return func(m *module) { m.image = img } }++func Module(opts ...Option) infra.Module {+ m := &module{+ image: "postgres:14-alpine",+ database: "infisical_test",+ // max_locks_per_transaction matches the dev stack. The application holds+ // enough locks in one transaction to need it.+ command: []string{"postgres", "-c", "max_locks_per_transaction=512"},+ }+ for _, o := range opts {+ o(m)+ }+ return m+}++func (m *module) Key() infra.Key {+ if m.instance == "" {+ return Key+ }+ return Key + infra.Key(":"+m.instance)+}++func (m *module) Requires() []infra.Key { return nil }+func (m *module) Optional() []infra.Key { return nil }++func (m *module) Name() infra.NameParts {+ return infra.NameParts{Module: "postgres", Instance: m.instance}+}++func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error) {+ c, err := d.Run(ctx, infra.ContainerSpec{+ Image: m.image,+ Command: m.command,+ Env: map[string]string{+ "POSTGRES_USER": user,+ "POSTGRES_PASSWORD": password,+ "POSTGRES_DB": m.database,+ },+ Ports: []int{port},+ // `up --wait` treats a container with no healthcheck as ready once it is+ // running, which for Postgres is before it accepts connections.+ Ready: infra.ExecReady("pg_isready", "-U", user, "-d", m.database),+ })+ if err != nil {+ return nil, err+ }+ return &Handle{c: c, database: m.database}, nil+}++// Handle is a running Postgres.+type Handle struct {+ c infra.Container+ database string+}++func (h *Handle) Endpoint(m infra.Mode) infra.Endpoint { return h.c.Endpoint(m, port) }+func (h *Handle) Stop(ctx context.Context) error { return h.c.Stop(ctx) }+func (h *Handle) Database() string { return h.database }++// DSN is the connection string in one mode. Internal for another container,+// External for the Go test process. Saying which is not optional.+func (h *Handle) DSN(m infra.Mode) string {+ e := h.Endpoint(m)+ return fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", user, password, e.HostPort(), h.database)+}++// From is for other MODULES during Start: an optional dependency.+func From(d infra.Deps, instance ...string) (*Handle, bool) {+ return d.Get[*Handle](key(instance...))+}++// MustFrom is for a required dependency. Unreachable when Resolve has run, since it+// rejects a missing requirement before any container starts.+func MustFrom(d infra.Deps, instance ...string) *Handle {+ h, ok := From(d, instance...)+ if !ok {+ panic("infra/postgres: MustFrom called for a module that was not declared")+ }+ return h+}++func key(instance ...string) infra.Key {+ if len(instance) == 0 || instance[0] == "" {+ return Key+ }+ return Key + infra.Key(":"+instance[0])+}diff --git a/tests/infra/postgres/postgres_test.go b/tests/infra/postgres/postgres_test.gonew file mode 100644index 0000000000..a8417bb2ce--- /dev/null+++ b/tests/infra/postgres/postgres_test.go@@ -0,0 +1,100 @@+package postgres_test++import (+ "context"+ "os"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/postgres"+ "github.com/Infisical/infisical/tests/internal/spec"+)++// These need Docker. Skipped when INFRA_DOCKER_TESTS is unset so `make test-unit`+// stays under a second.+func requireDocker(t *testing.T) {+ t.Helper()+ if os.Getenv("INFRA_DOCKER_TESTS") == "" {+ t.Skip("set INFRA_DOCKER_TESTS=1 to run container tests")+ }+}++func start(t *testing.T, opts ...postgres.Option) *postgres.Handle {+ t.Helper()+ ctx := t.Context()+ log := infra.NewLogger()+ runner := infra.NewRunner(infra.Workspace(), log)+ if err := runner.Network(ctx, infra.NetworkName); err != nil {+ t.Fatalf("network: %v", err)+ }++ m := postgres.Module(opts...)+ name := m.Name()+ name.Scope = infra.Test+ name.ScopeID = infra.Sanitize(t.Name())++ began := time.Now()+ h, err := m.Start(ctx, infra.NewDeps(nil, infra.NetworkName, infra.Workspace(), name, runner))+ if err != nil {+ t.Fatalf("start: %v", err)+ }+ pg := h.(*postgres.Handle)+ log.Decision("create", infra.ContainerName(name), pg.Endpoint(infra.External), time.Since(began), "")+ t.Cleanup(func() { _ = pg.Stop(context.WithoutCancel(ctx)) })+ return pg+}++func TestPostgres_Start(t *testing.T) {+ requireDocker(t)+ t.Parallel()++ t.Run("ok/is accepting connections once Start returns", func(t *testing.T) {+ requireDocker(t)+ t.Parallel()+ spec.Why(t, `The container being "running" is not the same as Postgres accepting+ connections, which is why readiness is pg_isready rather than a port check.`)++ pg := start(t)+ if got := pg.Endpoint(infra.External).Port; got == 0 || got == 5432 {+ t.Fatalf("external port should be an ephemeral mapping, got %d", got)+ }+ })++ t.Run("ok/internal and external addresses differ", func(t *testing.T) {+ requireDocker(t)+ t.Parallel()+ spec.Why(t, `Handing an Internal address to the test process, or an External one to+ another container, is the most common way to misuse a container harness. The two+ must be distinguishable at every call site.`)++ pg := start(t)+ in, ex := pg.Endpoint(infra.Internal), pg.Endpoint(infra.External)+ if in.Port != 5432 {+ t.Errorf("internal port = %d, want the container port 5432", in.Port)+ }+ if in.HostPort() == ex.HostPort() {+ t.Errorf("internal and external addresses are identical: %s", in.HostPort())+ }+ if in.Host == "127.0.0.1" || in.Host == "localhost" {+ t.Errorf("internal host should be the network alias, got %q", in.Host)+ }+ })++ t.Run("ok/a Named instance is a separate container", func(t *testing.T) {+ requireDocker(t)+ t.Parallel()+ spec.Why(t, `The rotation suites rotate credentials against a target database that+ must not be the application's own.`)++ app := start(t)+ target := start(t, postgres.Named("rotation"), postgres.WithDatabase("rotation_target"))++ if app.Endpoint(infra.External).Port == target.Endpoint(infra.External).Port {+ t.Fatal("Named() instance shares a container with the default")+ }+ if target.Database() != "rotation_target" {+ t.Fatalf("database = %q, want rotation_target", target.Database())+ }+ })+}diff --git a/tests/infra/ready.go b/tests/infra/ready.gonew file mode 100644index 0000000000..e2857addf1--- /dev/null+++ b/tests/infra/ready.go@@ -0,0 +1,88 @@+package infra++import (+ "context"+ "fmt"+ "net"+ "net/http"+ "strings"+ "time"+)++const (+ readyPoll = 250 * time.Millisecond+ readyTimeout = 90 * time.Second+)++// ExecReady polls a command inside the container until it exits zero.+func ExecReady(cmd ...string) ReadyFunc {+ return func(ctx context.Context, c Container) error {+ return poll(ctx, fmt.Sprintf("exec %s", strings.Join(cmd, " ")), func() error {+ code, out, err := c.Exec(ctx, cmd)+ if err != nil {+ return err+ }+ if code != 0 {+ return fmt.Errorf("exit %d: %s", code, strings.TrimSpace(out))+ }+ return nil+ })+ }+}++// TCPReady polls until the mapped port accepts a connection. The weakest useful+// check: it proves something is listening, not that it works.+func TCPReady(port int) ReadyFunc {+ return func(ctx context.Context, c Container) error {+ return poll(ctx, fmt.Sprintf("tcp %d", port), func() error {+ conn, err := net.DialTimeout("tcp", c.Endpoint(External, port).HostPort(), 2*time.Second)+ if err != nil {+ return err+ }+ return conn.Close()+ })+ }+}++// HTTPReady polls until path returns a 2xx.+func HTTPReady(port int, path string) ReadyFunc {+ return func(ctx context.Context, c Container) error {+ client := &http.Client{Timeout: 3 * time.Second}+ url := c.Endpoint(External, port).URL("http") + path+ return poll(ctx, "http "+path, func() error {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return err+ }+ resp, err := client.Do(req)+ if err != nil {+ return err+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode < 200 || resp.StatusCode > 299 {+ return fmt.Errorf("status %d", resp.StatusCode)+ }+ return nil+ })+ }+}++func poll(ctx context.Context, what string, check func() error) error {+ deadline := time.Now().Add(readyTimeout)+ var last error+ for {+ if err := check(); err == nil {+ return nil+ } else {+ last = err+ }+ if time.Now().After(deadline) {+ return fmt.Errorf("%s did not pass within %s, last error: %w", what, readyTimeout, last)+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-time.After(readyPoll):+ }+ }+}diff --git a/tests/infra/runner.go b/tests/infra/runner.gonew file mode 100644index 0000000000..2518229d23--- /dev/null+++ b/tests/infra/runner.go@@ -0,0 +1,214 @@+package infra++import (+ "context"+ "fmt"+ "io"+ "os"+ "os/exec"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/testcontainers/testcontainers-go"+ tcexec "github.com/testcontainers/testcontainers-go/exec"+ "github.com/testcontainers/testcontainers-go/network"+)++// dockerRunner is the only place in the harness that touches testcontainers.+//+// Modules go through Runner instead, which is what keeps each module about thirty+// lines and lets the adopt mechanism be replaced. That matters: testcontainers+// documents reuse-by-name as experimental and says the API is "subject to change for+// a more robust implementation that is not based on container names".+type dockerRunner struct {+ workspace string+ log Logger+ netName string++ mu sync.Mutex+ seen map[string]bool // names this process has already started+}++// NewRunner returns the default Docker-backed Runner.+func NewRunner(workspace string, log Logger) Runner {+ return &dockerRunner{workspace: workspace, log: log}+}++// Network creates the shared network if it is absent, and is a no-op otherwise.+//+// There is exactly one, with a fixed name, because a Package-scoped container has to+// join the same network as the Shared ones or an Isolated suite could not reach the+// shared Mailpit. testcontainers' network.New generates a random name per process,+// which would give every test binary its own island.+//+// Shelled out rather than using the Docker API, because importing the moby network+// types reintroduces an ambiguous import between github.com/moby/moby and+// github.com/moby/moby/api. This runs once per machine, so a subprocess is free.+func (r *dockerRunner) Network(ctx context.Context, name string) error {+ if r.netName == name {+ return nil+ }+ if err := exec.CommandContext(ctx, "docker", "network", "inspect", name).Run(); err == nil {+ r.netName = name+ return nil+ }++ out, err := exec.CommandContext(ctx, "docker", "network", "create",+ "--label", LabelScope+"=shared",+ "--label", LabelWorkspace+"="+r.workspace,+ name,+ ).CombinedOutput()+ // Two binaries starting at once race here; whoever loses sees "already exists",+ // which is the same outcome as winning.+ if err != nil && !strings.Contains(string(out), "already exists") {+ return fmt.Errorf("infra: creating network %s: %w: %s", name, err, strings.TrimSpace(string(out)))+ }+ r.netName = name+ return nil+}++func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container, error) {+ opts := []testcontainers.ContainerCustomizer{+ testcontainers.WithReuseByName(spec.Name),+ testcontainers.WithEnv(spec.Env),+ testcontainers.WithLabels(spec.Labels),+ }+ if len(spec.Ports) > 0 {+ ports := make([]string, len(spec.Ports))+ for i, p := range spec.Ports {+ ports[i] = strconv.Itoa(p) + "/tcp"+ }+ opts = append(opts, testcontainers.WithExposedPorts(ports...))+ }+ if len(spec.Command) > 0 {+ opts = append(opts, testcontainers.WithCmd(spec.Command...))+ }+ if r.netName != "" {+ alias := spec.Alias+ if alias == "" {+ alias = spec.Name+ }+ opts = append(opts, network.WithNetworkName([]string{alias}, r.netName))+ }+ for _, f := range spec.Files {+ mode := f.Mode+ if mode == 0 {+ mode = 0o644+ }+ opts = append(opts, testcontainers.WithFiles(testcontainers.ContainerFile{+ HostFilePath: f.Src,+ ContainerFilePath: f.Dst,+ FileMode: mode,+ }))+ }++ dc, err := testcontainers.Run(ctx, spec.Image, opts...)+ if err != nil {+ return Container{}, fmt.Errorf("infra: starting %s (%s): %w", spec.Name, spec.Image, err)+ }++ c := Container{+ ID: dc.GetContainerID(),+ Name: spec.Name,+ Adopted: r.adopted(ctx, spec.Name, dc),+ endpoint: func(m Mode, port int) Endpoint {+ if m == Internal {+ alias := spec.Alias+ if alias == "" {+ alias = spec.Name+ }+ return Endpoint{Host: alias, Port: port}+ }+ host, err := dc.Host(ctx)+ if err != nil {+ host = "127.0.0.1"+ }+ mapped, err := dc.MappedPort(ctx, strconv.Itoa(port)+"/tcp")+ if err != nil {+ return Endpoint{Host: host, Port: 0}+ }+ return Endpoint{Host: host, Port: int(mapped.Num())}+ },+ stop: func(ctx context.Context) error { return dc.Terminate(ctx) },+ exec: func(ctx context.Context, cmd []string) (int, string, error) {+ code, reader, err := dc.Exec(ctx, cmd, tcexec.Multiplexed())+ if err != nil {+ return code, "", err+ }+ out, _ := io.ReadAll(reader)+ return code, string(out), nil+ },+ logs: func(ctx context.Context) (string, error) {+ rc, err := dc.Logs(ctx)+ if err != nil {+ return "", err+ }+ defer func() { _ = rc.Close() }()+ out, err := io.ReadAll(rc)+ return string(out), err+ },+ }++ if spec.Ready != nil {+ if err := spec.Ready(ctx, c); err != nil {+ return c, fmt.Errorf("infra: %s never became ready: %w", spec.Name, err)+ }+ }+ return c, nil+}++// adopted reports whether an existing container was reused rather than created.+//+// Two signals, because neither is sufficient alone:+//+// - This process has already started a container of this name. Covers a single+// binary asking for the same module twice.+// - The container predates this process. Covers the case the whole design exists+// for: another test binary, or an earlier `go test`, created it.+//+// The first signal is the one a test exposed. Without it, a same-process reuse+// reports "create", because the container genuinely was created after this process+// started, just not by this call.+//+// Done by inspection rather than a pre-flight container list so the harness needs no+// direct dependency on the Docker API module, which has been splitting between+// github.com/docker/docker and github.com/moby/moby and is not worth tracking for a+// log line.+func (r *dockerRunner) adopted(ctx context.Context, name string, dc *testcontainers.DockerContainer) bool {+ r.mu.Lock()+ seenBefore := r.seen[name]+ if r.seen == nil {+ r.seen = map[string]bool{}+ }+ r.seen[name] = true+ r.mu.Unlock()++ if seenBefore {+ return true+ }++ info, err := dc.Inspect(ctx)+ if err != nil {+ return false+ }+ created, err := time.Parse(time.RFC3339Nano, info.Created)+ if err != nil {+ return false+ }+ return created.Before(processStart)+}++var processStart = time.Now()++// Workspace is the checkout that created a container. Recorded as a label but never+// part of identity, so `inf status` can tell you which worktree to ask before you+// reap something.+func Workspace() string {+ wd, err := os.Getwd()+ if err != nil {+ return "unknown"+ }+ return strings.TrimSuffix(wd, "/tests")+}diff --git a/tests/infra/runner_test.go b/tests/infra/runner_test.gonew file mode 100644index 0000000000..3d13a5330b--- /dev/null+++ b/tests/infra/runner_test.go@@ -0,0 +1,107 @@+package infra_test++import (+ "context"+ "os"+ "testing"++ "github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/internal/spec"+)++func requireDocker(t *testing.T) {+ t.Helper()+ if os.Getenv("INFRA_DOCKER_TESTS") == "" {+ t.Skip("set INFRA_DOCKER_TESTS=1 to run container tests")+ }+}++func TestRunner_AdoptOrCreate(t *testing.T) {+ requireDocker(t)+ spec.Why(t, `Adopt-or-create by name is what replaces a manifest file, a content hash and+ a config hash. If a second process creates instead of adopting, every binary in a+ `+"`go test ./...`"+` run pays for its own stack and the whole scheme is pointless.+ Nothing else in the suite exercises this, because a passing test looks identical+ either way.`)++ ctx := t.Context()+ runner := infra.NewRunner(infra.Workspace(), infra.NewLogger())+ if err := runner.Network(ctx, infra.NetworkName); err != nil {+ t.Fatalf("network: %v", err)+ }++ name := infra.ContainerName(infra.NameParts{+ Scope: infra.Shared,+ Module: "redis",+ // Not a fingerprint: a marker so this test cannot adopt a real shared Redis+ // that a suite is using, or leave one behind that a suite would adopt.+ Instance: "adopttest",+ })+ spec := infra.ContainerSpec{+ Name: name,+ Image: "redis:7-alpine",+ Ports: []int{6379},+ Ready: infra.ExecReady("redis-cli", "ping"),+ }++ first, err := runner.Run(ctx, spec)+ if err != nil {+ t.Fatalf("first run: %v", err)+ }+ t.Cleanup(func() { _ = first.Stop(context.WithoutCancel(ctx)) })++ if first.Adopted {+ t.Fatal("first run reported adopt; a container of this name was left behind by an earlier run")+ }++ second, err := runner.Run(ctx, spec)+ if err != nil {+ t.Fatalf("second run: %v", err)+ }++ if !second.Adopted {+ t.Error("second run created a new container instead of adopting the first")+ }+ if second.ID != first.ID {+ t.Errorf("adopted a different container: %s then %s", first.ID, second.ID)+ }+ if a, b := first.Endpoint(infra.External, 6379), second.Endpoint(infra.External, 6379); a != b {+ t.Errorf("adopted container moved ports: %s then %s", a.HostPort(), b.HostPort())+ }+}++func TestRunner_NameChangeCreatesNewContainer(t *testing.T) {+ requireDocker(t)+ spec.Why(t, `The other half of the same rule. Infisical puts its Docker image ID in the+ container name precisely so that changed code means a different name means a fresh+ container. A stale app container would run your previous code with every test still+ passing, which is the worst outcome available.`)++ ctx := t.Context()+ runner := infra.NewRunner(infra.Workspace(), infra.NewLogger())+ if err := runner.Network(ctx, infra.NetworkName); err != nil {+ t.Fatalf("network: %v", err)+ }++ base := infra.NameParts{Scope: infra.Shared, Module: "redis", Instance: "fptest"}+ run := func(fingerprint string) infra.Container {+ t.Helper()+ p := base+ p.Fingerprint = fingerprint+ c, err := runner.Run(ctx, infra.ContainerSpec{+ Name: infra.ContainerName(p),+ Image: "redis:7-alpine",+ Ports: []int{6379},+ Ready: infra.ExecReady("redis-cli", "ping"),+ })+ if err != nil {+ t.Fatalf("run %s: %v", fingerprint, err)+ }+ t.Cleanup(func() { _ = c.Stop(context.WithoutCancel(ctx)) })+ return c+ }++ if a, b := run("aaaa1111"), run("bbbb2222"); a.ID == b.ID {+ t.Fatal("a different fingerprint adopted the same container")+ }+}diff --git a/tests/internal/spec/spec.go b/tests/internal/spec/spec.gonew file mode 100644index 0000000000..80004090f3--- /dev/null+++ b/tests/internal/spec/spec.go@@ -0,0 +1,53 @@+// Package spec carries the rationale for a test into its output.+package spec++import (+ "strings"+ "testing"+)++// Why records why a test exists, for the cases where the name cannot carry the+// reason. It is t.Log rather than a comment for three reasons: it appears on+// FAILURE, so whoever is looking at a red run gets the rationale without opening the+// file; it is harvestable from `go test -json` into the generated spec document; and+// it sits at the top of the test, so it still serves a reader of the code.+//+// Most tests should not have one. The bar is the same one CLAUDE.md sets for+// comments: it earns its place only by explaining why. A non-obvious constraint, a+// past incident, a spec the behaviour has to match, or logic that looks wrong until+// you know the reason. If the majority of your subtests need one, the names are+// doing too little work.+//+// An empty string is a no-op, so a table-driven case can leave it unset.+func Why(t *testing.T, why string) {+ t.Helper()+ if strings.TrimSpace(why) == "" {+ return+ }+ t.Log("why: " + dedent(why))+}++// Ref is the short form: a pointer to the rule a test enforces, with no prose. It+// makes the generated spec document link back to the source of the requirement.+func Ref(t *testing.T, ref string) {+ t.Helper()+ if strings.TrimSpace(ref) == "" {+ return+ }+ t.Log("ref: " + ref)+}++// dedent strips the leading indentation that a raw Go string literal picks up from+// the surrounding code, so multi-line rationale reads as prose in test output.+func dedent(s string) string {+ lines := strings.Split(strings.TrimRight(s, " \t\n"), "\n")+ out := make([]string, 0, len(lines))+ for i, l := range lines {+ if i == 0 {+ out = append(out, strings.TrimSpace(l))+ continue+ }+ out = append(out, strings.TrimLeft(l, " \t"))+ }+ return strings.Join(out, "\n")+}