CodeSampleX

示例

chai 5.3.3: assert

已验证示例 — npm chai 5.3.3: assert. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: assert.strictEqual and assert.notStrictEqual validate primitive…

sha256:0c4d062207c3af189d2802de36e85b35dc7fff21de8aafd986e981c7e98e0dc0

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 npm

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

案例

HOW
目标
verify assert in pkg:npm/chai@5.3.3
包
符号
  • assert
创建时间
2026-08-27T02:21:25Z

契约

  1. assert.strictEqual and assert.notStrictEqual validate primitive identity and differentiation
  2. assert.deepEqual and assert.notDeepEqual validate structural equality across nested objects and arrays
  3. assert.typeOf and assert.instanceOf verify value types and prototype inheritance
  4. assert.isAtLeast and assert.isAtMost validate inclusive numeric boundaries
  5. assert.include and assert.lengthOf verify collection contents and exact size
  6. assert.throws asserts function failure matching constructor or pattern and AssertionError is thrown on failed assertions

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

下载源代码构件 (tar.gz)

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify assert in pkg:npm/chai@5.3.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/chai@5.3.3
Demonstrate these symbols/APIs:
  - assert

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:c531058111b001d2843ff08efbb6a0849eff4f6157698e5a51886b6989c40cd9","contract":["assert.strictEqual and assert.notStrictEqual validate primitive identity and differentiation","assert.deepEqual and assert.notDeepEqual validate structural equality across nested objects and arrays","assert.typeOf and assert.instanceOf verify value types and prototype inheritance","assert.isAtLeast and assert.isAtMost validate inclusive numeric boundaries","assert.include and assert.lengthOf verify collection contents and exact size","assert.throws asserts function failure matching constructor or pattern and AssertionError is thrown on failed assertions"],"goal":"verify assert in pkg:npm/chai@5.3.3","kind":"HOW","packages":["pkg:npm/chai@5.3.3"],"schemaVersion":1,"symbols":["assert"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/chai@5.3.3"],"schemaVersion":1,"subject":"pkg:npm/chai@5.3.3","symbols":["assert"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-chai-assert",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-chai-assert",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "chai": "5.3.3"
      }
    },
    "node_modules/assertion-error": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
      "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/chai": {
      "version": "5.3.3",
      "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
      "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
      "license": "MIT",
      "dependencies": {
        "assertion-error": "^2.0.1",
        "check-error": "^2.1.1",
        "deep-eql": "^5.0.1",
        "loupe": "^3.1.0",
        "pathval": "^2.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/check-error": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
      "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
      "license": "MIT",
      "engines": {
        "node": ">= 16"
      }
    },
    "node_modules/deep-eql": {
      "version": "5.0.2",
      "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
      "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/loupe": {
      "version": "3.2.1",
      "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
      "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
      "license": "MIT"
    },
    "node_modules/pathval": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
      "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 14.16"
      }
    }
  }
}
package.json
{
  "name": "sample-chai-assert",
  "version": "1.0.0",
  "description": "Clean-room verification of assert in chai",
  "type": "module",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "chai": "5.3.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify assert in pkg:npm/chai@5.3.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/chai@5.3.3"
  ],
  "symbols": [
    "assert"
  ]
}
src/index.js
import { assert } from 'chai';

/**
 * Validates strict primitive equality or inequality.
 *
 * @param {unknown} actual - Actual value.
 * @param {unknown} expected - Expected value.
 * @param {boolean} [shouldEqual=true] - Whether values should be strictly equal.
 * @returns {boolean} True if assertion passes.
 */
export function checkStrictEquality(actual, expected, shouldEqual = true) {
  if (shouldEqual) {
    assert.strictEqual(actual, expected, 'values must be strictly equal');
  } else {
    assert.notStrictEqual(actual, expected, 'values must not be strictly equal');
  }
  return true;
}

/**
 * Validates deep structural equality or inequality.
 *
 * @param {unknown} actual - Actual value.
 * @param {unknown} expected - Expected value.
 * @param {boolean} [shouldEqual=true] - Whether values should be deeply equal.
 * @returns {boolean} True if assertion passes.
 */
export function checkDeepEquality(actual, expected, shouldEqual = true) {
  if (shouldEqual) {
    assert.deepEqual(actual, expected, 'values must be deeply equal');
  } else {
    assert.notDeepEqual(actual, expected, 'values must not be deeply equal');
  }
  return true;
}

/**
 * Validates JavaScript runtime type and constructor instance.
 *
 * @param {unknown} value - Value to check.
 * @param {string} expectedType - Expected typeof string name (e.g., 'string', 'number', 'object').
 * @param {Function} [expectedConstructor] - Expected constructor class/function.
 * @returns {boolean} True if assertion passes.
 */
export function checkTypeAndInstance(value, expectedType, expectedConstructor) {
  assert.typeOf(value, expectedType, `value must be typeof ${expectedType}`);
  if (expectedConstructor) {
    assert.instanceOf(value, expectedConstructor, 'value must be instance of expected constructor');
  }
  return true;
}

