[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74CNF6BYDHCVW5YX8Y5D6KW":3,"skill-same:01M74CNF6BYDHCVW5YX8Y5D6KW":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M74CNF6BYDHCVW5YX8Y5D6KW","connector-testing",null,"Write tests for Apache Iggy connectors - sinks, sources, transforms, SDK, runtime. Covers BDD unit-test naming, the canonical source state round-trip tests, and the real-infra integration test targets under `\u003Cpackage>\u002Ftests\u002F\u003Csuite>\u002F` with `testcontainers-modules` + `#[iggy_harness]`. Load when writing or reviewing tests anywhere in this repository (`src\u002F` unit tests, `tests\u002F` targets, `testing\u002F`). Use for connector test authoring. NOT for runtime internals or non-connector test patterns.","apache\u002Figgy-connectors","apache","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F47359?v=4","01M6AC83E6K4FDKK7HZ8WNMQKE","The Apache Software Foundation","01M74CMTGQZXBYXVEKC91YP22N",5,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnector-testing\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: connector-testing\ndescription: Write tests for Apache Iggy connectors - sinks, sources, transforms, SDK, runtime. Covers BDD unit-test naming, the canonical source state round-trip tests, and the real-infra integration test targets under `\u003Cpackage>\u002Ftests\u002F\u003Csuite>\u002F` with `testcontainers-modules` + `#[iggy_harness]`. Load when writing or reviewing tests anywhere in this repository (`src\u002F` unit tests, `tests\u002F` targets, `testing\u002F`). Use for connector test authoring. NOT for runtime internals or non-connector test patterns.\n---\n\n# Testing Apache Iggy Connectors\n\n> **Universal connector rules** live in\n> [connectors-overview](..\u002Fconnectors-overview\u002FSKILL.md). Repo-wide testing rules (`#[iggy_harness]`, BDD naming, harness layout) live in [AGENTS.md](..\u002F..\u002F..\u002FAGENTS.md#testing). This skill covers connector-specific test conventions.\n\n## Contents\n\n- [STOP and ask the user before](#stop-and-ask-the-user-before)\n- [Unit tests](#unit-tests)\n- [Integration tests (real infra via Docker)](#integration-tests-real-infra-via-docker)\n- [SDK + runtime tests](#sdk--runtime-tests)\n- [CI \u002F verification flow](#ci--verification-flow)\n- [Common pitfalls](#common-pitfalls)\n- [Examples worth copying](#examples-worth-copying)\n\n## STOP and ask the user before\n\n- Mocking the database or backend in an integration test - we hit real infra via `testcontainers-modules` (mocks miss migration bugs).\n- Adding a unit test that requires Docker - that belongs in the package's test target `\u003Cplugin>\u002Ftests\u002F\u003Cbackend>\u002F`, not in `\u003Cplugin>\u002Fsrc\u002Flib.rs`.\n- Skipping the four canonical source state tests - they're mandatory for every source plugin.\n- Naming a test `test_foo` \u002F `does_bar` - we use BDD `given_X_when_Y_should_Z`.\n\nThere are **two distinct test layers**. Use both - they catch different bugs.\n\n| Layer                 | Location                                                 | What it covers                                                                                 | When required                                        |\n| --------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------- |\n| **Unit tests**        | `#[cfg(test)] mod tests` at EOF of `\u003Cplugin>\u002Fsrc\u002Flib.rs` | Config parsing, defaults, fallbacks, payload conversion, query\u002Fdocument building, state ser\u002Fde | Every plugin                                         |\n| **Integration tests** | `\u003Cplugin>\u002Ftests\u002F\u003Csuite>\u002F` (uses real backend via Docker) | End-to-end: runtime + plugin + real Postgres\u002FES\u002FIceberg\u002FMongo\u002Fetc. + Iggy server               | Every plugin that integrates with an external system |\n\n## Unit tests\n\n### Naming - BDD `given_when_should`\n\nMatch the convention used in the codebase (`sources\u002Frandom_source\u002Fsrc\u002Flib.rs::tests`, `sinks\u002Fpostgres_sink\u002Fsrc\u002Flib.rs::tests`):\n\n```rust\n#[test]\nfn given_persisted_state_should_restore_messages_produced() { ... }\n\n#[test]\nfn given_no_state_should_start_fresh() { ... }\n\n#[test]\nfn given_invalid_duration_should_fall_back_to_default() { ... }\n\n#[test]\nfn given_payload_json_should_serialize_correctly() { ... }\n```\n\nYou may **omit one part** when the test is small (`given_X_should_Y` instead of full `given_X_when_Y_should_Z`), but **stay consistent within a file**. Imperative `test_foo` \u002F `does_bar` names are not the convention here.\n\nA test whose subject is a **type** rather than a scenario has no \"given\" to name, and drops the prefix: it reads `\u003Csubject>_should_\u003Cproperty>`. The canonical state round trip below is `state_should_be_serializable_and_deserializable` in all three shipped sources (`random_source`, `postgres_source`, `http_source`). Leave those as they are rather than bending them into the scenario form.\n\n### Prove a test can fail, before trusting it\n\nA passing test says nothing until you have watched it fail. Break the behaviour it names, run the\nsuite, and put the code back:\n\n```bash\n# commit first: this reverts with `git checkout --`, which discards\n# every uncommitted change in the file, not only the mutation\ngit status --porcelain -- \u003Cfile>            # must be empty\n\u003Cedit the guard out>\ncargo nextest run -p \u003Ccrate>                # expect a failure naming that test\ngit checkout -- \u003Cfile>\n```\n\nTwo failures this catches, both seen in review of `http_source`:\n\n- **A fixture that makes the interesting case unreachable.** A guard test for endpoint resurrection\n  passed `&[]` as the static config, so there was nothing to resurrect and the assertion held\n  whatever `restore` did.\n- **An assertion aimed at something self-healing.** A test for a teardown guard asserted on gauges,\n  which `Metrics::encode` rebuilds from the live instances on every scrape, so it passed with the\n  guard deleted. Delete such a test rather than keep it; a test that cannot fail is worse than none,\n  because it reads as coverage.\n\nWatch for an arm hidden behind a catch-all: `StatusClass::from` ends in `_ => ServerError`, so the\nredirect arm could be removed with every existing assertion still green.\n\n### `test_config()` helper\n\nEvery plugin's tests start with a small helper returning a tuned-down version of the production config. New tests extend it. don't construct from scratch each time.\n\n```rust\nfn test_config() -> RandomSourceConfig {\n    RandomSourceConfig {\n        interval: Some(\"100ms\".to_string()),\n        max_count: Some(100),\n        messages_range: Some((5, 10)),\n        payload_size: Some(50),\n    }\n}\n```\n\n### Async testing pattern\n\nThe trait methods are `async`. For unit tests, build a runtime locally - don't add `#[tokio::test]` in `src\u002Flib.rs` (it pulls test macros into prod build):\n\n```rust\n#[test]\nfn given_X_should_Y() {\n    let runtime = tokio::runtime::Runtime::new().unwrap();\n    runtime.block_on(async {\n        \u002F\u002F await calls here\n    });\n}\n```\n\n### Mandatory: four canonical source state tests\n\nEvery source must have these. Copy from `sources\u002Frandom_source\u002Fsrc\u002Flib.rs::tests`:\n\n```rust\n#[test]\nfn given_persisted_state_should_restore_\u003Cfield>() {\n    let state = State { \u002F* fields *\u002F };\n    let serialized = rmp_serde::to_vec(&state).expect(\"Failed to serialize state\");\n    let connector_state = ConnectorState(serialized);\n\n    let source = MySource::new(1, test_config(), Some(connector_state));\n\n    let runtime = tokio::runtime::Runtime::new().unwrap();\n    runtime.block_on(async {\n        let restored = source.state.lock().await;\n        assert_eq!(restored.\u003Cfield>, \u002F* expected *\u002F);\n    });\n}\n\n#[test]\nfn given_no_state_should_start_fresh() {\n    let source = MySource::new(1, test_config(), None);\n    \u002F* assert default state *\u002F\n}\n\n#[test]\nfn given_invalid_state_should_start_fresh() {\n    let invalid = ConnectorState(b\"not valid msgpack\".to_vec());\n    let source = MySource::new(1, test_config(), Some(invalid));\n    \u002F* assert default state *\u002F\n}\n\n#[test]\nfn state_should_be_serializable_and_deserializable() {\n    let original = State { \u002F* fields *\u002F };\n    let bytes = rmp_serde::to_vec(&original).unwrap();\n    let restored: State = rmp_serde::from_slice(&bytes).unwrap();\n    assert_eq!(original.\u003Cfield>, restored.\u003Cfield>);\n}\n```\n\nState is the only thing that survives a plugin restart. Silent corruption here means lost data on the next deploy.\n\n**The third test has two correct shapes, and which one applies is a design decision rather than a style choice.**\n\nStarting fresh is right when the state is a cursor. The worst case is re-reading from the beginning, which the at-least-once contract already permits, so discarding an undecodable cursor costs duplicates and nothing else.\n\nIt is wrong when the state carries something whose *absence* is a downgrade rather than a repeat. `http_source` keeps its revocation tombstones in state, so starting fresh after a decode failure would serve every revoked endpoint again, with its secret. Its `restore` returns `Err` instead and the connector refuses to open. A source in that position asserts the refusal:\n\n```rust\n#[test]\nfn given_invalid_state_should_refuse_to_open() {\n    let invalid = ConnectorState(b\"not valid msgpack\".to_vec());\n\n    let restored = MyState::restore(&config_entries(), Some(invalid), 1);\n\n    assert!(\n        restored.is_err(),\n        \"discarding this state silently would re-serve what it was revoking\"\n    );\n}\n```\n\nName the test for whichever it is and say why in a comment. What is never right is starting fresh silently when the state that was discarded was load-bearing.\n\n### Sink unit tests\n\nCover pure per-message logic:\n\n- Config defaults + optional fields + invalid values → fallback.\n- Payload conversion for each `Payload` variant the sink claims to handle.\n- Header encoding (especially base64 for binary headers).\n- Query\u002Fdocument building (e.g., `postgres_sink::build_batch_insert_query`).\n- Transient vs permanent error classification (e.g., `postgres_sink::is_transient_error`).\n\n### Transform tests\n\nFour branches must be covered (see `connector-transform`):\n\n1. Happy path: matching input → expected output.\n2. Filter path: input that should be dropped returns `Ok(None)`.\n3. Pass-through path: non-JSON payload (or unmatched condition) returns `Ok(Some(unchanged))`.\n4. Invalid config: `new()` returns `Err(Error::InvalidConfigValue(_))`.\n\n### What NOT to mock\n\n- The underlying client lib (sqlx, reqwest, mongodb). Tests would exercise the mock, not the code.\n- The Iggy server.\n- The runtime.\n\nIf you need a fake backend, use `wiremock` (a real local HTTP server) - see `sinks\u002Fhttp_sink\u002Ftests\u002Fhttp\u002F`.\n\n## Integration tests (real infra via Docker)\n\nEach plugin that integrates with an external service (Postgres, Elasticsearch, Iceberg, MongoDB, InfluxDB, Quickwit, HTTP\u002Fwiremock) owns its integration tests: one test target per backend suite in `tests\u002F\u003Csuite>\u002F` of its own package, with a paired fixture + test file there. A backend with both a sink and a source has a target of the same name in both packages. Fixtures that more than one package needs live in `testing\u002F` (crate `iggy_connector_testing`).\n\n### Layout\n\n```text\nsinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002F      Test target `postgres` of iggy_connector_postgres_sink\n├── main.rs                   mod declarations, install_log_capture!(), shared constants (TEST_MESSAGE_COUNT, POLL_ATTEMPTS, ...)\n├── fixtures\u002F\n│   ├── sink.rs               PostgresSinkFixture, PostgresSinkByteaFixture, PostgresSinkJsonFixture\n│   └── mod.rs                re-exports, plus PostgresOps from iggy_connector_testing\n├── postgres_sink.rs          The actual #[iggy_harness] tests\n├── restart.rs                Sink restart tests through the runtime HTTP API\n└── sink.toml                 Runtime config used by the tests\n\nsources\u002Fpostgres_source\u002Ftests\u002Fpostgres\u002F  Test target `postgres` of iggy_connector_postgres_source\n├── main.rs\n├── fixtures\u002F\n│   ├── source.rs             PostgresSourceJsonFixture, PostgresSourceJsonbFixture, ...\n│   ├── cdc.rs                PostgresSourceCdcFixture, PostgresSourceCdcSlowPollFixture\n│   └── mod.rs                re-exports, plus PostgresOps and PostgresSourceOps from iggy_connector_testing\n├── postgres_source.rs  postgres_source_cdc.rs\n├── source.toml  source_cdc_restart.toml\n└── cdc_restart_connectors\u002F   Connector directory of source_cdc_restart.toml\n\ntesting\u002Fsrc\u002F                  iggy_connector_testing\n├── lib.rs                    TestMessage, create_test_messages, TEST_CONTAINER_PREFIX, unique_container_name\n├── postgres.rs               PostgresContainer (testcontainers wrapper), PostgresOps, PostgresSourceOps, env-var consts\n├── random_source_liveness.rs assert_produces_messages\n└── elasticsearch.rs  influxdb.rs  influxdb_v3.rs  floci.rs\n\nruntime\u002Ftests\u002F\n├── runtime\u002F                  Runtime-only tests (error isolation, missing plugin, ...)\n├── api\u002F                      HTTP control plane tests\n├── http_config_provider\u002F     HTTP config provider end-to-end, WireMock fixture in fixtures.rs\n└── config_env_listing.rs     Env-var listing of the runtime binary\n```\n\nA container that only one package uses lives in that target's `fixtures\u002Fcontainer.rs` (for example `sinks\u002Fhttp_sink\u002Ftests\u002Fhttp\u002Ffixtures\u002Fcontainer.rs`).\n\n### Container naming + cleanup\n\nEvery test container MUST be named with the `iggy-test-` prefix so a single\nsweep reaps them: `docker ps -aqf 'name=^iggy-test-' | xargs -r docker rm -f`.\nReuse fixtures keep their container running, and a crashed run can orphan any\nfixture's container, so run the sweep after a test session. New fixtures get\nthis for free by naming through `iggy_connector_testing::unique_container_name(\"\u003Csvc>\")`, which\nappends a uuid for parallel-safe ephemeral containers. Reuse fixtures use a fixed\n`iggy-test-\u003Csvc>` literal instead, because the stable name is what lets later\nnextest processes attach to the same container via `ReuseDirective::Always`. Do\nnot hand-roll a different prefix - the sweep only finds `iggy-test-*`.\n\nAs of now only `elasticsearch` and `doris` share a container. Both have a slow\nboot (JVM \u002F Doris FE+BE, tens of seconds), so reusing one across the whole\nregression beats spinning a fresh one per test. Every other fixture boots a\nfresh, ephemeral container per test - cheap enough that the isolation is worth\nmore than the reuse.\n\n### The `#[iggy_harness]` proc macro\n\nEach integration test is annotated with this macro from the `integration` crate of apache\u002Figgy at the core pin. It launches the prebuilt `target\u002Fdebug\u002Figgy-server` (from `.\u002Fscripts\u002Fbuild-test-server.sh`) and optionally `target\u002Fdebug\u002Figgy-connectors` for the duration of the test, runs the seeds, then injects a `&TestHarness` and your fixture. It never builds them: run `cargo build` first, or a stale binary runs.\n\n```rust\nuse integration::harness::seeds;\nuse integration::iggy_harness;\n\n#[iggy_harness(\n    server(connectors_runtime(config_path = \"tests\u002Fpostgres\u002Fsink.toml\")),\n    seed = seeds::connector_stream\n)]\nasync fn json_messages_sink_stores_as_bytea(\n    harness: &TestHarness,\n    fixture: PostgresSinkFixture,\n) {\n    let client = harness.root_client().await.unwrap();\n    let pool = fixture.create_pool().await.expect(\"Failed to create pool\");\n    fixture.wait_for_table(&pool, \"iggy_messages\").await;\n    \u002F\u002F ... send messages, assert on rows\n}\n```\n\nKey pieces:\n\n- `server(connectors_runtime(config_path = ...))` boots the connectors runtime against the given TOML.\n  The path is relative to the package directory: cargo and nextest run each test binary there, and the runtime inherits that working directory.\n  Most of these TOMLs set `config_dir = \".\"`, so the runtime loads the plugin's own `config.toml` from the package root (it skips `Cargo.toml`).\n  The fixture then sets the plugin path to the bare file name, for example `ENV_SINK_PATH` = `libiggy_connector_postgres_sink`, and the runtime finds it next to its own binary in `target\u002Fdebug\u002F`.\n  A test that needs other connector files keeps them in a directory under `tests\u002F\u003Csuite>\u002F`, for example `tests\u002Fpostgres\u002Fcdc_restart_connectors\u002F` in `sources\u002Fpostgres_source\u002F`.\n- `seed = seeds::connector_stream` runs the named seed to create the test stream\u002Ftopic.\n- `fixture: PostgresSinkFixture` - the test harness calls `PostgresSinkFixture::setup()` (which spins up the testcontainer) and injects the result.\n- `harness: &TestHarness` (defined in `core\u002Fintegration\u002Fsrc\u002Fharness\u002Forchestrator\u002Fharness.rs` of apache\u002Figgy) exposes `.root_client().await`, `.connectors_runtime().expect(\"...\").http_url()`, etc. - `connectors_runtime()` returns `Option`, so `.expect()` first.\n\n### Fixture pattern (`TestFixture` trait)\n\nEach fixture implements `integration::harness::TestFixture`. Pattern:\n\n```rust\n\u002F\u002F testing\u002Fsrc\u002F\u003Cbackend>.rs when several packages use it, else tests\u002F\u003Csuite>\u002Ffixtures\u002Fcontainer.rs\n\nuse testcontainers_modules::{\n    \u003Cbackend_module>,\n    testcontainers::{ContainerAsync, runners::AsyncRunner},\n};\n\npub struct MyContainer {\n    container: ContainerAsync\u003C\u003Cbackend_module>::Image>,\n    pub connection_string: String,\n}\n\nimpl MyContainer {\n    pub async fn start() -> Result\u003CSelf, TestBinaryError> {\n        let container = \u003Cbackend_module>::Image::default().start().await?;\n        let port = container.get_host_port_ipv4(DEFAULT_PORT).await?;\n        Ok(Self {\n            container,\n            connection_string: format!(\"...:\u002F\u002Flocalhost:{port}\"),\n        })\n    }\n}\n```\n\nThe fixture itself wraps the container and implements `TestFixture::setup()` to spin it up and inject env vars that the runtime picks up.\n\n### Env-var injection via `ConfigEnv`\n\nThe runtime's config structs derive `ConfigEnv` (`configs_derive::ConfigEnv`, applied in `runtime\u002Fsrc\u002Fconfigs\u002Fconnectors.rs` to `SinkConfig`, `SourceConfig`, `StreamConsumerConfig`, `StreamProducerConfig`). Fields are addressable by env var with a path-built prefix. Three concrete forms observed in `testing\u002Fsrc\u002Fpostgres.rs`:\n\n```rust\n\u002F\u002F Plugin-config fields (your sink\u002Fsource's own config struct):\n\u002F\u002F   IGGY_CONNECTORS_\u003CTYPE>_\u003CKEY>_PLUGIN_CONFIG_\u003CFIELD>\npub const ENV_SINK_CONNECTION_STRING: &str =\n    \"IGGY_CONNECTORS_SINK_POSTGRES_PLUGIN_CONFIG_CONNECTION_STRING\";\n\n\u002F\u002F Indexed nested fields (per-stream entries are a Vec):\n\u002F\u002F   IGGY_CONNECTORS_\u003CTYPE>_\u003CKEY>_STREAMS_\u003CINDEX>_\u003CFIELD>\npub const ENV_SINK_STREAMS_0_STREAM: &str =\n    \"IGGY_CONNECTORS_SINK_POSTGRES_STREAMS_0_STREAM\";\n\n\u002F\u002F Top-level scalar fields on SinkConfig\u002FSourceConfig itself:\n\u002F\u002F   IGGY_CONNECTORS_\u003CTYPE>_\u003CKEY>_\u003CFIELD>\npub const ENV_SINK_PATH: &str =\n    \"IGGY_CONNECTORS_SINK_POSTGRES_PATH\";\n```\n\n`\u003CTYPE>` is `SINK` or `SOURCE`. `\u003CKEY>` is the connector key (TOML key field, uppercased). `PLUGIN_CONFIG` is the literal segment used when reaching into your plugin's nested config. Fields marked `#[config_env(skip)]` (e.g., `transforms`, `plugin_config` as a whole) are NOT env-addressable. primitive leaves marked `#[config_env(leaf)]` are.\n\nThe fixture sets these in `setup()` before the runtime reads its config. This is how a dynamic container port reaches a static TOML.\n\n### Test naming for integration tests\n\nIntegration tests use a **descriptive declarative** style, not the unit-test `given_should` form. Match the codebase:\n\n```rust\nasync fn json_messages_sink_stores_as_bytea(...) { ... }\nasync fn binary_messages_sink_stores_as_bytea(...) { ... }\nasync fn json_messages_sink_stores_as_jsonb(...) { ... }\nasync fn delete_after_read_source_removes_rows_after_producing(...) { ... }\nasync fn processed_column_source_marks_rows_after_producing(...) { ... }\nasync fn state_persists_across_connector_restart(...) { ... }\nasync fn restart_sink_connector_continues_processing(...) { ... }\n```\n\nPattern: `\u003Csubject>_\u003Caction>_\u003Cobservation>`. Reads like a sentence describing what the test proves.\n\n### Polling vs sleeping\n\nIntegration tests poll until an expected condition - never `sleep(big_duration)`. Constants `POLL_ATTEMPTS` and `POLL_INTERVAL_MS` defined in each test target's `main.rs`. Fixture helpers like `PostgresSinkFixture::fetch_rows_as` and `PostgresSinkFixture::wait_for_table` encapsulate the pattern.\n\n### When to add an integration test\n\n- New sink\u002Fsource plugin → at minimum one happy-path test per supported `Schema` and per supported plugin mode. Concrete coverage in the `postgres` targets of `sinks\u002Fpostgres_sink\u002F` and `sources\u002Fpostgres_source\u002F`:\n  3 sink tests (`json_messages_sink_stores_as_bytea`, `binary_messages_sink_stores_as_bytea`, `json_messages_sink_stores_as_jsonb`) backed by 3 sink fixtures, plus 5 source fixtures (`Json`, `Jsonb`, `Bytea`, `Delete`, `Mark`), `state_persists_across_connector_restart` for state survival, and a dedicated `restart.rs` for sink restarts.\n- Bug fix in a plugin → regression test reproducing the bug.\n- Behavior that crosses the FFI boundary (state restart, transform chain, schema decode) → integration test, not unit test.\n\n### When NOT to add an integration test\n\n- Pure logic (query builder, payload converter) - that's a unit test.\n- Config validation - unit test.\n- Code paths already covered by an equivalent test for another backend, when the new backend has identical behavior.\n\n## SDK + runtime tests\n\n- `sdk\u002Ftests\u002F` - cross-module SDK concerns. In tree: `protobuf_integration.rs`, `flatbuffer_integration.rs` (round-trip schema decoders\u002Fencoders), `plugin_logging.rs`.\n- Runtime tests live under `runtime\u002Ftests\u002Fruntime\u002F`, `runtime\u002Ftests\u002Fapi\u002F` and `runtime\u002Ftests\u002Fhttp_config_provider\u002F`. They exercise the runtime alone (no plugin-specific backend, only `random_source` and `stdout_sink`) - error isolation, missing plugin, invalid config, HTTP API contract.\n\n## CI \u002F verification flow\n\nBefore pushing:\n\n```text\ncargo fmt --all\ncargo sort --no-format --grouped --workspace\ncargo clippy -p \u003Cpackage> --all-targets -- -D warnings\ncargo nextest run -p \u003Cpackage> --lib        # --bins for the runtime\n```\n\nIntegration tests run per test target. Build what the harness launches first, then filter by target and test name:\n\n```text\n.\u002Fscripts\u002Fbuild-test-server.sh                                          # once per core pin\ncargo build -p iggy-connectors -p iggy_connector_postgres_sink\ncargo nextest run -p iggy_connector_postgres_sink --test postgres postgres_sink::   # one module\ncargo nextest run -p iggy_connector_postgres_sink --test postgres                   # the whole suite\ncargo nextest run --workspace                                                        # all tests, as CI\n```\n\nA test that apache\u002Figgy named `connectors::\u003Csuite>::\u003Crest>` is `\u003Crest>` in the test target `\u003Csuite>` of the package that owns it.\n\nIntegration tests assume Docker is available locally and pull images from a public registry on first run.\n\n## Common pitfalls\n\n1. **Skipping integration tests for a real-infra plugin.** Unit tests don't catch FFI\u002Flifecycle\u002Fencoding regressions.\n2. **Forgetting the four canonical source state tests.** This is the most common review comment.\n3. **Mocking the client library** instead of using `testcontainers` - test exercises the mock.\n4. **`#[tokio::test]` in `src\u002Flib.rs`** - pulls tokio test macros into prod build. Use `Runtime::new()` instead. (`#[tokio::test]` is fine in `tests\u002F` directories, which compile separately.)\n5. **`unwrap()` in test assertions** - prefer `assert_eq!` \u002F `expect(\"descriptive\")` so failures tell you which step blew up.\n6. **Tests depending on system time** - inject the clock or use `tokio::time::pause()`.\n7. **Hidden coupling via shared globals** (static `AtomicU64`, env vars) - tests must be independent and parallelizable.\n8. **Asserting on `Display` of an error** - use `matches!(err, Error::Variant(_))`. `assert_eq!(err.to_string(), ...)` breaks on message tweaks.\n9. **Sleeping a fixed duration** instead of polling - causes flakes when CI is slow.\n\n## Examples worth copying\n\n| Concern                             | Where                                                                                                          |\n| ----------------------------------- | -------------------------------------------------------------------------------------------------------------- |\n| Source state round-trip             | `sources\u002Frandom_source\u002Fsrc\u002Flib.rs::tests`                                                                      |\n| Config + query-building unit tests  | `sinks\u002Fpostgres_sink\u002Fsrc\u002Flib.rs::tests`                                                                        |\n| Real-infra sink integration tests   | `sinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002Fpostgres_sink.rs`                                                          |\n| Real-infra source integration tests | `sources\u002Fpostgres_source\u002Ftests\u002Fpostgres\u002Fpostgres_source.rs`                                                    |\n| Restart + state survival            | `sinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002Frestart.rs`, `postgres_source.rs::state_persists_across_connector_restart` |\n| Wiremock-driven HTTP sink test      | `sinks\u002Fhttp_sink\u002Ftests\u002Fhttp\u002Fhttp_sink.rs`                                                                      |\n| Testcontainer wrapper               | `testing\u002Fsrc\u002Fpostgres.rs`                                                                                      |\n| Fixture impl `TestFixture`          | `sinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002Ffixtures\u002Fsink.rs`                                                          |\n| Runtime-only error-isolation        | `runtime\u002Ftests\u002Fruntime\u002Ferror_isolation.rs`                                                                     |\n| Transform tests                     | `sdk\u002Fsrc\u002Ftransforms\u002Fadd_fields.rs::tests`, `filter_fields.rs::tests`                                           |\n\n---\n\nDiscussion \u002F help: see [AGENTS.md](..\u002F..\u002F..\u002FAGENTS.md#discussion-and-support).\n","# Testing Apache Iggy Connectors\n\n> **Universal connector rules** live in\n> [connectors-overview](..\u002Fconnectors-overview\u002FSKILL.md). Repo-wide testing rules (`#[iggy_harness]`, BDD naming, harness layout) live in [AGENTS.md](..\u002F..\u002F..\u002FAGENTS.md#testing). This skill covers connector-specific test conventions.\n\n## Contents\n\n- [STOP and ask the user before](#stop-and-ask-the-user-before)\n- [Unit tests](#unit-tests)\n- [Integration tests (real infra via Docker)](#integration-tests-real-infra-via-docker)\n- [SDK + runtime tests](#sdk--runtime-tests)\n- [CI \u002F verification flow](#ci--verification-flow)\n- [Common pitfalls](#common-pitfalls)\n- [Examples worth copying](#examples-worth-copying)\n\n## STOP and ask the user before\n\n- Mocking the database or backend in an integration test - we hit real infra via `testcontainers-modules` (mocks miss migration bugs).\n- Adding a unit test that requires Docker - that belongs in the package's test target `\u003Cplugin>\u002Ftests\u002F\u003Cbackend>\u002F`, not in `\u003Cplugin>\u002Fsrc\u002Flib.rs`.\n- Skipping the four canonical source state tests - they're mandatory for every source plugin.\n- Naming a test `test_foo` \u002F `does_bar` - we use BDD `given_X_when_Y_should_Z`.\n\nThere are **two distinct test layers**. Use both - they catch different bugs.\n\n| Layer                 | Location                                                 | What it covers                                                                                 | When required                                        |\n| --------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------- |\n| **Unit tests**        | `#[cfg(test)] mod tests` at EOF of `\u003Cplugin>\u002Fsrc\u002Flib.rs` | Config parsing, defaults, fallbacks, payload conversion, query\u002Fdocument building, state ser\u002Fde | Every plugin                                         |\n| **Integration tests** | `\u003Cplugin>\u002Ftests\u002F\u003Csuite>\u002F` (uses real backend via Docker) | End-to-end: runtime + plugin + real Postgres\u002FES\u002FIceberg\u002FMongo\u002Fetc. + Iggy server               | Every plugin that integrates with an external system |\n\n## Unit tests\n\n### Naming - BDD `given_when_should`\n\nMatch the convention used in the codebase (`sources\u002Frandom_source\u002Fsrc\u002Flib.rs::tests`, `sinks\u002Fpostgres_sink\u002Fsrc\u002Flib.rs::tests`):\n\n```rust\n#[test]\nfn given_persisted_state_should_restore_messages_produced() { ... }\n\n#[test]\nfn given_no_state_should_start_fresh() { ... }\n\n#[test]\nfn given_invalid_duration_should_fall_back_to_default() { ... }\n\n#[test]\nfn given_payload_json_should_serialize_correctly() { ... }\n```\n\nYou may **omit one part** when the test is small (`given_X_should_Y` instead of full `given_X_when_Y_should_Z`), but **stay consistent within a file**. Imperative `test_foo` \u002F `does_bar` names are not the convention here.\n\nA test whose subject is a **type** rather than a scenario has no \"given\" to name, and drops the prefix: it reads `\u003Csubject>_should_\u003Cproperty>`. The canonical state round trip below is `state_should_be_serializable_and_deserializable` in all three shipped sources (`random_source`, `postgres_source`, `http_source`). Leave those as they are rather than bending them into the scenario form.\n\n### Prove a test can fail, before trusting it\n\nA passing test says nothing until you have watched it fail. Break the behaviour it names, run the\nsuite, and put the code back:\n\n```bash\n# commit first: this reverts with `git checkout --`, which discards\n# every uncommitted change in the file, not only the mutation\ngit status --porcelain -- \u003Cfile>            # must be empty\n\u003Cedit the guard out>\ncargo nextest run -p \u003Ccrate>                # expect a failure naming that test\ngit checkout -- \u003Cfile>\n```\n\nTwo failures this catches, both seen in review of `http_source`:\n\n- **A fixture that makes the interesting case unreachable.** A guard test for endpoint resurrection\n  passed `&[]` as the static config, so there was nothing to resurrect and the assertion held\n  whatever `restore` did.\n- **An assertion aimed at something self-healing.** A test for a teardown guard asserted on gauges,\n  which `Metrics::encode` rebuilds from the live instances on every scrape, so it passed with the\n  guard deleted. Delete such a test rather than keep it; a test that cannot fail is worse than none,\n  because it reads as coverage.\n\nWatch for an arm hidden behind a catch-all: `StatusClass::from` ends in `_ => ServerError`, so the\nredirect arm could be removed with every existing assertion still green.\n\n### `test_config()` helper\n\nEvery plugin's tests start with a small helper returning a tuned-down version of the production config. New tests extend it. don't construct from scratch each time.\n\n```rust\nfn test_config() -> RandomSourceConfig {\n    RandomSourceConfig {\n        interval: Some(\"100ms\".to_string()),\n        max_count: Some(100),\n        messages_range: Some((5, 10)),\n        payload_size: Some(50),\n    }\n}\n```\n\n### Async testing pattern\n\nThe trait methods are `async`. For unit tests, build a runtime locally - don't add `#[tokio::test]` in `src\u002Flib.rs` (it pulls test macros into prod build):\n\n```rust\n#[test]\nfn given_X_should_Y() {\n    let runtime = tokio::runtime::Runtime::new().unwrap();\n    runtime.block_on(async {\n        \u002F\u002F await calls here\n    });\n}\n```\n\n### Mandatory: four canonical source state tests\n\nEvery source must have these. Copy from `sources\u002Frandom_source\u002Fsrc\u002Flib.rs::tests`:\n\n```rust\n#[test]\nfn given_persisted_state_should_restore_\u003Cfield>() {\n    let state = State { \u002F* fields *\u002F };\n    let serialized = rmp_serde::to_vec(&state).expect(\"Failed to serialize state\");\n    let connector_state = ConnectorState(serialized);\n\n    let source = MySource::new(1, test_config(), Some(connector_state));\n\n    let runtime = tokio::runtime::Runtime::new().unwrap();\n    runtime.block_on(async {\n        let restored = source.state.lock().await;\n        assert_eq!(restored.\u003Cfield>, \u002F* expected *\u002F);\n    });\n}\n\n#[test]\nfn given_no_state_should_start_fresh() {\n    let source = MySource::new(1, test_config(), None);\n    \u002F* assert default state *\u002F\n}\n\n#[test]\nfn given_invalid_state_should_start_fresh() {\n    let invalid = ConnectorState(b\"not valid msgpack\".to_vec());\n    let source = MySource::new(1, test_config(), Some(invalid));\n    \u002F* assert default state *\u002F\n}\n\n#[test]\nfn state_should_be_serializable_and_deserializable() {\n    let original = State { \u002F* fields *\u002F };\n    let bytes = rmp_serde::to_vec(&original).unwrap();\n    let restored: State = rmp_serde::from_slice(&bytes).unwrap();\n    assert_eq!(original.\u003Cfield>, restored.\u003Cfield>);\n}\n```\n\nState is the only thing that survives a plugin restart. Silent corruption here means lost data on the next deploy.\n\n**The third test has two correct shapes, and which one applies is a design decision rather than a style choice.**\n\nStarting fresh is right when the state is a cursor. The worst case is re-reading from the beginning, which the at-least-once contract already permits, so discarding an undecodable cursor costs duplicates and nothing else.\n\nIt is wrong when the state carries something whose *absence* is a downgrade rather than a repeat. `http_source` keeps its revocation tombstones in state, so starting fresh after a decode failure would serve every revoked endpoint again, with its secret. Its `restore` returns `Err` instead and the connector refuses to open. A source in that position asserts the refusal:\n\n```rust\n#[test]\nfn given_invalid_state_should_refuse_to_open() {\n    let invalid = ConnectorState(b\"not valid msgpack\".to_vec());\n\n    let restored = MyState::restore(&config_entries(), Some(invalid), 1);\n\n    assert!(\n        restored.is_err(),\n        \"discarding this state silently would re-serve what it was revoking\"\n    );\n}\n```\n\nName the test for whichever it is and say why in a comment. What is never right is starting fresh silently when the state that was discarded was load-bearing.\n\n### Sink unit tests\n\nCover pure per-message logic:\n\n- Config defaults + optional fields + invalid values → fallback.\n- Payload conversion for each `Payload` variant the sink claims to handle.\n- Header encoding (especially base64 for binary headers).\n- Query\u002Fdocument building (e.g., `postgres_sink::build_batch_insert_query`).\n- Transient vs permanent error classification (e.g., `postgres_sink::is_transient_error`).\n\n### Transform tests\n\nFour branches must be covered (see `connector-transform`):\n\n1. Happy path: matching input → expected output.\n2. Filter path: input that should be dropped returns `Ok(None)`.\n3. Pass-through path: non-JSON payload (or unmatched condition) returns `Ok(Some(unchanged))`.\n4. Invalid config: `new()` returns `Err(Error::InvalidConfigValue(_))`.\n\n### What NOT to mock\n\n- The underlying client lib (sqlx, reqwest, mongodb). Tests would exercise the mock, not the code.\n- The Iggy server.\n- The runtime.\n\nIf you need a fake backend, use `wiremock` (a real local HTTP server) - see `sinks\u002Fhttp_sink\u002Ftests\u002Fhttp\u002F`.\n\n## Integration tests (real infra via Docker)\n\nEach plugin that integrates with an external service (Postgres, Elasticsearch, Iceberg, MongoDB, InfluxDB, Quickwit, HTTP\u002Fwiremock) owns its integration tests: one test target per backend suite in `tests\u002F\u003Csuite>\u002F` of its own package, with a paired fixture + test file there. A backend with both a sink and a source has a target of the same name in both packages. Fixtures that more than one package needs live in `testing\u002F` (crate `iggy_connector_testing`).\n\n### Layout\n\n```text\nsinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002F      Test target `postgres` of iggy_connector_postgres_sink\n├── main.rs                   mod declarations, install_log_capture!(), shared constants (TEST_MESSAGE_COUNT, POLL_ATTEMPTS, ...)\n├── fixtures\u002F\n│   ├── sink.rs               PostgresSinkFixture, PostgresSinkByteaFixture, PostgresSinkJsonFixture\n│   └── mod.rs                re-exports, plus PostgresOps from iggy_connector_testing\n├── postgres_sink.rs          The actual #[iggy_harness] tests\n├── restart.rs                Sink restart tests through the runtime HTTP API\n└── sink.toml                 Runtime config used by the tests\n\nsources\u002Fpostgres_source\u002Ftests\u002Fpostgres\u002F  Test target `postgres` of iggy_connector_postgres_source\n├── main.rs\n├── fixtures\u002F\n│   ├── source.rs             PostgresSourceJsonFixture, PostgresSourceJsonbFixture, ...\n│   ├── cdc.rs                PostgresSourceCdcFixture, PostgresSourceCdcSlowPollFixture\n│   └── mod.rs                re-exports, plus PostgresOps and PostgresSourceOps from iggy_connector_testing\n├── postgres_source.rs  postgres_source_cdc.rs\n├── source.toml  source_cdc_restart.toml\n└── cdc_restart_connectors\u002F   Connector directory of source_cdc_restart.toml\n\ntesting\u002Fsrc\u002F                  iggy_connector_testing\n├── lib.rs                    TestMessage, create_test_messages, TEST_CONTAINER_PREFIX, unique_container_name\n├── postgres.rs               PostgresContainer (testcontainers wrapper), PostgresOps, PostgresSourceOps, env-var consts\n├── random_source_liveness.rs assert_produces_messages\n└── elasticsearch.rs  influxdb.rs  influxdb_v3.rs  floci.rs\n\nruntime\u002Ftests\u002F\n├── runtime\u002F                  Runtime-only tests (error isolation, missing plugin, ...)\n├── api\u002F                      HTTP control plane tests\n├── http_config_provider\u002F     HTTP config provider end-to-end, WireMock fixture in fixtures.rs\n└── config_env_listing.rs     Env-var listing of the runtime binary\n```\n\nA container that only one package uses lives in that target's `fixtures\u002Fcontainer.rs` (for example `sinks\u002Fhttp_sink\u002Ftests\u002Fhttp\u002Ffixtures\u002Fcontainer.rs`).\n\n### Container naming + cleanup\n\nEvery test container MUST be named with the `iggy-test-` prefix so a single\nsweep reaps them: `docker ps -aqf 'name=^iggy-test-' | xargs -r docker rm -f`.\nReuse fixtures keep their container running, and a crashed run can orphan any\nfixture's container, so run the sweep after a test session. New fixtures get\nthis for free by naming through `iggy_connector_testing::unique_container_name(\"\u003Csvc>\")`, which\nappends a uuid for parallel-safe ephemeral containers. Reuse fixtures use a fixed\n`iggy-test-\u003Csvc>` literal instead, because the stable name is what lets later\nnextest processes attach to the same container via `ReuseDirective::Always`. Do\nnot hand-roll a different prefix - the sweep only finds `iggy-test-*`.\n\nAs of now only `elasticsearch` and `doris` share a container. Both have a slow\nboot (JVM \u002F Doris FE+BE, tens of seconds), so reusing one across the whole\nregression beats spinning a fresh one per test. Every other fixture boots a\nfresh, ephemeral container per test - cheap enough that the isolation is worth\nmore than the reuse.\n\n### The `#[iggy_harness]` proc macro\n\nEach integration test is annotated with this macro from the `integration` crate of apache\u002Figgy at the core pin. It launches the prebuilt `target\u002Fdebug\u002Figgy-server` (from `.\u002Fscripts\u002Fbuild-test-server.sh`) and optionally `target\u002Fdebug\u002Figgy-connectors` for the duration of the test, runs the seeds, then injects a `&TestHarness` and your fixture. It never builds them: run `cargo build` first, or a stale binary runs.\n\n```rust\nuse integration::harness::seeds;\nuse integration::iggy_harness;\n\n#[iggy_harness(\n    server(connectors_runtime(config_path = \"tests\u002Fpostgres\u002Fsink.toml\")),\n    seed = seeds::connector_stream\n)]\nasync fn json_messages_sink_stores_as_bytea(\n    harness: &TestHarness,\n    fixture: PostgresSinkFixture,\n) {\n    let client = harness.root_client().await.unwrap();\n    let pool = fixture.create_pool().await.expect(\"Failed to create pool\");\n    fixture.wait_for_table(&pool, \"iggy_messages\").await;\n    \u002F\u002F ... send messages, assert on rows\n}\n```\n\nKey pieces:\n\n- `server(connectors_runtime(config_path = ...))` boots the connectors runtime against the given TOML.\n  The path is relative to the package directory: cargo and nextest run each test binary there, and the runtime inherits that working directory.\n  Most of these TOMLs set `config_dir = \".\"`, so the runtime loads the plugin's own `config.toml` from the package root (it skips `Cargo.toml`).\n  The fixture then sets the plugin path to the bare file name, for example `ENV_SINK_PATH` = `libiggy_connector_postgres_sink`, and the runtime finds it next to its own binary in `target\u002Fdebug\u002F`.\n  A test that needs other connector files keeps them in a directory under `tests\u002F\u003Csuite>\u002F`, for example `tests\u002Fpostgres\u002Fcdc_restart_connectors\u002F` in `sources\u002Fpostgres_source\u002F`.\n- `seed = seeds::connector_stream` runs the named seed to create the test stream\u002Ftopic.\n- `fixture: PostgresSinkFixture` - the test harness calls `PostgresSinkFixture::setup()` (which spins up the testcontainer) and injects the result.\n- `harness: &TestHarness` (defined in `core\u002Fintegration\u002Fsrc\u002Fharness\u002Forchestrator\u002Fharness.rs` of apache\u002Figgy) exposes `.root_client().await`, `.connectors_runtime().expect(\"...\").http_url()`, etc. - `connectors_runtime()` returns `Option`, so `.expect()` first.\n\n### Fixture pattern (`TestFixture` trait)\n\nEach fixture implements `integration::harness::TestFixture`. Pattern:\n\n```rust\n\u002F\u002F testing\u002Fsrc\u002F\u003Cbackend>.rs when several packages use it, else tests\u002F\u003Csuite>\u002Ffixtures\u002Fcontainer.rs\n\nuse testcontainers_modules::{\n    \u003Cbackend_module>,\n    testcontainers::{ContainerAsync, runners::AsyncRunner},\n};\n\npub struct MyContainer {\n    container: ContainerAsync\u003C\u003Cbackend_module>::Image>,\n    pub connection_string: String,\n}\n\nimpl MyContainer {\n    pub async fn start() -> Result\u003CSelf, TestBinaryError> {\n        let container = \u003Cbackend_module>::Image::default().start().await?;\n        let port = container.get_host_port_ipv4(DEFAULT_PORT).await?;\n        Ok(Self {\n            container,\n            connection_string: format!(\"...:\u002F\u002Flocalhost:{port}\"),\n        })\n    }\n}\n```\n\nThe fixture itself wraps the container and implements `TestFixture::setup()` to spin it up and inject env vars that the runtime picks up.\n\n### Env-var injection via `ConfigEnv`\n\nThe runtime's config structs derive `ConfigEnv` (`configs_derive::ConfigEnv`, applied in `runtime\u002Fsrc\u002Fconfigs\u002Fconnectors.rs` to `SinkConfig`, `SourceConfig`, `StreamConsumerConfig`, `StreamProducerConfig`). Fields are addressable by env var with a path-built prefix. Three concrete forms observed in `testing\u002Fsrc\u002Fpostgres.rs`:\n\n```rust\n\u002F\u002F Plugin-config fields (your sink\u002Fsource's own config struct):\n\u002F\u002F   IGGY_CONNECTORS_\u003CTYPE>_\u003CKEY>_PLUGIN_CONFIG_\u003CFIELD>\npub const ENV_SINK_CONNECTION_STRING: &str =\n    \"IGGY_CONNECTORS_SINK_POSTGRES_PLUGIN_CONFIG_CONNECTION_STRING\";\n\n\u002F\u002F Indexed nested fields (per-stream entries are a Vec):\n\u002F\u002F   IGGY_CONNECTORS_\u003CTYPE>_\u003CKEY>_STREAMS_\u003CINDEX>_\u003CFIELD>\npub const ENV_SINK_STREAMS_0_STREAM: &str =\n    \"IGGY_CONNECTORS_SINK_POSTGRES_STREAMS_0_STREAM\";\n\n\u002F\u002F Top-level scalar fields on SinkConfig\u002FSourceConfig itself:\n\u002F\u002F   IGGY_CONNECTORS_\u003CTYPE>_\u003CKEY>_\u003CFIELD>\npub const ENV_SINK_PATH: &str =\n    \"IGGY_CONNECTORS_SINK_POSTGRES_PATH\";\n```\n\n`\u003CTYPE>` is `SINK` or `SOURCE`. `\u003CKEY>` is the connector key (TOML key field, uppercased). `PLUGIN_CONFIG` is the literal segment used when reaching into your plugin's nested config. Fields marked `#[config_env(skip)]` (e.g., `transforms`, `plugin_config` as a whole) are NOT env-addressable. primitive leaves marked `#[config_env(leaf)]` are.\n\nThe fixture sets these in `setup()` before the runtime reads its config. This is how a dynamic container port reaches a static TOML.\n\n### Test naming for integration tests\n\nIntegration tests use a **descriptive declarative** style, not the unit-test `given_should` form. Match the codebase:\n\n```rust\nasync fn json_messages_sink_stores_as_bytea(...) { ... }\nasync fn binary_messages_sink_stores_as_bytea(...) { ... }\nasync fn json_messages_sink_stores_as_jsonb(...) { ... }\nasync fn delete_after_read_source_removes_rows_after_producing(...) { ... }\nasync fn processed_column_source_marks_rows_after_producing(...) { ... }\nasync fn state_persists_across_connector_restart(...) { ... }\nasync fn restart_sink_connector_continues_processing(...) { ... }\n```\n\nPattern: `\u003Csubject>_\u003Caction>_\u003Cobservation>`. Reads like a sentence describing what the test proves.\n\n### Polling vs sleeping\n\nIntegration tests poll until an expected condition - never `sleep(big_duration)`. Constants `POLL_ATTEMPTS` and `POLL_INTERVAL_MS` defined in each test target's `main.rs`. Fixture helpers like `PostgresSinkFixture::fetch_rows_as` and `PostgresSinkFixture::wait_for_table` encapsulate the pattern.\n\n### When to add an integration test\n\n- New sink\u002Fsource plugin → at minimum one happy-path test per supported `Schema` and per supported plugin mode. Concrete coverage in the `postgres` targets of `sinks\u002Fpostgres_sink\u002F` and `sources\u002Fpostgres_source\u002F`:\n  3 sink tests (`json_messages_sink_stores_as_bytea`, `binary_messages_sink_stores_as_bytea`, `json_messages_sink_stores_as_jsonb`) backed by 3 sink fixtures, plus 5 source fixtures (`Json`, `Jsonb`, `Bytea`, `Delete`, `Mark`), `state_persists_across_connector_restart` for state survival, and a dedicated `restart.rs` for sink restarts.\n- Bug fix in a plugin → regression test reproducing the bug.\n- Behavior that crosses the FFI boundary (state restart, transform chain, schema decode) → integration test, not unit test.\n\n### When NOT to add an integration test\n\n- Pure logic (query builder, payload converter) - that's a unit test.\n- Config validation - unit test.\n- Code paths already covered by an equivalent test for another backend, when the new backend has identical behavior.\n\n## SDK + runtime tests\n\n- `sdk\u002Ftests\u002F` - cross-module SDK concerns. In tree: `protobuf_integration.rs`, `flatbuffer_integration.rs` (round-trip schema decoders\u002Fencoders), `plugin_logging.rs`.\n- Runtime tests live under `runtime\u002Ftests\u002Fruntime\u002F`, `runtime\u002Ftests\u002Fapi\u002F` and `runtime\u002Ftests\u002Fhttp_config_provider\u002F`. They exercise the runtime alone (no plugin-specific backend, only `random_source` and `stdout_sink`) - error isolation, missing plugin, invalid config, HTTP API contract.\n\n## CI \u002F verification flow\n\nBefore pushing:\n\n```text\ncargo fmt --all\ncargo sort --no-format --grouped --workspace\ncargo clippy -p \u003Cpackage> --all-targets -- -D warnings\ncargo nextest run -p \u003Cpackage> --lib        # --bins for the runtime\n```\n\nIntegration tests run per test target. Build what the harness launches first, then filter by target and test name:\n\n```text\n.\u002Fscripts\u002Fbuild-test-server.sh                                          # once per core pin\ncargo build -p iggy-connectors -p iggy_connector_postgres_sink\ncargo nextest run -p iggy_connector_postgres_sink --test postgres postgres_sink::   # one module\ncargo nextest run -p iggy_connector_postgres_sink --test postgres                   # the whole suite\ncargo nextest run --workspace                                                        # all tests, as CI\n```\n\nA test that apache\u002Figgy named `connectors::\u003Csuite>::\u003Crest>` is `\u003Crest>` in the test target `\u003Csuite>` of the package that owns it.\n\nIntegration tests assume Docker is available locally and pull images from a public registry on first run.\n\n## Common pitfalls\n\n1. **Skipping integration tests for a real-infra plugin.** Unit tests don't catch FFI\u002Flifecycle\u002Fencoding regressions.\n2. **Forgetting the four canonical source state tests.** This is the most common review comment.\n3. **Mocking the client library** instead of using `testcontainers` - test exercises the mock.\n4. **`#[tokio::test]` in `src\u002Flib.rs`** - pulls tokio test macros into prod build. Use `Runtime::new()` instead. (`#[tokio::test]` is fine in `tests\u002F` directories, which compile separately.)\n5. **`unwrap()` in test assertions** - prefer `assert_eq!` \u002F `expect(\"descriptive\")` so failures tell you which step blew up.\n6. **Tests depending on system time** - inject the clock or use `tokio::time::pause()`.\n7. **Hidden coupling via shared globals** (static `AtomicU64`, env vars) - tests must be independent and parallelizable.\n8. **Asserting on `Display` of an error** - use `matches!(err, Error::Variant(_))`. `assert_eq!(err.to_string(), ...)` breaks on message tweaks.\n9. **Sleeping a fixed duration** instead of polling - causes flakes when CI is slow.\n\n## Examples worth copying\n\n| Concern                             | Where                                                                                                          |\n| ----------------------------------- | -------------------------------------------------------------------------------------------------------------- |\n| Source state round-trip             | `sources\u002Frandom_source\u002Fsrc\u002Flib.rs::tests`                                                                      |\n| Config + query-building unit tests  | `sinks\u002Fpostgres_sink\u002Fsrc\u002Flib.rs::tests`                                                                        |\n| Real-infra sink integration tests   | `sinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002Fpostgres_sink.rs`                                                          |\n| Real-infra source integration tests | `sources\u002Fpostgres_source\u002Ftests\u002Fpostgres\u002Fpostgres_source.rs`                                                    |\n| Restart + state survival            | `sinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002Frestart.rs`, `postgres_source.rs::state_persists_across_connector_restart` |\n| Wiremock-driven HTTP sink test      | `sinks\u002Fhttp_sink\u002Ftests\u002Fhttp\u002Fhttp_sink.rs`                                                                      |\n| Testcontainer wrapper               | `testing\u002Fsrc\u002Fpostgres.rs`                                                                                      |\n| Fixture impl `TestFixture`          | `sinks\u002Fpostgres_sink\u002Ftests\u002Fpostgres\u002Ffixtures\u002Fsink.rs`                                                          |\n| Runtime-only error-isolation        | `runtime\u002Ftests\u002Fruntime\u002Ferror_isolation.rs`                                                                     |\n| Transform tests                     | `sdk\u002Fsrc\u002Ftransforms\u002Fadd_fields.rs::tests`, `filter_fields.rs::tests`                                           |\n\n---\n\nDiscussion \u002F help: see [AGENTS.md](..\u002F..\u002F..\u002FAGENTS.md#discussion-and-support).\n",{"name":5,"description":7},"master","8282728d93c560a8714a985ace3e91bea36214b0",".claude\u002Fskills\u002Fconnector-testing",9,"https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors","https:\u002F\u002Figgy.apache.org\u002F","https:\u002F\u002Fgithub.com\u002Fapache","https:\u002F\u002Fwww.apache.org\u002F","2026-11-14 16:40:07",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add apache\u002Figgy-connectors --skill connector-testing",{"tool":39,"command":40},"bunx","bunx skills add apache\u002Figgy-connectors --skill connector-testing",{"tool":42,"command":43},"pnpm","pnpm dlx skills add apache\u002Figgy-connectors --skill connector-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnector-testing\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M74CNZYB8S4XAQ9G19VTP7S0","team-review","Four expert review of a PR, branch, or ref range.\nUse only when the user explicitly requests team-review.","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fteam-review\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M74CMY09QP0D2TK15BN1P1XK","connector-review","Adversarial review of a connectors PR, branch, or ref range, with clean-room validation of every finding. Experts\nwork alone and use the focused connector skills as their source of subsystem rules.\nUse only when the user explicitly requests connector-review.","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnector-review\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M74CNWVGHJ6GFK6CMCX6H0YE","connectors-overview","Entry point and index for the Apache Iggy Connectors repository. Load this first when working anywhere in it - runtime, SDK, sinks, sources, transforms, or their tests. Routes to the focused per-area skills.","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnectors-overview\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M74CNKY8NRVGY59SK1V2ZSY5","connector-transform","Add a new transform under `sdk\u002Fsrc\u002Ftransforms\u002F`. Transforms mutate, filter, or convert messages between source\u002Fencode and decode\u002Fsink. Use when adding field-level transforms (add\u002Fdelete\u002Fupdate\u002Ffilter), format conversions, envelope unwrapping, or similar config-driven message manipulations for Apache Iggy connectors. Use for transform authoring. NOT for runtime internals or sink\u002Fsource loops.","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnector-transform\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M74CNBQE9HSA111QAN094YC4","connector-source","Author a new Apache Iggy connector source plugin under sources\u002F. Sources poll an external system (DB, API, queue) and produce messages into Apache Iggy streams. Load when creating, modifying, or reviewing a source crate. Use for source plugin authoring. NOT for runtime internals (see connector-runtime).","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnector-source\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M74CN8KEF5GH3JFSTHH4EJ7T","connector-sink","Author a new Apache Iggy connector sink plugin under sinks\u002F. Sinks consume messages from Apache Iggy streams and push them to an external system (DB, search engine, HTTP endpoint, object store). Load when creating, modifying, or reviewing a sink crate. Use for sink plugin authoring. NOT for runtime internals (see connector-runtime).","https:\u002F\u002Fgithub.com\u002Fapache\u002Figgy-connectors\u002Fblob\u002Fmaster\u002F.claude\u002Fskills\u002Fconnector-sink\u002FSKILL.md",[],[]]