Metadata-Version: 2.4
Name: grpc-testkit
Version: 0.3.0
Summary: A requests-like, test-first client toolkit for synchronous and asynchronous gRPC services
Project-URL: Homepage, https://gitlab.com/ItHummanoid/grpc-testkit
Project-URL: Documentation, https://gitlab.com/ItHummanoid/grpc-testkit/-/tree/main/docs
Project-URL: Repository, https://gitlab.com/ItHummanoid/grpc-testkit
Project-URL: Issues, https://gitlab.com/ItHummanoid/grpc-testkit/-/issues
Project-URL: Changelog, https://gitlab.com/ItHummanoid/grpc-testkit/-/blob/main/CHANGELOG.md
Author: grpc-testkit contributors
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2026 grpc-testkit contributors
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: asyncio,grpc,protobuf,pytest,qa,testing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Testing
Requires-Python: <3.15,>=3.10
Requires-Dist: grpcio<2,>=1.66
Requires-Dist: protobuf<7,>=5.27
Provides-Extra: allure
Requires-Dist: allure-pytest<3,>=2.13; extra == 'allure'
Provides-Extra: config
Requires-Dist: pyyaml<7,>=6.0.2; extra == 'config'
Requires-Dist: tomli<3,>=2.0; (python_version < '3.11') and extra == 'config'
Provides-Extra: dev
Requires-Dist: allure-pytest<3,>=2.13; extra == 'dev'
Requires-Dist: bandit[toml]<2,>=1.9; extra == 'dev'
Requires-Dist: build<2,>=1.2; extra == 'dev'
Requires-Dist: cryptography<51,>=50; (sys_platform != 'darwin' or platform_machine != 'x86_64') and extra == 'dev'
Requires-Dist: detect-secrets<2,>=1.5; extra == 'dev'
Requires-Dist: googleapis-common-protos<2,>=1.63; extra == 'dev'
Requires-Dist: grpcio-health-checking<2,>=1.66; extra == 'dev'
Requires-Dist: grpcio-reflection<2,>=1.66; extra == 'dev'
Requires-Dist: grpcio-status<2,>=1.66; extra == 'dev'
Requires-Dist: grpcio-tools<2,>=1.66; extra == 'dev'
Requires-Dist: mypy<2,>=1.11; extra == 'dev'
Requires-Dist: pip-audit<3,>=2.10; extra == 'dev'
Requires-Dist: pytest-asyncio<2,>=0.24; extra == 'dev'
Requires-Dist: pytest-cov<7,>=5; extra == 'dev'
Requires-Dist: pytest<10,>=8; extra == 'dev'
Requires-Dist: pyyaml<7,>=6.0.2; extra == 'dev'
Requires-Dist: ruff<1,>=0.6; extra == 'dev'
Requires-Dist: tomli<3,>=2.0; (python_version < '3.11') and extra == 'dev'
Requires-Dist: twine<7,>=5; extra == 'dev'
Requires-Dist: types-grpcio-health-checking<2,>=1; extra == 'dev'
Requires-Dist: types-grpcio-reflection<2,>=1; extra == 'dev'
Requires-Dist: types-grpcio-status<2,>=1; extra == 'dev'
Requires-Dist: types-grpcio<2,>=1; extra == 'dev'
Requires-Dist: types-protobuf<8,>=6; extra == 'dev'
Requires-Dist: types-pyyaml<7,>=6; extra == 'dev'
Provides-Extra: full
Requires-Dist: allure-pytest<3,>=2.13; extra == 'full'
Requires-Dist: googleapis-common-protos<2,>=1.63; extra == 'full'
Requires-Dist: grpcio-health-checking<2,>=1.66; extra == 'full'
Requires-Dist: grpcio-reflection<2,>=1.66; extra == 'full'
Requires-Dist: grpcio-status<2,>=1.66; extra == 'full'
Requires-Dist: grpcio-tools<2,>=1.66; extra == 'full'
Requires-Dist: pytest-asyncio<2,>=0.24; extra == 'full'
Requires-Dist: pytest<10,>=8; extra == 'full'
Requires-Dist: pyyaml<7,>=6.0.2; extra == 'full'
Requires-Dist: tomli<3,>=2.0; (python_version < '3.11') and extra == 'full'
Provides-Extra: health
Requires-Dist: grpcio-health-checking<2,>=1.66; extra == 'health'
Provides-Extra: otel
Requires-Dist: grpcio-observability<2,>=1.66; extra == 'otel'
Provides-Extra: proto
Requires-Dist: grpcio-tools<2,>=1.66; extra == 'proto'
Provides-Extra: pytest
Requires-Dist: pytest-asyncio<2,>=0.24; extra == 'pytest'
Requires-Dist: pytest<10,>=8; extra == 'pytest'
Provides-Extra: reflection
Requires-Dist: grpcio-reflection<2,>=1.66; extra == 'reflection'
Provides-Extra: security
Requires-Dist: bandit[toml]<2,>=1.9; extra == 'security'
Requires-Dist: detect-secrets<2,>=1.5; extra == 'security'
Requires-Dist: pip-audit<3,>=2.10; extra == 'security'
Provides-Extra: status
Requires-Dist: googleapis-common-protos<2,>=1.63; extra == 'status'
Requires-Dist: grpcio-status<2,>=1.66; extra == 'status'
Description-Content-Type: text/markdown

