> ## Documentation Index
> Fetch the complete documentation index at: https://shinydapps-bd9fa40b.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# テスト

> L402インテグレーションをエンドツーエンドでテストする — ローカル、CI、および実際の支払いで。

## 概要

L402 APIのテストには2つの層があります：

1. **ユニット／インテグレーションテスト** — 実際のLightning支払いなしでミドルウェアロジックを検証する
2. **エンドツーエンドテスト** — 実際のウォレットと実際のsatsで完全なフローを検証する

***

## ユニットテスト — プロバイダーをモックする

モックの`LightningProvider`を渡してLightningを完全にバイパスする：

```typescript theme={null}
import { l402, LightningProvider, Invoice } from "l402-kit";
import request from "supertest";
import express from "express";

const mockProvider: LightningProvider = {
  async createInvoice(amountSats: number): Promise<Invoice> {
    const hash = "abc123def456abc123def456abc123def456abc123def456abc123def456abc1";
    const macaroon = Buffer.from(
      JSON.stringify({ hash, exp: Date.now() + 3_600_000 })
    ).toString("base64");
    return { paymentRequest: "lnbc1...", paymentHash: hash, macaroon, amountSats };
  },
  async checkPayment(paymentHash: string): Promise<boolean> {
    return true; // always paid in tests
  },
};

const app = express();
app.get("/premium", l402({ priceSats: 10, lightning: mockProvider }), (_req, res) => {
  res.json({ data: "ok" });
});

// Test 1 — no auth → 402
const res402 = await request(app).get("/premium");
assert(res402.status === 402);
assert(res402.body.invoice === "lnbc1...");

// Test 2 — valid token → 200
// SHA256("correct-preimage") must equal the paymentHash above, or use a real hash pair
const macaroon = res402.body.macaroon;
const preimage = "correct-preimage-hex"; // must satisfy SHA256(preimage) == paymentHash
const res200 = await request(app)
  .get("/premium")
  .set("Authorization", `L402 ${macaroon}:${preimage}`);
assert(res200.status === 200);
```

### テスト用の有効なpreimageを生成する

```typescript theme={null}
import { createHash, randomBytes } from "crypto";

// Generate a real hash/preimage pair
const preimage = randomBytes(32).toString("hex");
const paymentHash = createHash("sha256").update(Buffer.from(preimage, "hex")).digest("hex");

// Use these in your mock provider
const mockProvider: LightningProvider = {
  async createInvoice(amountSats: number): Promise<Invoice> {
    const macaroon = Buffer.from(
      JSON.stringify({ hash: paymentHash, exp: Date.now() + 3_600_000 })
    ).toString("base64");
    return { paymentRequest: "lnbc1...", paymentHash, macaroon, amountSats };
  },
  async checkPayment(): Promise<boolean> { return true; },
};

// In your test:
// Authorization: L402 <macaroon>:<preimage>
// This satisfies SHA256(preimage) == paymentHash ✓
```

***

## Python — モックプロバイダーでpytest

```python theme={null}
import pytest
import hashlib
import secrets
import base64
import json
from fastapi.testclient import TestClient
from l402kit.types import LightningProvider, Invoice
from your_app import app

class MockProvider(LightningProvider):
    def __init__(self):
        self.preimage = secrets.token_hex(32)
        self.payment_hash = hashlib.sha256(bytes.fromhex(self.preimage)).hexdigest()

    async def create_invoice(self, amount_sats: int) -> Invoice:
        exp = int((__import__("time").time() + 3600) * 1000)
        macaroon = base64.b64encode(
            json.dumps({"hash": self.payment_hash, "exp": exp}).encode()
        ).decode()
        return Invoice(
            payment_request="lnbc1...",
            payment_hash=self.payment_hash,
            macaroon=macaroon,
            amount_sats=amount_sats,
        )

    async def check_payment(self, payment_hash: str) -> bool:
        return True

def test_402_then_200(monkeypatch):
    provider = MockProvider()
    monkeypatch.setattr("your_app.lightning", provider)
    client = TestClient(app)

    # Step 1: no auth → 402
    res = client.get("/premium")
    assert res.status_code == 402
    macaroon = res.json()["macaroon"]

    # Step 2: valid L402 token → 200
    auth = f"L402 {macaroon}:{provider.preimage}"
    res = client.get("/premium", headers={"Authorization": auth})
    assert res.status_code == 200
```

***

## リプレイ保護のテスト

preimageが再利用できないことを検証する：

```typescript theme={null}
const res1 = await request(app)
  .get("/premium")
  .set("Authorization", `L402 ${macaroon}:${preimage}`);
assert(res1.status === 200); // first use — ok

const res2 = await request(app)
  .get("/premium")
  .set("Authorization", `L402 ${macaroon}:${preimage}`);
assert(res2.status === 401); // replay — rejected
assert(res2.body.error === "Token already used");
```

***

## CIパイプライン

CIではモックプロバイダーを使用する — Lightning ノードやAPIキーは不要：

```yaml theme={null}
# .github/workflows/test.yml
- name: Run tests
  run: npm test
  env:
    NODE_ENV: test
    # No BLINK_API_KEY needed — mock provider is used in test env
```

環境によってプロバイダーの選択を制御する：

```typescript theme={null}
const lightning = process.env.NODE_ENV === "test"
  ? mockProvider
  : ManagedProvider.fromAddress(process.env.LIGHTNING_ADDRESS!);
```

***

## 実際のsatsでのエンドツーエンドテスト

完全な支払いフローのテスト（ステージング／リリース前）：

1. `priceSats: 1`を設定する — テスト実行あたり約\$0.0008のコスト
2. [OpenNode sandbox](https://app.opennode.com)（`testMode: true`）を使用して実際のお金なしで支払う：
   ```typescript theme={null}
   const lightning = new OpenNodeProvider(process.env.OPENNODE_KEY!, true); // testMode
   ```
3. またはBlinkウォレットを使用する — 1 sat支払いは実質的に無料

### テストウォレットを使った自動E2E

```typescript theme={null}
import { L402Client, BlinkWallet } from "l402-kit";

// Use a dedicated test wallet with a small budget
const wallet = new BlinkWallet(
  process.env.TEST_BLINK_API_KEY!,
  process.env.TEST_BLINK_WALLET_ID!,
);
const client = new L402Client({ wallet, budgetSats: 100 });

const res = await client.fetch("http://localhost:3000/premium");
assert(res.ok);
const data = await res.json();
assert(data.data !== undefined);
```

***

## 本番前チェックリスト

<Steps>
  <Step title="モックプロバイダーでユニットテストが通過する">
    402 → 支払い → 200のフローを検証済み。リプレイ保護を検証済み（2回目の使用で401が返る）。
  </Step>

  <Step title="トークンの有効期限をテスト済み">
    モックのmacaroonで`exp: Date.now() - 1`を設定する — ミドルウェアが401を返すことを検証する。
  </Step>

  <Step title="priceSats: 1で実際の支払いによる完全なE2Eを実施">
    実際のウォレット、実際の支払い、実際の200 OK。スマートフォンでWallet of SatoshiまたはBlinkを使用する。
  </Step>

  <Step title="デプロイ環境に適したリプレイ保護が設定されている">
    シングルプロセス：デフォルトのインメモリアダプターで問題なし。マルチプロセス（Kubernetes、PM2クラスター）：SupabaseまたはRedisアダプターを使用する。[本番ガイド](/guides/production)を参照。
  </Step>
</Steps>
