CodeSampleX

Exemple

@vitest/runner 4.1.10: getCurrentTest

Échantillon vérifié pour npm @vitest/runner 4.1.10: getCurrentTest. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi.

sha256:0f0b623b3530aaf1f23a2984616e8e7980f9414ead5d6c8e10edca318e53fdac

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

Cas

HOW
Objectif
verify @vitest/runner.getCurrentTest in pkg:npm/%40vitest/runner@4.1.10
Paquets
Symboles
  • @vitest/runner.getCurrentTest
Environnement
node 22.23.2
Créé
2026-09-06T19:49:37Z

Contrat

  1. getCurrentTest returns undefined when called outside an active test execution context
  2. getCurrentTest returns the active test task with name and enclosing suite during test execution
  3. getCurrentTest maintains active test reference across asynchronous boundaries within test functions
  4. onTestFinished and onTestFailed resolve active test from getCurrentTest and throw outside tests
  5. nested test definitions throw an error when getCurrentTest detects an active test execution context
  6. getCurrentTest resets to undefined once runner test execution completes

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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 @vitest/runner.getCurrentTest in pkg:npm/%40vitest/runner@4.1.10
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/runner@4.1.10
Demonstrate these symbols/APIs:
  - @vitest/runner.getCurrentTest
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - runtime: node@22.23.2

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:51e10dd5c943f6d1bf61b8f390470f27d0870e97655843b045832f2d4d899ec5","constraints":{"executionContext":"node"},"contract":["getCurrentTest returns undefined when called outside an active test execution context","getCurrentTest returns the active test task with name and enclosing suite during test execution","getCurrentTest maintains active test reference across asynchronous boundaries within test functions","onTestFinished and onTestFailed resolve active test from getCurrentTest and throw outside tests","nested test definitions throw an error when getCurrentTest detects an active test execution context","getCurrentTest resets to undefined once runner test execution completes"],"goal":"verify @vitest/runner.getCurrentTest in pkg:npm/%40vitest/runner@4.1.10","kind":"HOW","packages":["pkg:npm/%40vitest/runner@4.1.10"],"schemaVersion":1,"symbols":["@vitest/runner.getCurrentTest"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/runner@4.1.10"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/runner@4.1.10","symbols":["@vitest/runner.getCurrentTest"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-vitest-runner-get-current-test",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-runner-get-current-test",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/runner": "4.1.10"
      }
    },
    "node_modules/@vitest/pretty-format": {
      "version": "4.1.10",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz",
      "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^3.1.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/runner": {
      "version": "4.1.10",
      "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz",
      "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==",
      "license": "MIT",
      "dependencies": {
        "@vitest/utils": "4.1.10",
        "pathe": "^2.0.3"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/utils": {
      "version": "4.1.10",
      "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz",
      "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "4.1.10",
        "convert-source-map": "^2.0.0",
        "tinyrainbow": "^3.1.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/convert-source-map": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
      "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
      "license": "MIT"
    },
    "node_modules/pathe": {
      "version": "2.0.3",
      "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
      "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
      "license": "MIT"
    },
    "node_modules/tinyrainbow": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
      "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-runner-get-current-test",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for @vitest/runner@4.1.10",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/runner": "4.1.10"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/runner.getCurrentTest in pkg:npm/%40vitest/runner@4.1.10",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/runner@4.1.10"
  ],
  "symbols": [
    "@vitest/runner.getCurrentTest"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

const {
  getCurrentTest,
  startTests,
  describe,
  test,
  it,
  suite,
  onTestFinished,
  onTestFailed
} = require('@vitest/runner');

/**
 * Checks whether code is currently executing inside an active test.
 *
 * @returns {boolean} True if an active test context is present, false otherwise.
 */
function isInTestContext() {
  return getCurrentTest() !== undefined;
}

/**
 * Retrieves metadata for the currently executing test task.
 *
 * @returns {{ id: string, name: string, suiteName: string | undefined } | null}
 * Test metadata if inside a test, or null if called outside.
 */
function getCurrentTestMetadata() {
  const current = getCurrentTest();
  if (!current) {
    return null;
  }
  return {
    id: current.id,
    name: current.name,
    suiteName: current.suite?.name
  };
}

/**
 * Creates a minimal Vitest runner config and executes test definitions.
 *
 * @param {string} specName - Symbolic test file name.
 * @param {() => void | Promise<void>} defineTests - Callback defining suites and tests.
 * @param {object} [customConfig] - Optional runner configuration overrides.
 * @returns {Promise<Array<any>>} The executed test files.
 */
async function executeRunnerTests(specName, defineTests, customConfig = {}) {
  const config = {
    root: process.cwd(),
    setupFiles: [],
    passWithNoTests: true,
    allowOnly: true,
    sequence: { seed: 1, hooks: 'stack', setupFiles: 'list' },
    maxConcurrency: 5,
    testTimeout: 5000,
    hookTimeout: 5000,
    retry: 0,
    strictTags: false,
    ...customConfig
  };

  const runner = {
    config,
    importFile: async () => {
      await defineTests();
    }
  };

  return startTests([specName], runner);
}

module.exports = {
  getCurrentTest,
  startTests,
  describe,
  test,
  it,
  suite,
  onTestFinished,
  onTestFailed,
  isInTestContext,
  getCurrentTestMetadata,
  executeRunnerTests
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  getCurrentTest,
  describe,
  test,
  onTestFinished,
  onTestFailed,
  isInTestContext,
  getCurrentTestMetadata,
  executeRunnerTests
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification and initial state outside test execution
  assert.equal(typeof getCurrentTest, 'function', 'getCurrentTest must be an exported function');
  assert.equal(getCurrentTest(), undefined, 'getCurrentTest returns undefined outside test execution');
  assert.equal(isInTestContext(), false, 'isInTestContext returns false outside test execution');
  assert.equal(getCurrentTestMetadata(), null, 'getCurrentTestMetadata returns null outside test execution');

  // 2. Lifecycle hooks throw outside active test context
  assert.throws(
    () => onTestFinished(() => {}),
    {
      name: 'Error',
      message: 'Hook onTestFinished() can only be called inside a test'
    },
    'onTestFinished should throw Error when called outside a test'
  );

  assert.throws(
    () => onTestFailed(() => {}),
    {
      name: 'Error',
      message: 'Hook onTestFailed() can only be called inside a test'
    },
    'onTestFailed should throw Error when called outside a test'
  );

  // 3. Active test execution context in synchronous tests
  let syncObservedInTest = false;
  let syncObservedMeta = null;
  let finishedHookRan = false;

  await executeRunnerTests('sync-suite.spec.js', () => {
    describe('synchronous suite', () => {
      test('synchronous test case', () => {
        syncObservedInTest = isInTestContext();
        syncObservedMeta = getCurrentTestMetadata();
        onTestFinished(() => {
          finishedHookRan = true;
        });
      });
    });
  });

  assert.equal(syncObservedInTest, true, 'isInTestContext must be true inside active test');
  assert.ok(syncObservedMeta, 'getCurrentTestMetadata must return metadata inside test');
  assert.equal(syncObservedMeta.name, 'synchronous test case', 'test name must match active test');
  assert.equal(syncObservedMeta.suiteName, 'synchronous suite', 'enclosing suite name must match');
  assert.equal(finishedHookRan, true, 'onTestFinished hook registered via active test must execute');

  // 4. Asynchronous context preservation across await
  let beforeAwaitTest = null;
  let afterAwaitTest = null;

  await executeRunnerTests('async-suite.spec.js', () => {
    describe('asynchronous suite', () => {
      test('asynchronous test case', async () => {
        beforeAwaitTest = getCurrentTest();
        await new Promise((resolve) => setTimeout(resolve, 10));
        afterAwaitTest = getCurrentTest();
      });
    });
  });

  assert.ok(beforeAwaitTest, 'getCurrentTest must return test object before await');
  assert.equal(beforeAwaitTest.name, 'asynchronous test case', 'test name must match before await');
  assert.equal(beforeAwaitTest, afterAwaitTest, 'getCurrentTest must preserve the same test reference across await');

  // 5. Calling test() inside another test is prevented
  let nestedTestError = null;

  await executeRunnerTests('nested-suite.spec.js', () => {
    describe('parent suite', () => {
      test('outer test', () => {
        try {
          test('illegal nested test', () => {});
        } catch (err) {
          nestedTestError = err.message;
        }
      });
    });
  });

  assert.match(
    nestedTestError,
    /Calling the test function inside another test function is not allowed/,
    'nested test definition must throw when getCurrentTest detects an active test'
  );

  // 6. State reset after execution completes
  assert.equal(getCurrentTest(), undefined, 'getCurrentTest must reset to undefined once tests complete');
  assert.equal(isInTestContext(), false, 'isInTestContext must be false once tests complete');

  console.log('All @vitest/runner getCurrentTest contract assertions passed.');
}

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

Seeder d'origine

anonyme