# grpc-testkit

`grpc-testkit` is a test-first Python client for gRPC with a small, requests-like API.
It supports generated stubs and runtime descriptors, synchronous and `grpc.aio` clients,
all four RPC cardinalities, TLS/mTLS, reflection, proto acquisition/generation, pytest
fixtures, streaming, explicit retries, and rich failure responses.

The package targets Python 3.10–3.14.

## Documentation

Complete step-by-step tutorials are included in this repository:

- [English tutorial](docs/tutorial.en.md) — `docs/tutorial.en.md`;
- [Русский туториал](docs/tutorial.ru.md) — `docs/tutorial.ru.md`.

They cover installation, generated stubs, reflection, TLS/mTLS, authentication,
synchronous and asynchronous calls, every streaming type, retries, dynamic proto
acquisition, pytest, Service Object Model, Docker, Kubernetes, CI, troubleshooting,
and security practices.

## Installation

```bash
pip install grpc-testkit
```

Install only the optional capabilities your project needs:

```bash
pip install "grpc-testkit[proto,reflection,health,pytest,allure,status]"
```

`grpc-testkit[full]` enables all runtime integrations. OpenTelemetry instrumentation is
kept separate as `grpc-testkit[otel]` because applications often configure telemetry at
process startup.

## First call

Dynamic calls need a descriptor source. Reflection is the most convenient option when
the server exposes it:

```python
from grpc_testkit import Session

with Session.from_reflection("localhost:50051") as grpc:
    response = grpc.call("acme.users.v1.Users/GetUser", {"id": "42"})

assert response.ok
assert response.message.id == "42"
assert response.code.name == "OK"
```

The same API can bootstrap directly from a descriptor set or a proto tree:

```python
with Session.from_descriptor("localhost:50051", "schema.pb") as grpc:
    ...

with Session.from_proto("localhost:50051", "protos", cache_dir=".grpc/proto-cache") as grpc:
    ...
```

Use `connect(...)` / `aconnect(...)` when a compact requests-style factory reads better.
All factories have synchronous and asynchronous variants. Create and use `aconnect()`
inside a running event loop (normally inside an `async def` test).

## Connection profiles and project bootstrap

Profiles keep environment-specific channel settings out of tests. JSON, TOML, and YAML
are supported; YAML and Python 3.10 TOML support are in the `config` extra. Only
environment-variable names belong in a profile—never token values.

```toml
[profiles.stage]
target = "dns:///users.stage.internal:443"
ca_file = "certs/corporate-ca.pem"
client_cert_file = "certs/test-client.pem"
client_key_file = "certs/test-client-key.pem"
token_env = "USERS_GRPC_TOKEN"
timeout = 10.0
max_receive_message_bytes = 16777216
keepalive_time_ms = 30000
use_http_proxy = false
user_agent = "users-e2e/1.0"
```

```python
with Session.from_profile("grpc-testkit.toml", name="stage") as grpc:
    grpc.wait_until_ready()
```

Generate a safe starter layout and diagnose the runtime before a test run:

```bash
grpc-testkit init .
grpc-testkit doctor --profile grpc-testkit.toml --profile-name stage \
  --reflection --health --check-git --check-buf
```

For servers without reflection, use a descriptor set generated by this library:

```python
from grpc_testkit import DescriptorResolver, Session

resolver = DescriptorResolver.from_file("generated/descriptors.pb")
with Session("localhost:50051", resolver=resolver) as grpc:
    response = grpc.call("acme.users.v1.Users/GetUser", {"id": "42"})
```

Generated stubs remain first-class and provide the best IDE/type-checker experience:

```python
from grpc_testkit import ServiceClient, Session
from generated import users_pb2, users_pb2_grpc

with Session("localhost:50051") as grpc:
    users = ServiceClient(grpc, users_pb2_grpc.UsersStub)
    response = users.unary("GetUser", users_pb2.GetUserRequest(id="42"))
```

## Error model for tests

Calls are strict by default. A non-OK status raises `GrpcCallError`, but the exception
keeps the complete `Response`: status, details, initial/trailing metadata, elapsed time,
debug string, attempts, request, and raw call/error.