/**
 * Validates numeric ranges with boundary assertions.
 *
 * @param {number} value - Numeric value to check.
 * @param {number} min - Lower bound.
 * @param {number} max - Upper bound.
 * @returns {boolean} True if assertion passes.
 */
export function checkNumericBounds(value, min, max) {
  assert.isAtLeast(value, min, `value ${value} must be at least ${min}`);
  assert.isAtMost(value, max, `value ${value} must be at most ${max}`);
  return true;
}

/**
 * Validates collection membership, string patterns, and object properties.
 *
 * @param {Array|string} collection - Collection or string to inspect.
 * @param {unknown} element - Element or substring expected to be included.
 * @param {number} length - Expected length of collection.
 * @returns {boolean} True if assertion passes.
 */
export function checkCollectionAndLength(collection, element, length) {
  assert.lengthOf(collection, length, `collection must have length ${length}`);
  assert.include(collection, element, 'collection must include specified element');
  return true;
}

/**
 * Asserts that a function throws an error matching constructor and message/regex.
 *
 * @param {() => unknown} fn - Function to execute.
 * @param {Function} [errorConstructor] - Expected error constructor.
 * @param {string|RegExp} [matcher] - Expected message or pattern.
 * @returns {boolean} True if assertion passes.
 */
export function checkThrows(fn, errorConstructor, matcher) {
  if (errorConstructor && matcher) {
    assert.throws(fn, errorConstructor, matcher);
  } else if (errorConstructor) {
    assert.throws(fn, errorConstructor);
  } else {
    assert.throws(fn);
  }
  return true;
}

export { assert };
test/contract.mjs
import { assert } from 'chai';
import {
  checkStrictEquality,
  checkDeepEquality,
  checkTypeAndInstance,
  checkNumericBounds,
  checkCollectionAndLength,
  checkThrows,
} from '../src/index.js';

async function runContract() {
  // 1. Primitive equality assertions
  assert.strictEqual('hello', 'hello', 'strictEqual should match identical strings');
  assert.notStrictEqual('hello', 'world', 'notStrictEqual should distinguish different strings');
  assert.isTrue(checkStrictEquality(42, 42, true));
  assert.isTrue(checkStrictEquality(42, 43, false));

  // 2. Structural deep equality assertions
  const dataA = { items: [1, 2, { key: 'value' }], enabled: true };
  const dataB = { items: [1, 2, { key: 'value' }], enabled: true };
  const dataC = { items: [1, 2, { key: 'different' }], enabled: true };
  assert.deepEqual(dataA, dataB, 'deepEqual should pass for equal nested structures');
  assert.notDeepEqual(dataA, dataC, 'notDeepEqual should fail for differing nested structures');
  assert.isTrue(checkDeepEquality(dataA, dataB, true));
  assert.isTrue(checkDeepEquality(dataA, dataC, false));

  // 3. Type and constructor instance assertions (Chai uses type-detect for typeOf)
  assert.typeOf('sample', 'string');
  assert.typeOf(12345, 'number');
  assert.typeOf(true, 'boolean');
  assert.typeOf({ a: 1 }, 'object');
  assert.typeOf([1, 2], 'array');
  assert.typeOf(new Map(), 'Map');
  assert.instanceOf(new Date(), Date);
  assert.instanceOf(new TypeError('type err'), Error);
  assert.isTrue(checkTypeAndInstance('sample', 'string', null));
  assert.isTrue(checkTypeAndInstance(new Map(), 'Map', Map));

  // 4. Numeric boundary assertions
  assert.isAtLeast(10, 5, '10 should be at least 5');
  assert.isAtLeast(10, 10, '10 should be at least 10');
  assert.isAtMost(10, 15, '10 should be at most 15');
  assert.isAtMost(10, 10, '10 should be at most 10');
  assert.isAbove(10, 9);
  assert.isBelow(10, 11);
  assert.isTrue(checkNumericBounds(25, 10, 50));

  // 5. Collection containment and length assertions
  const list = ['alpha', 'beta', 'gamma'];
  assert.lengthOf(list, 3, 'list length should be 3');
  assert.include(list, 'beta', 'list should include beta');
  assert.notInclude(list, 'delta', 'list should not include delta');
  assert.match('release-v1.0.0', /^release-v\d+\.\d+\.\d+$/);
  assert.isTrue(checkCollectionAndLength(['apple', 'banana', 'cherry'], 'banana', 3));

  // 6. Exception handling and failure verification
  const errorFn = () => {
    throw new RangeError('Index out of bounds');
  };
  assert.throws(errorFn, RangeError, /out of bounds/);
  assert.isTrue(checkThrows(errorFn, RangeError, 'Index out of bounds'));

  const safeFn = () => 100;
  assert.doesNotThrow(safeFn);

  // 7. Verify AssertionError is thrown when assert fails
  let threwAssertionError = false;
  try {
    assert.strictEqual(1, 2, 'should fail');
  } catch (err) {
    threwAssertionError = true;
    assert.strictEqual(err.name, 'AssertionError', 'thrown error name must be AssertionError');
  }
  assert.isTrue(threwAssertionError, 'failed assertion must throw an error');

  console.log('Contract tests passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名