```python
import grpc
from grpc_testkit import GrpcCallError, expect_status

with expect_status(grpc.StatusCode.NOT_FOUND) as failure:
    users.unary("GetUser", users_pb2.GetUserRequest(id="missing"))

assert failure.response.details == "user not found"
```

For data-driven negative tests, capture the same response without an exception:

```python
response = users.unary(
    "GetUser",
    users_pb2.GetUserRequest(id="missing"),
    raise_on_error=False,
)
assert response.code is grpc.StatusCode.NOT_FOUND
```

## TLS, mTLS, metadata, and auth

Certificates may come from files or bytes. Client certificate and key must be supplied
together.

```python
from grpc_testkit import BearerToken, Session, TLSConfig

tls = TLSConfig(
    ca_file="certs/ca.pem",
    client_cert_file="certs/client.pem",
    client_key_file="certs/client-key.pem",
    server_name_override="service.internal",  # only when infrastructure requires it
)

with Session(
    "gateway.internal:443",
    tls=tls,
    auth=BearerToken(token_env="SERVICE_TOKEN"),
    metadata={"x-test-run-id": "run-123"},
) as grpc:
    ...
```

Use `channel_credentials=` for composite or cloud-provider credentials that do not fit
the built-in TLS model. Auth providers can compute metadata per call; async sessions
accept async providers. Secrets are redacted by bundled logging and Allure observers.

## Streaming

`Session.call()` resolves cardinality from descriptors. Server and bidi streaming
return a `StreamResponse`; its final status becomes available after consumption.

```python
stream = grpc.call("acme.events.v1.Events/Subscribe", {"topic": "orders"})
messages = stream.collect(max_messages=10)
assert stream.response.ok
```

The typed methods `unary_unary`, `unary_stream`, `stream_unary`, and `stream_stream`
accept generated stub callables directly. Async equivalents are available on
`AsyncSession`, and `arequest()` provides a one-call API.

## Modern transport and protobuf features

The dynamic payload path supports proto3 optional fields, oneofs, maps, enums, bytes,
well-known types, nested imports, `Any`, and all four RPC cardinalities. `PayloadFactory`
creates deterministic descriptor-driven messages; explicit overrides keep domain values
readable.

```python
from grpc_testkit import PayloadFactory

request = PayloadFactory(seed="test-case-42", repeated_items=2).build(
    users_pb2.CreateUserRequest,
    email="qa@example.test",
)
```

Transport helpers cover DNS, direct IPv4/IPv6, Unix sockets, Linux abstract sockets,
and xDS target URIs:

```python
from grpc_testkit import Session, Target

with Session(
    Target.xds("users.v1.Users", authority="test-mesh"),
    use_http_proxy=False,
    load_balancing_policy="round_robin",
    service_config={"loadBalancingConfig": [{"round_robin": {}}]},
) as grpc:
    ...
```

xDS still requires the consuming environment's bootstrap/control plane. Proxy behavior,
resolvers, load balancing, custom credentials/interceptors, gzip compression, message
limits, keepalive, authority and user-agent settings are passed to gRPC Core rather than
reimplemented.

Use `DeadlineBudget` to share one monotonic deadline across dependent calls. Rich
`google.rpc.Status` details are decoded with `rich_status(response)` when the `status`
extra is installed. Real TLS and mTLS are tested with an ephemeral CA/server/client
certificate chain.

## Assertions, snapshots, and local servers

`assert_message_snapshot()` stores stable protobuf JSON and supports dotted-field
redaction. Snapshot creation is explicit:

```bash
GRPC_TESTKIT_UPDATE_SNAPSHOTS=1 pytest tests/test_users_grpc.py
```

`GrpcTestServer` / `AsyncGrpcTestServer` and their pytest fixtures provide in-process
servers for service-object tests. They never need a network service and bind only to
loopback by default.

## Safe retries

Retries are deliberately opt-in and limited to unary-unary RPCs. Both a policy and an
explicit idempotency declaration are required, preventing accidental replay of writes.

```python
from grpc_testkit import RetryPolicy

response = users.unary(
    "GetUser",
    request,
    retry=RetryPolicy(max_attempts=3),
    idempotent=True,
)
assert len(response.attempts) <= 3
```

The library records every attempt in the final response. It does not retry streaming
RPCs or infer that a business operation is safe to replay.

## Proto sources and generation

Install `grpc-testkit[proto]`. A registry can acquire proto files from:

- a local file/tree;
- HTTP(S);
- a checksum-pinned zip/tar archive with safe extraction and optional path stripping;
- GitLab repository files at an explicit ref;
- a Git repository branch, tag, or commit;
- a Buf module through the installed Buf CLI;
- a descriptor set;
- a composite of several sources.

The registry stages downloads and generated code, validates the result, writes a SHA-256
lock, then atomically publishes the new snapshot. An inter-process lock protects xdist
and parallel CI, unchanged snapshots reuse generated artifacts, and existing code is
preserved when acquisition or compilation fails. HTTP headers can be sourced from named
environment variables, and archives can require an expected SHA-256. Remote downloads
and extracted archives have bounded sizes/member counts; cross-origin redirects discard
credentials, and traversal paths, links, duplicate outputs, and special files are
rejected on every OS.

`proto build` owns only an empty/new directory or one carrying its generated ownership
marker. It refuses roots, proto ancestors, symlinks, and arbitrary non-empty application
directories, so a mistaken `--output .` cannot replace a project checkout.

Example `grpc-testkit.json`:

```json
{
  "workspace": ".grpc-testkit",
  "compile": true,
  "generate_pyi": true,
  "source": {
    "type": "gitlab",
    "base_url": "https://gitlab.example.com",
    "project_id": 123,
    "ref": "v2.4.0",
    "paths": ["api/users/v1/users.proto"],
    "token_env": "GITLAB_PROTO_TOKEN"
  }
}
```

```bash
grpc-testkit proto sync --config grpc-testkit.json
grpc-testkit proto check --workspace .grpc-testkit
grpc-testkit proto build --proto-root protos --output generated
grpc-testkit proto inspect generated/descriptors.pb
grpc-testkit proto breaking . --against '.git#branch=main'
```

Never place tokens in the JSON file. Pin a tag or commit for reproducible CI; a moving
branch is useful for local development but changes the tested contract over time.

## CLI diagnostics

```bash
grpc-testkit services localhost:50051 --insecure
grpc-testkit call localhost:50051 acme.users.v1.Users/GetUser \
  --insecure --data '{"id":"42"}' \
  --metadata-env authorization=SERVICE_AUTHORIZATION
```

TLS is the CLI default; pass `--insecure` explicitly for plaintext endpoints. Other
options include CA/client certificates, bearer token environment variable, metadata,
timeouts, captured errors, and a maximum number of streamed messages. Prefer
`--metadata-env KEY=ENV_NAME` over inline metadata for credentials. Common secret fields
in payloads and sensitive response metadata are redacted from output by default;
`--redact-field` adds domain-specific dotted paths. `--show-sensitive-metadata` is an
explicit escape hatch and should not be used in shared CI logs.

## pytest

Installing the `pytest` extra auto-registers these fixtures:

- `grpc_session`;
- `grpc_async_session_factory`;
- `grpc_expect_status`;
- `grpc_test_server`;
- `grpc_async_test_server`;
- `grpc_snapshot`.

Configure `GRPC_TARGET`, certificates through `GRPC_CA_CERT`, `GRPC_CLIENT_CERT`, and
`GRPC_CLIENT_KEY`, or equivalent command-line options. Plaintext requires
`--grpc-insecure`; otherwise TLS is used.

For reusable domain APIs, put generated stubs behind `ServiceClient` subclasses rather
than spreading channel and metadata mechanics across tests. See
[`examples/service_object.py`](examples/service_object.py).

## Design boundaries

- No production call is made during installation or proto compilation.
- No retry is performed unless the test declares the unary operation idempotent.
- Reflection is optional because production services frequently disable it.
- Generated stubs and descriptor-driven calls share one `Response` and assertion model.
- Blocking and async transports are separate; the library does not hide event-loop
  ownership.
- `grpcio-observability` is opt-in and never initialized as an import side effect.
- PEP 561 metadata (`py.typed`) is shipped so typed service clients work in consumers.

More detail is in [`docs/architecture.md`](docs/architecture.md), CI setup is covered by
[`docs/ci-integrations.md`](docs/ci-integrations.md), and release setup is covered by
[`docs/publishing.md`](docs/publishing.md).

## Development

```bash
python -m venv .venv
. .venv/bin/activate
python -m pip install -e ".[dev]"
ruff check .
mypy src
pytest --cov=grpc_testkit --cov-report=term-missing
bandit -q -r src/grpc_testkit -ll
pip-audit --local --skip-editable --progress-spinner off
git ls-files -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline
python -m build
twine check dist/*
```

The test suite uses only in-process gRPC servers and does not require a live service.
For container verification use `docker compose -f docker-compose.test.yml build` and
`docker compose -f docker-compose.test.yml run --rm debian` (or `alpine`). Cross-platform
details are in [`docs/cross-platform.md`](docs/cross-platform.md). A real inter-pod mTLS
gRPC smoke test for upstream Kubernetes is documented in [`k8s/README.md`](k8s/README.md).
