diff --git a/.buildkite/ci.mjs b/.buildkite/ci.mjs
index 31144f19ed..70d4e44c1d 100755
--- a/.buildkite/ci.mjs
+++ b/.buildkite/ci.mjs
@@ -304,15 +304,23 @@ function getPipeline(options) {
* @param {Target} target
* @returns {Agent}
*/
- const getZigAgent = target => {
- const { abi, arch } = target;
- // if (abi === "musl") {
- // const instanceType = arch === "aarch64" ? "c8g.large" : "c7i.large";
- // return getEmphemeralAgent("v2", target, instanceType);
- // }
+ const getZigAgent = platform => {
+ const { arch } = platform;
+ const instanceType = arch === "aarch64" ? "c8g.2xlarge" : "c7i.2xlarge";
return {
- queue: "build-zig",
+ robobun: true,
+ robobun2: true,
+ os: "linux",
+ arch,
+ distro: "debian",
+ release: "11",
+ "image-name": `linux-${arch}-debian-11-v5`, // v5 is not on main yet
+ "instance-type": instanceType,
};
+ // TODO: Temporarily disable due to configuration
+ // return {
+ // queue: "build-zig",
+ // };
};
/**
@@ -443,7 +451,7 @@ function getPipeline(options) {
label: `${getTargetLabel(platform)} - build-zig`,
depends_on: getDependsOn(platform),
agents: getZigAgent(platform),
- retry: getRetry(1), // FIXME: Sometimes zig build hangs, so we need to retry once
+ retry: getRetry(),
cancel_on_build_failing: isMergeQueue(),
env: getBuildEnv(platform),
command: `bun run build:ci --target bun-zig --toolchain ${toolchain}`,
@@ -664,16 +672,18 @@ async function main() {
}
let changedFiles;
- // FIXME: Fix various bugs when calculating changed files
- // false -> !isFork() && !isMainBranch()
- if (false) {
+ let changedFilesBranch;
+ if (!isFork() && !isMainBranch()) {
console.log("Checking changed files...");
- const baseRef = lastBuild?.commit_id || getTargetBranch() || getMainBranch();
+ const targetRef = getTargetBranch();
+ console.log(" - Target Ref:", targetRef);
+ const baseRef = lastBuild?.commit_id || targetRef || getMainBranch();
console.log(" - Base Ref:", baseRef);
const headRef = getCommit();
console.log(" - Head Ref:", headRef);
changedFiles = await getChangedFiles(undefined, baseRef, headRef);
+ changedFilesBranch = await getChangedFiles(undefined, targetRef, headRef);
if (changedFiles) {
if (changedFiles.length) {
changedFiles.forEach(filename => console.log(` - ${filename}`));
@@ -698,7 +708,7 @@ async function main() {
forceBuild = true;
}
for (const coref of [".buildkite/ci.mjs", "scripts/utils.mjs", "scripts/bootstrap.sh", "scripts/machine.mjs"]) {
- if (changedFiles && changedFiles.includes(coref)) {
+ if (changedFilesBranch && changedFilesBranch.includes(coref)) {
console.log(" - Yes, because the list of changed files contains:", coref);
forceBuild = true;
ciFileChanged = true;
diff --git a/.github/workflows/update-cares.yml b/.github/workflows/update-cares.yml
new file mode 100644
index 0000000000..d5d111b663
--- /dev/null
+++ b/.github/workflows/update-cares.yml
@@ -0,0 +1,92 @@
+name: Update c-ares
+
+on:
+ schedule:
+ - cron: "0 4 * * 0"
+ workflow_dispatch:
+
+jobs:
+ check-update:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check c-ares version
+ id: check-version
+ run: |
+ set -euo pipefail
+
+ # Extract the commit hash from the line after COMMIT
+ CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildCares.cmake)
+
+ if [ -z "$CURRENT_VERSION" ]; then
+ echo "Error: Could not find COMMIT line in BuildCares.cmake"
+ exit 1
+ fi
+
+ # Validate that it looks like a git hash
+ if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid git hash format in BuildCares.cmake"
+ echo "Found: $CURRENT_VERSION"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
+
+ LATEST_RELEASE=$(curl -sL https://api.github.com/repos/c-ares/c-ares/releases/latest)
+ if [ -z "$LATEST_RELEASE" ]; then
+ echo "Error: Failed to fetch latest release from GitHub API"
+ exit 1
+ fi
+
+ LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
+ if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
+ echo "Error: Could not extract tag name from GitHub API response"
+ exit 1
+ fi
+
+ LATEST_SHA=$(curl -sL "https://api.github.com/repos/c-ares/c-ares/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
+ if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
+ echo "Error: Could not fetch SHA for tag $LATEST_TAG"
+ exit 1
+ fi
+
+ if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid SHA format received from GitHub"
+ echo "Found: $LATEST_SHA"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
+
+ - name: Update version if needed
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ run: |
+ set -euo pipefail
+ # Handle multi-line format where COMMIT and its value are on separate lines
+ sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildCares.cmake
+
+ - name: Create Pull Request
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ uses: peter-evans/create-pull-request@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ add-paths: |
+ cmake/targets/BuildCares.cmake
+ commit-message: "deps: update c-ares to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
+ title: "deps: update c-ares to ${{ steps.check-version.outputs.tag }}"
+ delete-branch: true
+ branch: deps/update-cares-${{ github.run_number }}
+ body: |
+ ## What does this PR do?
+
+ Updates c-ares to version ${{ steps.check-version.outputs.tag }}
+
+ Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-cares.yml)
diff --git a/.github/workflows/update-libarchive.yml b/.github/workflows/update-libarchive.yml
new file mode 100644
index 0000000000..f4dce7cfce
--- /dev/null
+++ b/.github/workflows/update-libarchive.yml
@@ -0,0 +1,92 @@
+name: Update libarchive
+
+on:
+ schedule:
+ - cron: "0 3 * * 0"
+ workflow_dispatch:
+
+jobs:
+ check-update:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check libarchive version
+ id: check-version
+ run: |
+ set -euo pipefail
+
+ # Extract the commit hash from the line after COMMIT
+ CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLibArchive.cmake)
+
+ if [ -z "$CURRENT_VERSION" ]; then
+ echo "Error: Could not find COMMIT line in BuildLibArchive.cmake"
+ exit 1
+ fi
+
+ # Validate that it looks like a git hash
+ if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid git hash format in BuildLibArchive.cmake"
+ echo "Found: $CURRENT_VERSION"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
+
+ LATEST_RELEASE=$(curl -sL https://api.github.com/repos/libarchive/libarchive/releases/latest)
+ if [ -z "$LATEST_RELEASE" ]; then
+ echo "Error: Failed to fetch latest release from GitHub API"
+ exit 1
+ fi
+
+ LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
+ if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
+ echo "Error: Could not extract tag name from GitHub API response"
+ exit 1
+ fi
+
+ LATEST_SHA=$(curl -sL "https://api.github.com/repos/libarchive/libarchive/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
+ if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
+ echo "Error: Could not fetch SHA for tag $LATEST_TAG"
+ exit 1
+ fi
+
+ if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid SHA format received from GitHub"
+ echo "Found: $LATEST_SHA"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
+
+ - name: Update version if needed
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ run: |
+ set -euo pipefail
+ # Handle multi-line format where COMMIT and its value are on separate lines
+ sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLibArchive.cmake
+
+ - name: Create Pull Request
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ uses: peter-evans/create-pull-request@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ add-paths: |
+ cmake/targets/BuildLibArchive.cmake
+ commit-message: "deps: update libarchive to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
+ title: "deps: update libarchive to ${{ steps.check-version.outputs.tag }}"
+ delete-branch: true
+ branch: deps/update-libarchive-${{ github.run_number }}
+ body: |
+ ## What does this PR do?
+
+ Updates libarchive to version ${{ steps.check-version.outputs.tag }}
+
+ Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-libarchive.yml)
diff --git a/.github/workflows/update-libdeflate.yml b/.github/workflows/update-libdeflate.yml
new file mode 100644
index 0000000000..7e0be86a1c
--- /dev/null
+++ b/.github/workflows/update-libdeflate.yml
@@ -0,0 +1,92 @@
+name: Update libdeflate
+
+on:
+ schedule:
+ - cron: "0 2 * * 0"
+ workflow_dispatch:
+
+jobs:
+ check-update:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check libdeflate version
+ id: check-version
+ run: |
+ set -euo pipefail
+
+ # Extract the commit hash from the line after COMMIT
+ CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLibDeflate.cmake)
+
+ if [ -z "$CURRENT_VERSION" ]; then
+ echo "Error: Could not find COMMIT line in BuildLibDeflate.cmake"
+ exit 1
+ fi
+
+ # Validate that it looks like a git hash
+ if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid git hash format in BuildLibDeflate.cmake"
+ echo "Found: $CURRENT_VERSION"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
+
+ LATEST_RELEASE=$(curl -sL https://api.github.com/repos/ebiggers/libdeflate/releases/latest)
+ if [ -z "$LATEST_RELEASE" ]; then
+ echo "Error: Failed to fetch latest release from GitHub API"
+ exit 1
+ fi
+
+ LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
+ if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
+ echo "Error: Could not extract tag name from GitHub API response"
+ exit 1
+ fi
+
+ LATEST_SHA=$(curl -sL "https://api.github.com/repos/ebiggers/libdeflate/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
+ if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
+ echo "Error: Could not fetch SHA for tag $LATEST_TAG"
+ exit 1
+ fi
+
+ if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid SHA format received from GitHub"
+ echo "Found: $LATEST_SHA"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
+
+ - name: Update version if needed
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ run: |
+ set -euo pipefail
+ # Handle multi-line format where COMMIT and its value are on separate lines
+ sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLibDeflate.cmake
+
+ - name: Create Pull Request
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ uses: peter-evans/create-pull-request@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ add-paths: |
+ cmake/targets/BuildLibDeflate.cmake
+ commit-message: "deps: update libdeflate to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
+ title: "deps: update libdeflate to ${{ steps.check-version.outputs.tag }}"
+ delete-branch: true
+ branch: deps/update-libdeflate-${{ github.run_number }}
+ body: |
+ ## What does this PR do?
+
+ Updates libdeflate to version ${{ steps.check-version.outputs.tag }}
+
+ Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-libdeflate.yml)
diff --git a/.github/workflows/update-lolhtml.yml b/.github/workflows/update-lolhtml.yml
new file mode 100644
index 0000000000..f48c4b5ce9
--- /dev/null
+++ b/.github/workflows/update-lolhtml.yml
@@ -0,0 +1,92 @@
+name: Update lolhtml
+
+on:
+ schedule:
+ - cron: "0 1 * * 0"
+ workflow_dispatch:
+
+jobs:
+ check-update:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check lolhtml version
+ id: check-version
+ run: |
+ set -euo pipefail
+
+ # Extract the commit hash from the line after COMMIT
+ CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLolHtml.cmake)
+
+ if [ -z "$CURRENT_VERSION" ]; then
+ echo "Error: Could not find COMMIT line in BuildLolHtml.cmake"
+ exit 1
+ fi
+
+ # Validate that it looks like a git hash
+ if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid git hash format in BuildLolHtml.cmake"
+ echo "Found: $CURRENT_VERSION"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
+
+ LATEST_RELEASE=$(curl -sL https://api.github.com/repos/cloudflare/lol-html/releases/latest)
+ if [ -z "$LATEST_RELEASE" ]; then
+ echo "Error: Failed to fetch latest release from GitHub API"
+ exit 1
+ fi
+
+ LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
+ if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
+ echo "Error: Could not extract tag name from GitHub API response"
+ exit 1
+ fi
+
+ LATEST_SHA=$(curl -sL "https://api.github.com/repos/cloudflare/lol-html/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
+ if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
+ echo "Error: Could not fetch SHA for tag $LATEST_TAG"
+ exit 1
+ fi
+
+ if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid SHA format received from GitHub"
+ echo "Found: $LATEST_SHA"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
+
+ - name: Update version if needed
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ run: |
+ set -euo pipefail
+ # Handle multi-line format where COMMIT and its value are on separate lines
+ sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLolHtml.cmake
+
+ - name: Create Pull Request
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ uses: peter-evans/create-pull-request@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ add-paths: |
+ cmake/targets/BuildLolHtml.cmake
+ commit-message: "deps: update lolhtml to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
+ title: "deps: update lolhtml to ${{ steps.check-version.outputs.tag }}"
+ delete-branch: true
+ branch: deps/update-lolhtml-${{ github.run_number }}
+ body: |
+ ## What does this PR do?
+
+ Updates lolhtml to version ${{ steps.check-version.outputs.tag }}
+
+ Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-lolhtml.yml)
diff --git a/.github/workflows/update-lshpack.yml b/.github/workflows/update-lshpack.yml
new file mode 100644
index 0000000000..ae917cc3e9
--- /dev/null
+++ b/.github/workflows/update-lshpack.yml
@@ -0,0 +1,92 @@
+name: Update lshpack
+
+on:
+ schedule:
+ - cron: "0 5 * * 0"
+ workflow_dispatch:
+
+jobs:
+ check-update:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check lshpack version
+ id: check-version
+ run: |
+ set -euo pipefail
+
+ # Extract the commit hash from the line after COMMIT
+ CURRENT_VERSION=$(awk '/[[:space:]]*COMMIT[[:space:]]*$/{getline; gsub(/^[[:space:]]+|[[:space:]]+$/,"",$0); print}' cmake/targets/BuildLshpack.cmake)
+
+ if [ -z "$CURRENT_VERSION" ]; then
+ echo "Error: Could not find COMMIT line in BuildLshpack.cmake"
+ exit 1
+ fi
+
+ # Validate that it looks like a git hash
+ if ! [[ $CURRENT_VERSION =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid git hash format in BuildLshpack.cmake"
+ echo "Found: $CURRENT_VERSION"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
+
+ LATEST_RELEASE=$(curl -sL https://api.github.com/repos/litespeedtech/ls-hpack/releases/latest)
+ if [ -z "$LATEST_RELEASE" ]; then
+ echo "Error: Failed to fetch latest release from GitHub API"
+ exit 1
+ fi
+
+ LATEST_TAG=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
+ if [ -z "$LATEST_TAG" ] || [ "$LATEST_TAG" = "null" ]; then
+ echo "Error: Could not extract tag name from GitHub API response"
+ exit 1
+ fi
+
+ LATEST_SHA=$(curl -sL "https://api.github.com/repos/litespeedtech/ls-hpack/git/ref/tags/$LATEST_TAG" | jq -r '.object.sha')
+ if [ -z "$LATEST_SHA" ] || [ "$LATEST_SHA" = "null" ]; then
+ echo "Error: Could not fetch SHA for tag $LATEST_TAG"
+ exit 1
+ fi
+
+ if ! [[ $LATEST_SHA =~ ^[0-9a-f]{40}$ ]]; then
+ echo "Error: Invalid SHA format received from GitHub"
+ echo "Found: $LATEST_SHA"
+ echo "Expected: 40 character hexadecimal string"
+ exit 1
+ fi
+
+ echo "latest=$LATEST_SHA" >> $GITHUB_OUTPUT
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
+
+ - name: Update version if needed
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ run: |
+ set -euo pipefail
+ # Handle multi-line format where COMMIT and its value are on separate lines
+ sed -i -E '/[[:space:]]*COMMIT[[:space:]]*$/{n;s/[[:space:]]*([0-9a-f]+)[[:space:]]*$/ ${{ steps.check-version.outputs.latest }}/}' cmake/targets/BuildLshpack.cmake
+
+ - name: Create Pull Request
+ if: success() && steps.check-version.outputs.current != steps.check-version.outputs.latest
+ uses: peter-evans/create-pull-request@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ add-paths: |
+ cmake/targets/BuildLshpack.cmake
+ commit-message: "deps: update lshpack to ${{ steps.check-version.outputs.tag }} (${{ steps.check-version.outputs.latest }})"
+ title: "deps: update lshpack to ${{ steps.check-version.outputs.tag }}"
+ delete-branch: true
+ branch: deps/update-lshpack-${{ github.run_number }}
+ body: |
+ ## What does this PR do?
+
+ Updates lshpack to version ${{ steps.check-version.outputs.tag }}
+
+ Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-lshpack.yml)
diff --git a/.github/workflows/update-sqlite3.yml b/.github/workflows/update-sqlite3.yml
new file mode 100644
index 0000000000..66b5753cca
--- /dev/null
+++ b/.github/workflows/update-sqlite3.yml
@@ -0,0 +1,109 @@
+name: Update SQLite3
+
+on:
+ schedule:
+ - cron: "0 6 * * 0" # Run weekly
+ workflow_dispatch:
+
+jobs:
+ check-update:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check SQLite version
+ id: check-version
+ run: |
+ set -euo pipefail
+
+ # Get current version from the header file using SQLITE_VERSION_NUMBER
+ CURRENT_VERSION_NUM=$(grep -o '#define SQLITE_VERSION_NUMBER [0-9]\+' src/bun.js/bindings/sqlite/sqlite3_local.h | awk '{print $3}' | tr -d '\n\r')
+ if [ -z "$CURRENT_VERSION_NUM" ]; then
+ echo "Error: Could not find SQLITE_VERSION_NUMBER in sqlite3_local.h"
+ exit 1
+ fi
+
+ # Convert numeric version to semantic version for display
+ CURRENT_MAJOR=$((CURRENT_VERSION_NUM / 1000000))
+ CURRENT_MINOR=$((($CURRENT_VERSION_NUM / 1000) % 1000))
+ CURRENT_PATCH=$((CURRENT_VERSION_NUM % 1000))
+ CURRENT_VERSION="$CURRENT_MAJOR.$CURRENT_MINOR.$CURRENT_PATCH"
+
+ echo "current=$CURRENT_VERSION" >> $GITHUB_OUTPUT
+ echo "current_num=$CURRENT_VERSION_NUM" >> $GITHUB_OUTPUT
+
+ # Fetch SQLite download page
+ DOWNLOAD_PAGE=$(curl -sL https://sqlite.org/download.html)
+ if [ -z "$DOWNLOAD_PAGE" ]; then
+ echo "Error: Failed to fetch SQLite download page"
+ exit 1
+ fi
+
+ # Extract latest version and year from the amalgamation link
+ LATEST_INFO=$(echo "$DOWNLOAD_PAGE" | grep -o 'sqlite-amalgamation-[0-9]\{7\}.zip' | head -n1)
+ LATEST_YEAR=$(echo "$DOWNLOAD_PAGE" | grep -o '[0-9]\{4\}/sqlite-amalgamation-[0-9]\{7\}.zip' | head -n1 | cut -d'/' -f1 | tr -d '\n\r')
+ LATEST_VERSION_NUM=$(echo "$LATEST_INFO" | grep -o '[0-9]\{7\}' | tr -d '\n\r')
+
+ if [ -z "$LATEST_VERSION_NUM" ] || [ -z "$LATEST_YEAR" ]; then
+ echo "Error: Could not extract latest version info"
+ exit 1
+ fi
+
+ # Convert numeric version to semantic version for display
+ LATEST_MAJOR=$((10#$LATEST_VERSION_NUM / 1000000))
+ LATEST_MINOR=$((($LATEST_VERSION_NUM / 1000) % 1000))
+ LATEST_PATCH=$((10#$LATEST_VERSION_NUM % 1000))
+ LATEST_VERSION="$LATEST_MAJOR.$LATEST_MINOR.$LATEST_PATCH"
+
+ echo "latest=$LATEST_VERSION" >> $GITHUB_OUTPUT
+ echo "latest_year=$LATEST_YEAR" >> $GITHUB_OUTPUT
+ echo "latest_num=$LATEST_VERSION_NUM" >> $GITHUB_OUTPUT
+
+ # Debug output
+ echo "Current version: $CURRENT_VERSION ($CURRENT_VERSION_NUM)"
+ echo "Latest version: $LATEST_VERSION ($LATEST_VERSION_NUM)"
+
+ - name: Update SQLite if needed
+ if: success() && steps.check-version.outputs.current_num < steps.check-version.outputs.latest_num
+ run: |
+ set -euo pipefail
+
+ TEMP_DIR=$(mktemp -d)
+ cd $TEMP_DIR
+
+ echo "Downloading from: https://sqlite.org/${{ steps.check-version.outputs.latest_year }}/sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}.zip"
+
+ # Download and extract latest version
+ wget "https://sqlite.org/${{ steps.check-version.outputs.latest_year }}/sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}.zip"
+ unzip "sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}.zip"
+ cd "sqlite-amalgamation-${{ steps.check-version.outputs.latest_num }}"
+
+ # Add header comment and copy files
+ echo "// clang-format off" > $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3.c
+ cat sqlite3.c >> $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3.c
+
+ echo "// clang-format off" > $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3_local.h
+ cat sqlite3.h >> $GITHUB_WORKSPACE/src/bun.js/bindings/sqlite/sqlite3_local.h
+
+ - name: Create Pull Request
+ if: success() && steps.check-version.outputs.current_num < steps.check-version.outputs.latest_num
+ uses: peter-evans/create-pull-request@v4
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ add-paths: |
+ src/bun.js/bindings/sqlite/sqlite3.c
+ src/bun.js/bindings/sqlite/sqlite3_local.h
+ commit-message: "deps: update sqlite to ${{ steps.check-version.outputs.latest }}"
+ title: "deps: update sqlite to ${{ steps.check-version.outputs.latest }}"
+ delete-branch: true
+ branch: deps/update-sqlite-${{ steps.check-version.outputs.latest }}
+ body: |
+ ## What does this PR do?
+
+ Updates SQLite to version ${{ steps.check-version.outputs.latest }}
+
+ Auto-updated by [this workflow](https://github.com/oven-sh/bun/actions/workflows/update-sqlite3.yml)
diff --git a/.gitignore b/.gitignore
index 8491d87032..3822491fcb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -175,4 +175,5 @@ test/js/third_party/prisma/prisma/sqlite/dev.db-journal
# Generated files
.buildkite/ci.yml
-*.sock
\ No newline at end of file
+*.sock
+scratch*.{js,ts,tsx,cjs,mjs}
\ No newline at end of file
diff --git a/.prettierignore b/.prettierignore
index da765c9c28..42d0c454a9 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -5,6 +5,5 @@ test/js/deno
test/node.js
src/react-refresh.js
*.min.js
-test/js/node/test/fixtures
-test/js/node/test/common
test/snippets
+test/js/node/test
diff --git a/.vscode/launch.json b/.vscode/launch.json
index 191c0a815e..dc019a5445 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -224,8 +224,11 @@
"cwd": "${fileDirname}",
"env": {
"FORCE_COLOR": "1",
+ // "BUN_DEBUG_DEBUGGER": "1",
+ // "BUN_DEBUG_INTERNAL_DEBUGGER": "1",
"BUN_DEBUG_QUIET_LOGS": "1",
"BUN_GARBAGE_COLLECTOR_LEVEL": "2",
+ // "BUN_INSPECT": "ws+unix:///var/folders/jk/8fzl9l5119598vsqrmphsw7m0000gn/T/tl15npi7qtf.sock?report=1",
},
"console": "internalConsole",
// Don't pause when the GC runs while the debugger is open.
@@ -1254,4 +1257,4 @@
"description": "Usage: bun test [...]",
},
],
-}
+}
\ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
index faf1dc0d22..5ead186425 100644
--- a/.vscode/tasks.json
+++ b/.vscode/tasks.json
@@ -2,50 +2,57 @@
"version": "2.0.0",
"tasks": [
{
- "type": "process",
- "label": "Install Dependencies",
- "command": "scripts/all-dependencies.sh",
- "windows": {
- "command": "scripts/all-dependencies.ps1",
- },
- "icon": {
- "id": "arrow-down",
- },
- "options": {
- "cwd": "${workspaceFolder}",
- },
- },
- {
- "type": "process",
- "label": "Setup Environment",
- "dependsOn": ["Install Dependencies"],
- "command": "scripts/setup.sh",
- "windows": {
- "command": "scripts/setup.ps1",
- },
- "icon": {
- "id": "check",
- },
- "options": {
- "cwd": "${workspaceFolder}",
- },
- },
- {
- "type": "process",
"label": "Build Bun",
- "dependsOn": ["Setup Environment"],
- "command": "bun",
- "args": ["run", "build"],
- "icon": {
- "id": "gear",
+ "type": "shell",
+ "command": "bun run build",
+ "group": {
+ "kind": "build",
+ "isDefault": true,
},
- "options": {
- "cwd": "${workspaceFolder}",
- },
- "isBuildCommand": true,
- "runOptions": {
- "instanceLimit": 1,
- "reevaluateOnRerun": true,
+ "problemMatcher": [
+ {
+ "owner": "zig",
+ "fileLocation": ["relative", "${workspaceFolder}"],
+ "pattern": [
+ {
+ "regexp": "^(.+?):(\\d+):(\\d+): (error|warning|note): (.+)$",
+ "file": 1,
+ "line": 2,
+ "column": 3,
+ "severity": 4,
+ "message": 5,
+ },
+ {
+ "regexp": "^\\s+(.+)$",
+ "message": 1,
+ "loop": true,
+ },
+ ],
+ },
+ {
+ "owner": "clang",
+ "fileLocation": ["relative", "${workspaceFolder}"],
+ "pattern": [
+ {
+ "regexp": "^([^:]+):(\\d+):(\\d+):\\s+(warning|error|note|remark):\\s+(.*)$",
+ "file": 1,
+ "line": 2,
+ "column": 3,
+ "severity": 4,
+ "message": 5,
+ },
+ {
+ "regexp": "^\\s*(.*)$",
+ "message": 1,
+ "loop": true,
+ },
+ ],
+ },
+ ],
+ "presentation": {
+ "reveal": "always",
+ "panel": "shared",
+ "clear": true,
},
},
],
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0bf6e5cf59..1a7f41ae5c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,6 +1,6 @@
Configuring a development environment for Bun can take 10-30 minutes depending on your internet connection and computer speed. You will need ~10GB of free disk space for the repository and build artifacts.
-If you are using Windows, please refer to [this guide](/docs/project/building-windows)
+If you are using Windows, please refer to [this guide](/docs/project/building-windows.md)
{% details summary="For Ubuntu users" %}
TL;DR: Ubuntu 22.04 is suggested.
diff --git a/LATEST b/LATEST
index 474ad5be60..c99926d330 100644
--- a/LATEST
+++ b/LATEST
@@ -1 +1 @@
-1.1.36
\ No newline at end of file
+1.1.38
\ No newline at end of file
diff --git a/build.zig b/build.zig
index fed6086672..cfc512ad8d 100644
--- a/build.zig
+++ b/build.zig
@@ -414,6 +414,15 @@ pub fn addBunObject(b: *Build, opts: *BunBuildOptions) *Compile {
}
addInternalPackages(b, obj, opts);
obj.root_module.addImport("build_options", opts.buildOptionsModule(b));
+
+ const translate_plugin_api = b.addTranslateC(.{
+ .root_source_file = b.path("./packages/bun-native-bundler-plugin-api/bundler_plugin.h"),
+ .target = opts.target,
+ .optimize = opts.optimize,
+ .link_libc = true,
+ });
+ obj.root_module.addImport("bun-native-bundler-plugin-api", translate_plugin_api.createModule());
+
return obj;
}
diff --git a/cmake/Globals.cmake b/cmake/Globals.cmake
index 106e1285ea..3066bb2033 100644
--- a/cmake/Globals.cmake
+++ b/cmake/Globals.cmake
@@ -136,16 +136,6 @@ else()
set(WARNING WARNING)
endif()
-if(LINUX)
- if(EXISTS "/etc/alpine-release")
- set(DEFAULT_ABI "musl")
- else()
- set(DEFAULT_ABI "gnu")
- endif()
-
- optionx(ABI "musl|gnu" "The ABI to use (e.g. musl, gnu)" DEFAULT ${DEFAULT_ABI})
-endif()
-
# TODO: This causes flaky zig builds in CI, so temporarily disable it.
# if(CI)
# set(DEFAULT_VENDOR_PATH ${CACHE_PATH}/vendor)
diff --git a/cmake/Options.cmake b/cmake/Options.cmake
index 89cdaef0e8..d6cc8582ea 100644
--- a/cmake/Options.cmake
+++ b/cmake/Options.cmake
@@ -48,6 +48,16 @@ else()
message(FATAL_ERROR "Unsupported architecture: ${CMAKE_SYSTEM_PROCESSOR}")
endif()
+if(LINUX)
+ if(EXISTS "/etc/alpine-release")
+ set(DEFAULT_ABI "musl")
+ else()
+ set(DEFAULT_ABI "gnu")
+ endif()
+
+ optionx(ABI "musl|gnu" "The ABI to use (e.g. musl, gnu)" DEFAULT ${DEFAULT_ABI})
+endif()
+
if(ARCH STREQUAL "x64")
optionx(ENABLE_BASELINE BOOL "If baseline features should be used for older CPUs (e.g. disables AVX, AVX2)" DEFAULT OFF)
endif()
diff --git a/cmake/targets/BuildBun.cmake b/cmake/targets/BuildBun.cmake
index c27d820afe..20cbb8293e 100644
--- a/cmake/targets/BuildBun.cmake
+++ b/cmake/targets/BuildBun.cmake
@@ -1163,7 +1163,7 @@ if(NOT BUN_CPP_ONLY)
if(CI)
set(bunTriplet bun-${OS}-${ARCH})
- if(ABI STREQUAL "musl")
+ if(LINUX AND ABI STREQUAL "musl")
set(bunTriplet ${bunTriplet}-musl)
endif()
if(ENABLE_BASELINE)
diff --git a/cmake/targets/BuildCares.cmake b/cmake/targets/BuildCares.cmake
index e49d9a7ab9..373369b543 100644
--- a/cmake/targets/BuildCares.cmake
+++ b/cmake/targets/BuildCares.cmake
@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
c-ares/c-ares
COMMIT
- d1722e6e8acaf10eb73fa995798a9cd421d9f85e
+ 41ee334af3e3d0027dca5e477855d0244936bd49
)
register_cmake_command(
diff --git a/cmake/targets/BuildLibDeflate.cmake b/cmake/targets/BuildLibDeflate.cmake
index 3faf5963a7..f629d52fe5 100644
--- a/cmake/targets/BuildLibDeflate.cmake
+++ b/cmake/targets/BuildLibDeflate.cmake
@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
ebiggers/libdeflate
COMMIT
- dc76454a39e7e83b68c3704b6e3784654f8d5ac5
+ 9d624d1d8ba82c690d6d6be1d0a961fc5a983ea4
)
register_cmake_command(
diff --git a/cmake/targets/BuildLolHtml.cmake b/cmake/targets/BuildLolHtml.cmake
index aeac571321..934f8d0be9 100644
--- a/cmake/targets/BuildLolHtml.cmake
+++ b/cmake/targets/BuildLolHtml.cmake
@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
cloudflare/lol-html
COMMIT
- 8d4c273ded322193d017042d1f48df2766b0f88b
+ 4f8becea13a0021c8b71abd2dcc5899384973b66
)
set(LOLHTML_CWD ${VENDOR_PATH}/lolhtml/c-api)
diff --git a/cmake/targets/BuildLshpack.cmake b/cmake/targets/BuildLshpack.cmake
index c1cbb12ff5..845f9bf011 100644
--- a/cmake/targets/BuildLshpack.cmake
+++ b/cmake/targets/BuildLshpack.cmake
@@ -4,7 +4,7 @@ register_repository(
REPOSITORY
litespeedtech/ls-hpack
COMMIT
- 3d0f1fc1d6e66a642e7a98c55deb38aa986eb4b0
+ 32e96f10593c7cb8553cd8c9c12721100ae9e924
)
if(WIN32)
diff --git a/cmake/tools/SetupLLVM.cmake b/cmake/tools/SetupLLVM.cmake
index 5e5fd3a953..9db637b60d 100644
--- a/cmake/tools/SetupLLVM.cmake
+++ b/cmake/tools/SetupLLVM.cmake
@@ -4,7 +4,7 @@ if(NOT ENABLE_LLVM)
return()
endif()
-if(CMAKE_HOST_WIN32 OR CMAKE_HOST_APPLE OR ABI STREQUAL "musl")
+if(CMAKE_HOST_WIN32 OR CMAKE_HOST_APPLE OR EXISTS "/etc/alpine-release")
set(DEFAULT_LLVM_VERSION "18.1.8")
else()
set(DEFAULT_LLVM_VERSION "16.0.6")
diff --git a/cmake/tools/SetupWebKit.cmake b/cmake/tools/SetupWebKit.cmake
index dd263335c4..e7cb26be5e 100644
--- a/cmake/tools/SetupWebKit.cmake
+++ b/cmake/tools/SetupWebKit.cmake
@@ -63,7 +63,7 @@ else()
message(FATAL_ERROR "Unsupported architecture: ${CMAKE_SYSTEM_PROCESSOR}")
endif()
-if(ABI STREQUAL "musl")
+if(LINUX AND ABI STREQUAL "musl")
set(WEBKIT_SUFFIX "-musl")
endif()
diff --git a/docs/cli/test.md b/docs/cli/test.md
index 29912ba2f5..e1b37f229b 100644
--- a/docs/cli/test.md
+++ b/docs/cli/test.md
@@ -75,8 +75,10 @@ jobs:
name: build-app
runs-on: ubuntu-latest
steps:
+ - name: Checkout
+ uses: actions/checkout@v4
- name: Install bun
- uses: oven-sh/setup-bun
+ uses: oven-sh/setup-bun@v2
- name: Install dependencies # (assuming your project has dependencies)
run: bun install # You can use npm/yarn/pnpm instead if you prefer
- name: Run tests
diff --git a/docs/upgrading-webkit.md b/docs/contributing/upgrading-webkit.md
similarity index 100%
rename from docs/upgrading-webkit.md
rename to docs/contributing/upgrading-webkit.md
diff --git a/docs/guides/runtime/set-env.md b/docs/guides/runtime/set-env.md
index 92cd5e27ec..c336a2c7a5 100644
--- a/docs/guides/runtime/set-env.md
+++ b/docs/guides/runtime/set-env.md
@@ -16,7 +16,7 @@ Set these variables in a `.env` file.
Bun reads the following files automatically (listed in order of increasing precedence).
- `.env`
-- `.env.production` or `.env.development` (depending on value of `NODE_ENV`)
+- `.env.production`, `.env.development`, `.env.test` (depending on value of `NODE_ENV`)
- `.env.local`
```txt#.env
diff --git a/docs/installation.md b/docs/installation.md
index f52d4d5f5a..f98e3bbfa1 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -73,8 +73,7 @@ There are also image variants for different operating systems.
$ docker pull oven/bun:debian
$ docker pull oven/bun:slim
$ docker pull oven/bun:distroless
-# alpine not recommended until #918 is fixed
-# $ docker pull oven/bun:alpine
+$ docker pull oven/bun:alpine
```
## Checking installation
@@ -190,14 +189,19 @@ For convenience, here are download links for the latest version:
- [`bun-linux-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64.zip)
- [`bun-linux-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-baseline.zip)
+- [`bun-linux-x64-musl.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-musl.zip)
+- [`bun-linux-x64-musl-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64-musl-baseline.zip)
- [`bun-windows-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64.zip)
- [`bun-windows-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64-baseline.zip)
- [`bun-darwin-aarch64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-aarch64.zip)
- [`bun-linux-aarch64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-aarch64.zip)
+- [`bun-linux-aarch64-musl.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-linux-aarch64-musl.zip)
- [`bun-darwin-x64.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-x64.zip)
- [`bun-darwin-x64-baseline.zip`](https://github.com/oven-sh/bun/releases/latest/download/bun-darwin-x64-baseline.zip)
-The `baseline` binaries are built for older CPUs which may not support AVX2 instructions. If you run into an "Illegal Instruction" error when running Bun, try using the `baseline` binaries instead. Bun's install scripts automatically choose the correct binary for your system which helps avoid this issue. Baseline builds are slower than regular builds, so use them only if necessary.
+The `musl` binaries are built for distributions that do not ship with the glibc libraries by default, instead relying on musl. The two most popular distros are Void Linux and Alpine Linux, with the latter is used heavily in Docker containers. If you encounter an error like the following: `bun: /lib/x86_64-linux-gnu/libm.so.6: version GLIBC_2.29' not found (required by bun)`, try using the musl binary. Bun's install script automatically chooses the correct binary for your system.
+
+The `baseline` binaries are built for older CPUs which may not support AVX2 instructions. If you run into an "Illegal Instruction" error when running Bun, try using the `baseline` binaries instead. Bun's install scripts automatically chooses the correct binary for your system which helps avoid this issue. Baseline builds are slower than regular builds, so use them only if necessary.
Hello world!
");
});
it("beep:boop returns 42", () => {
@@ -296,9 +294,8 @@ describe("dynamic import", () => {
it("SSRs `Hello world!
` with Svelte", async () => {
const { default: App }: any = await import("./hello.svelte");
- const { html } = App.render();
-
- expect(html).toBe("Hello world!
");
+ const { body } = svelteRender(App);
+ expect(body).toBe("Hello world!
");
});
it("beep:boop returns 42", async () => {
@@ -327,9 +324,9 @@ import Hello from ${JSON.stringify(resolve(import.meta.dir, "hello2.svelte"))};
export default Hello;
`;
const { default: SvelteApp } = await import("delay:hello2.svelte");
- const { html } = SvelteApp.render();
+ const { body } = svelteRender(SvelteApp);
- expect(html).toBe("Hello world!
");
+ expect(body).toBe("Hello world!
");
});
});
@@ -483,631 +480,3 @@ describe("errors", () => {
expect(text).toBe(result);
});
});
-
-describe("start", () => {
- {
- let state: string = "Should not see this!";
-
- itBundled("works", {
- experimentalCss: true,
- minifyWhitespace: true,
- files: {
- "/entry.css": /* css */ `
- body {
- background: white;
- color: blue; }
- `,
- },
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onStart(() => {
- state = "red";
- });
-
- build.onLoad({ filter: /\.css/ }, async ({ path }) => {
- console.log("[plugin] Path", path);
- return {
- contents: `body { color: ${state} }`,
- loader: "css",
- };
- });
- },
- },
- ],
- outfile: "/out.js",
- onAfterBundle(api) {
- api.expectFile("/out.js").toEqualIgnoringWhitespace(`body{color:${state}}`);
- },
- });
- }
-
- {
- type Action = "onLoad" | "onStart";
- let actions: Action[] = [];
-
- itBundled("executes before everything", {
- experimentalCss: true,
- minifyWhitespace: true,
- files: {
- "/entry.css": /* css */ `
- body {
- background: white;
- color: blue; }
- `,
- },
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onLoad({ filter: /\.css/ }, async ({ path }) => {
- actions.push("onLoad");
- return {
- contents: `body { color: red }`,
- loader: "css",
- };
- });
-
- build.onStart(() => {
- actions.push("onStart");
- });
- },
- },
- ],
- outfile: "/out.js",
- onAfterBundle(api) {
- api.expectFile("/out.js").toEqualIgnoringWhitespace(`body{ color: red }`);
-
- expect(actions).toStrictEqual(["onStart", "onLoad"]);
- },
- });
- }
-
- {
- let action: string[] = [];
- itBundled("executes after all plugins have been setup", {
- experimentalCss: true,
- minifyWhitespace: true,
- files: {
- "/entry.css": /* css */ `
- body {
- background: white;
- color: blue; }
- `,
- },
- plugins: [
- {
- name: "onStart 1",
- setup(build) {
- build.onStart(async () => {
- action.push("onStart 1 setup");
- await Bun.sleep(1000);
- action.push("onStart 1 complete");
- });
- },
- },
- {
- name: "onStart 2",
- setup(build) {
- build.onStart(async () => {
- action.push("onStart 2 setup");
- await Bun.sleep(1000);
- action.push("onStart 2 complete");
- });
- },
- },
- {
- name: "onStart 3",
- setup(build) {
- build.onStart(async () => {
- action.push("onStart 3 setup");
- await Bun.sleep(1000);
- action.push("onStart 3 complete");
- });
- },
- },
- ],
- outfile: "/out.js",
- onAfterBundle(api) {
- expect(action.slice(0, 3)).toStrictEqual(["onStart 1 setup", "onStart 2 setup", "onStart 3 setup"]);
- expect(new Set(action.slice(3))).toStrictEqual(
- new Set(["onStart 1 complete", "onStart 2 complete", "onStart 3 complete"]),
- );
- },
- });
- }
-
- {
- let action: string[] = [];
- test("LMAO", async () => {
- const folder = tempDirWithFiles("plz", {
- "index.ts": "export const foo = {}",
- });
- try {
- const result = await Bun.build({
- entrypoints: [path.join(folder, "index.ts")],
- experimentalCss: true,
- minify: true,
- plugins: [
- {
- name: "onStart 1",
- setup(build) {
- build.onStart(async () => {
- action.push("onStart 1 setup");
- throw new Error("WOOPS");
- // await Bun.sleep(1000);
- });
- },
- },
- {
- name: "onStart 2",
- setup(build) {
- build.onStart(async () => {
- action.push("onStart 2 setup");
- await Bun.sleep(1000);
- action.push("onStart 2 complete");
- });
- },
- },
- {
- name: "onStart 3",
- setup(build) {
- build.onStart(async () => {
- action.push("onStart 3 setup");
- await Bun.sleep(1000);
- action.push("onStart 3 complete");
- });
- },
- },
- ],
- });
- console.log(result);
- } catch (err) {
- expect(err).toBeDefined();
- return;
- }
- throw new Error("DIDNT GET ERRROR!");
- });
- }
-});
-
-describe("defer", () => {
- {
- type Action = {
- type: "load" | "defer";
- path: string;
- };
- let actions: Action[] = [];
- function logLoad(path: string) {
- actions.push({ type: "load", path: path.replaceAll("\\", "/") });
- }
- function logDefer(path: string) {
- actions.push({ type: "defer", path: path.replaceAll("\\", "/") });
- }
-
- itBundled("basic", {
- experimentalCss: true,
- files: {
- "/index.ts": /* ts */ `
-import { lmao } from "./lmao.ts";
-import foo from "./a.css";
-
-console.log("Foo", foo, lmao);
- `,
- "/lmao.ts": `
-import { foo } from "./foo.ts";
-export const lmao = "lolss";
-console.log(foo);
- `,
- "/foo.ts": `
- export const foo = 'lkdfjlsdf';
- console.log('hi')`,
- "/a.css": `
- h1 {
- color: blue;
- }
- `,
- },
- entryPoints: ["index.ts"],
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onLoad({ filter: /\.(ts)/ }, async ({ defer, path }) => {
- // console.log("Running on load plugin", path);
- if (path.includes("index.ts")) {
- logLoad(path);
- return undefined;
- }
- logDefer(path);
- await defer();
- logLoad(path);
- return undefined;
- });
- },
- },
- ],
- outdir: "/out",
- onAfterBundle(api) {
- const expected_actions: Action[] = [
- {
- type: "load",
- path: "index.ts",
- },
- {
- type: "defer",
- path: "lmao.ts",
- },
- {
- type: "load",
- path: "lmao.ts",
- },
- {
- type: "defer",
- path: "foo.ts",
- },
- {
- type: "load",
- path: "foo.ts",
- },
- ];
-
- expect(actions.length).toBe(expected_actions.length);
- for (let i = 0; i < expected_actions.length; i++) {
- const expected = expected_actions[i];
- const action = actions[i];
- const filename = action.path.split("/").pop();
-
- expect(action.type).toEqual(expected.type);
- expect(filename).toEqual(expected.path);
- }
- },
- });
- }
-
- itBundled("edgecase", {
- experimentalCss: true,
- minifyWhitespace: true,
- files: {
- "/entry.css": /* css */ `
- body {
- background: white;
- color: black }
- `,
- },
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onLoad({ filter: /\.css/ }, async ({ path }) => {
- console.log("[plugin] Path", path);
- return {
- contents: 'h1 [this_worked="nice!"] { color: red; }',
- loader: "css",
- };
- });
- },
- },
- ],
- outfile: "/out.js",
- onAfterBundle(api) {
- api.expectFile("/out.js").toContain(`h1 [this_worked=nice\\!]{color:red}
-`);
- },
- });
-
- // encountered double free when CSS build has error
- itBundled("shouldn't crash on CSS parse error", {
- experimentalCss: true,
- files: {
- "/index.ts": /* ts */ `
- import { lmao } from "./lmao.ts";
- import foo from "./a.css";
-
- console.log("Foo", foo, lmao);
- `,
- "/lmao.ts": `
- import { foo } from "./foo.ts";
- export const lmao = "lolss";
- console.log(foo);
- `,
- "/foo.ts": `
- export const foo = "LOL bro";
- console.log("FOOOO", foo);
- `,
- "/a.css": `
- /* helllooo friends */
- `,
- },
- entryPoints: ["index.ts"],
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onLoad({ filter: /\.css/ }, async ({ path }) => {
- console.log("[plugin] CSS path", path);
- return {
- // this fails, because it causes a Build error I think?
- contents: `hello friends!`,
- loader: "css",
- };
- });
-
- build.onLoad({ filter: /\.(ts)/ }, async ({ defer, path }) => {
- // console.log("Running on load plugin", path);
- if (path.includes("index.ts")) {
- console.log("[plugin] Path", path);
- return undefined;
- }
- await defer();
- return undefined;
- });
- },
- },
- ],
- outdir: "/out",
- bundleErrors: {
- "/a.css": ["Unexpected end of input"],
- },
- });
-
- itBundled("works as expected when onLoad error occurs after defer", {
- experimentalCss: true,
- files: {
- "/index.ts": /* ts */ `
- import { lmao } from "./lmao.ts";
- import foo from "./a.css";
-
- console.log("Foo", foo, lmao);
- `,
- "/lmao.ts": `
- import { foo } from "./foo.ts";
- export const lmao = "lolss";
- console.log(foo);
- `,
- "/foo.ts": `
- export const foo = "LOL bro";
- console.log("FOOOO", foo);
- `,
- "/a.css": `
- /* helllooo friends */
- `,
- },
- entryPoints: ["index.ts"],
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onLoad({ filter: /\.css/ }, async ({ path }) => {
- return {
- // this fails, because it causes a Build error I think?
- contents: `hello friends`,
- loader: "css",
- };
- });
-
- build.onLoad({ filter: /\.(ts)/ }, async ({ defer, path }) => {
- if (path.includes("index.ts")) {
- return undefined;
- }
- await defer();
- throw new Error("woopsie");
- });
- },
- },
- ],
- outdir: "/out",
- bundleErrors: {
- "/a.css": ["Unexpected end of input"],
- "/lmao.ts": ["woopsie"],
- },
- });
-
- itBundled("calling defer more than once errors", {
- experimentalCss: true,
- files: {
- "/index.ts": /* ts */ `
- import { lmao } from "./lmao.ts";
- import foo from "./a.css";
-
- console.log("Foo", foo, lmao);
- `,
- "/lmao.ts": `
- import { foo } from "./foo.ts";
- export const lmao = "lolss";
- console.log(foo);
- `,
- "/foo.ts": `
- export const foo = "LOL bro";
- console.log("FOOOO", foo);
- `,
- "/a.css": `
- /* helllooo friends */
- `,
- },
- entryPoints: ["index.ts"],
- plugins: [
- {
- name: "demo",
- setup(build) {
- build.onLoad({ filter: /\.css/ }, async ({ path }) => {
- return {
- // this fails, because it causes a Build error I think?
- contents: `hello friends`,
- loader: "css",
- };
- });
-
- build.onLoad({ filter: /\.(ts)/ }, async ({ defer, path }) => {
- if (path.includes("index.ts")) {
- return undefined;
- }
- await defer();
- await defer();
- });
- },
- },
- ],
- outdir: "/out",
- bundleErrors: {
- "/a.css": ["Unexpected end of input"],
- "/lmao.ts": ["can't call .defer() more than once within an onLoad plugin"],
- },
- });
-
- test("integration", async () => {
- const folder = tempDirWithFiles("integration", {
- "module_data.json": "{}",
- "package.json": `{
- "name": "integration-test",
- "version": "1.0.0",
- "private": true,
- "type": "module",
- "dependencies": {
- }
- }`,
- "src/index.ts": `
-import { greet } from "./utils/greetings";
-import { formatDate } from "./utils/dates";
-import { calculateTotal } from "./math/calculations";
-import { logger } from "./services/logger";
-import moduleData from "../module_data.json";
-import path from "path";
-
-
-await Bun.write(path.join(import.meta.dirname, 'output.json'), JSON.stringify(moduleData))
-
-function main() {
- const today = new Date();
- logger.info("Application started");
-
- const total = calculateTotal([10, 20, 30, 40]);
- console.log(greet("World"));
- console.log(\`Today is \${formatDate(today)}\`);
- console.log(\`Total: \${total}\`);
-}
-`,
- "src/utils/greetings.ts": `
-export function greet(name: string): string {
- return \`Hello \${name}!\`;
-}
-`,
- "src/utils/dates.ts": `
-export function formatDate(date: Date): string {
- return date.toLocaleDateString("en-US", {
- weekday: "long",
- year: "numeric",
- month: "long",
- day: "numeric"
- });
-}
-`,
- "src/math/calculations.ts": `
-export function calculateTotal(numbers: number[]): number {
- return numbers.reduce((sum, num) => sum + num, 0);
-}
-
-export function multiply(a: number, b: number): number {
- return a * b;
-}
-`,
- "src/services/logger.ts": `
-export const logger = {
- info: (msg: string) => console.log(\`[INFO] \${msg}\`),
- error: (msg: string) => console.error(\`[ERROR] \${msg}\`),
- warn: (msg: string) => console.warn(\`[WARN] \${msg}\`)
-};
-`,
- });
-
- const entrypoint = path.join(folder, "src", "index.ts");
- await Bun.$`${bunExe()} install`.env(bunEnv).cwd(folder);
-
- const outdir = path.join(folder, "dist");
-
- const result = await Bun.build({
- entrypoints: [entrypoint],
- outdir,
- plugins: [
- {
- name: "xXx123_import_checker_321xXx",
- setup(build) {
- type Import = {
- imported: string[];
- dep: string;
- };
- type Export = {
- ident: string;
- };
- let imports_and_exports: Record; exports: Array }> = {};
-
- build.onLoad({ filter: /\.ts/ }, async ({ path }) => {
- const contents = await Bun.$`cat ${path}`.quiet().text();
-
- const import_regex = /import\s+(?:([\s\S]*?)\s+from\s+)?['"]([^'"]+)['"];/g;
- const imports: Array = [...contents.toString().matchAll(import_regex)].map(m => ({
- imported: m
- .slice(1, m.length - 1)
- .map(match => (match[0] === "{" ? match.slice(2, match.length - 2) : match)),
- dep: m[m.length - 1],
- }));
-
- const export_regex =
- /export\s+(?:default\s+|const\s+|let\s+|var\s+|function\s+|class\s+|enum\s+|type\s+|interface\s+)?([\w$]+)?(?:\s*=\s*|(?:\s*{[^}]*})?)?[^;]*;/g;
- const exports: Array = [...contents.matchAll(export_regex)].map(m => ({
- ident: m[1],
- }));
-
- imports_and_exports[path.replaceAll("\\", "/").split("/").pop()!] = { imports, exports };
- return undefined;
- });
-
- build.onLoad({ filter: /module_data\.json/ }, async ({ defer }) => {
- await defer();
- const contents = JSON.stringify(imports_and_exports);
-
- return {
- contents,
- loader: "json",
- };
- });
- },
- },
- ],
- });
-
- expect(result.success).toBeTrue();
- await Bun.$`${bunExe()} run ${result.outputs[0].path}`;
- const output = await Bun.$`cat ${path.join(folder, "dist", "output.json")}`.json();
- expect(output).toStrictEqual({
- "index.ts": {
- "imports": [
- { "imported": ["greet"], "dep": "./utils/greetings" },
- { "imported": ["formatDate"], "dep": "./utils/dates" },
- { "imported": ["calculateTotal"], "dep": "./math/calculations" },
- { "imported": ["logger"], "dep": "./services/logger" },
- { "imported": ["moduleData"], "dep": "../module_data.json" },
- { "imported": ["path"], "dep": "path" },
- ],
- "exports": [],
- },
- "greetings.ts": {
- "imports": [],
- "exports": [{ "ident": "greet" }],
- },
- "dates.ts": {
- "imports": [],
- "exports": [{ "ident": "formatDate" }],
- },
- "calculations.ts": {
- "imports": [],
- "exports": [{ "ident": "calculateTotal" }, { "ident": "multiply" }],
- },
- "logger.ts": {
- "imports": [],
- "exports": [{ "ident": "logger" }],
- },
- });
- });
-});
diff --git a/test/js/bun/util/filesystem_router.test.ts b/test/js/bun/util/filesystem_router.test.ts
index e297a57be6..96a503112b 100644
--- a/test/js/bun/util/filesystem_router.test.ts
+++ b/test/js/bun/util/filesystem_router.test.ts
@@ -344,6 +344,31 @@ it("reload() works", () => {
expect(router.match("/posts")!.name).toBe("/posts");
});
+it("reload() works with new dirs/files", () => {
+ const { dir } = make(["posts.tsx"]);
+
+ const router = new Bun.FileSystemRouter({
+ dir,
+ style: "nextjs",
+ assetPrefix: "/_next/static/",
+ origin: "https://nextjs.org",
+ });
+
+ expect(router.match("/posts")!.name).toBe("/posts");
+ createTree(dir, ['test/recursive/index.ts']);
+ router.reload();
+ expect(router.match("/test/recursive")!.name).toBe("/test/recursive");
+ rmSync(`${dir}/test/recursive`, {
+ recursive: true,
+ force: true
+ });
+ router.reload();
+ expect(router.match("/test/recursive")).toBe(null);
+ createTree(dir, ['test/test2/index.ts']);
+ router.reload();
+ expect(router.match("/test/test2")!.name).toBe("/test/test2");
+})
+
it(".query works with dynamic routes, including params", () => {
// set up the test
const { dir } = make(["posts/[id].tsx"]);
diff --git a/test/js/bun/util/inspect.test.js b/test/js/bun/util/inspect.test.js
index 301d267426..6ee2d89b6a 100644
--- a/test/js/bun/util/inspect.test.js
+++ b/test/js/bun/util/inspect.test.js
@@ -525,13 +525,39 @@ it("Bun.inspect array with non-indexed properties", () => {
});
describe("console.logging function displays async and generator names", async () => {
- const cases = [function a() {}, async function b() {}, function* c() {}, async function* d() {}];
+ const cases = [
+ function () {},
+ function a() {},
+ async function b() {},
+ function* c() {},
+ async function* d() {},
+ async function* () {},
+ ];
const expected_logs = [
+ "[Function]",
"[Function: a]",
"[AsyncFunction: b]",
"[GeneratorFunction: c]",
"[AsyncGeneratorFunction: d]",
+ "[AsyncGeneratorFunction]",
+ ];
+
+ for (let i = 0; i < cases.length; i++) {
+ it(expected_logs[i], () => {
+ expect(Bun.inspect(cases[i])).toBe(expected_logs[i]);
+ });
+ }
+});
+describe("console.logging class displays names and extends", async () => {
+ class A {}
+ const cases = [A, class B extends A {}, class extends A {}, class {}];
+
+ const expected_logs = [
+ "[class A]",
+ "[class B extends A]",
+ "[class (anonymous) extends A]",
+ "[class (anonymous)]",
];
for (let i = 0; i < cases.length; i++) {
@@ -562,3 +588,14 @@ it("console.log on a Blob shows name", () => {
`File (3 bytes) {\n name: "",\n type: "text/plain;charset=utf-8",\n lastModified: ${file.lastModified}\n}`,
);
});
+
+it("console.log on a arguments shows list", () => {
+ function fn() {
+ expect(Bun.inspect(arguments)).toBe(`[ 1, [ 1 ], [Function: fn] ]`);
+ }
+ fn(1, [1], fn);
+});
+
+it("console.log on null prototype", () => {
+ expect(Bun.inspect(Object.create(null))).toBe("[Object: null prototype] {}");
+});
diff --git a/test/js/bun/websocket/websocket-server.test.ts b/test/js/bun/websocket/websocket-server.test.ts
index 6bcb231747..23022030c2 100644
--- a/test/js/bun/websocket/websocket-server.test.ts
+++ b/test/js/bun/websocket/websocket-server.test.ts
@@ -825,3 +825,13 @@ async function connect(server: Server): Promise {
clients.push(client);
await promise;
}
+
+it("you can call server.subscriberCount() when its not a websocket server", async () => {
+ using server = serve({
+ port: 0,
+ fetch(request, server) {
+ return new Response();
+ },
+ });
+ expect(server.subscriberCount("boop")).toBe(0);
+});
diff --git a/test/js/node/buffer.test.js b/test/js/node/buffer.test.js
index f5622d093c..645d29ac9e 100644
--- a/test/js/node/buffer.test.js
+++ b/test/js/node/buffer.test.js
@@ -633,6 +633,37 @@ for (let withOverridenBufferWrite of [false, true]) {
expect(dot.toString("base64url")).toBe("__4uAA");
});
+ describe("writing with offset undefined", () => {
+ [
+ ["writeUInt8", "readUInt8", 8, 1],
+ ["writeInt8", "readInt8", 8, 1],
+ ["writeUInt16LE", "readUInt16LE", 8, 2],
+ ["writeInt16LE", "readInt16LE", 8, 2],
+ ["writeUInt16BE", "readUInt16BE", 8, 2],
+ ["writeInt16BE", "readInt16BE", 8, 2],
+ ["writeUInt32LE", "readUInt32LE", 8, 4],
+ ["writeInt32LE", "readInt32LE", 8, 4],
+ ["writeUInt32BE", "readUInt32BE", 8, 4],
+ ["writeInt32BE", "readInt32BE", 8, 4],
+ ["writeFloatLE", "readFloatLE", 8, 4],
+ ["writeFloatBE", "readFloatBE", 8, 4],
+ ["writeDoubleLE", "readDoubleLE", 8, 8],
+ ["writeDoubleBE", "readDoubleBE", 8, 8],
+ ].forEach(([method, read, value, size]) => {
+ it(`${method} (implicit offset)`, () => {
+ const b = Buffer.alloc(10, 42);
+ expect(b[method](value)).toBe(size);
+ expect(b[read]()).toBe(value);
+ });
+
+ it(`${method} (explicit offset)`, () => {
+ const b = Buffer.alloc(10, 42);
+ expect(b[method](value, 0)).toBe(size);
+ expect(b[read]()).toBe(value);
+ });
+ });
+ });
+
// https://github.com/joyent/node/issues/402
it("writing base64 at a position > 0 should not mangle the result", () => {
const segments = ["TWFkbmVzcz8h", "IFRoaXM=", "IGlz", "IG5vZGUuanMh"];
diff --git a/test/js/node/child_process/child_process.test.ts b/test/js/node/child_process/child_process.test.ts
index 11bd16de1d..f70772d421 100644
--- a/test/js/node/child_process/child_process.test.ts
+++ b/test/js/node/child_process/child_process.test.ts
@@ -454,3 +454,13 @@ it.if(!isWindows)("spawnSync correctly reports signal codes", () => {
expect(signal).toBe("SIGTRAP");
});
+
+it("spawnSync(does-not-exist)", () => {
+ const x = spawnSync("does-not-exist");
+ expect(x.error?.code).toEqual("ENOENT");
+ expect(x.error.path).toEqual("does-not-exist");
+ expect(x.signal).toEqual(null);
+ expect(x.output).toEqual([null, null, null]);
+ expect(x.stdout).toEqual(null);
+ expect(x.stderr).toEqual(null);
+});
diff --git a/test/js/node/cluster/common.ts b/test/js/node/cluster/common.ts
deleted file mode 100644
index b99b402c49..0000000000
--- a/test/js/node/cluster/common.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import assert from "node:assert";
-import fs from "node:fs";
-import os from "node:os";
-import path from "node:path";
-import process from "node:process";
-import util from "node:util";
-
-export const isWindows = process.platform === "win32";
-
-export function tmpdirSync(pattern: string = "bun.test.") {
- return fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), pattern));
-}
-
-export function isAlive(pid) {
- try {
- process.kill(pid, "SIGCONT");
- return true;
- } catch {
- return false;
- }
-}
-
-export function mustNotCall(msg?) {
- return function mustNotCall(...args) {
- const argsInfo = args.length > 0 ? `\ncalled with arguments: ${args.map(arg => util.inspect(arg)).join(", ")}` : "";
- assert.fail(`${msg || "function should not have been called"} ` + argsInfo);
- };
-}
-
-export function patchEmitter(emitter: any, prefix: string) {
- var oldEmit = emitter.emit;
-
- emitter.emit = function () {
- console.log([prefix, arguments[0]]);
- oldEmit.apply(emitter, arguments);
- };
-}
diff --git a/test/js/node/cluster/test-worker-no-exit-http.ts b/test/js/node/cluster/test-worker-no-exit-http.ts
index 661c439861..93156225b9 100644
--- a/test/js/node/cluster/test-worker-no-exit-http.ts
+++ b/test/js/node/cluster/test-worker-no-exit-http.ts
@@ -1,7 +1,15 @@
const assert = require("assert");
const cluster = require("cluster");
const http = require("http");
-import { patchEmitter } from "./common";
+
+function patchEmitter(emitter: any, prefix: string) {
+ var oldEmit = emitter.emit;
+
+ emitter.emit = function () {
+ console.log([prefix, arguments[0]]);
+ oldEmit.apply(emitter, arguments);
+ };
+}
let destroyed;
let success;
diff --git a/test/js/node/cluster/upstream/common/countdown.js b/test/js/node/cluster/upstream/common/countdown.js
deleted file mode 100644
index 9853c9fa47..0000000000
--- a/test/js/node/cluster/upstream/common/countdown.js
+++ /dev/null
@@ -1,27 +0,0 @@
-"use strict";
-
-const assert = require("assert");
-const kLimit = Symbol("limit");
-const kCallback = Symbol("callback");
-const common = require("./");
-
-class Countdown {
- constructor(limit, cb) {
- assert.strictEqual(typeof limit, "number");
- assert.strictEqual(typeof cb, "function");
- this[kLimit] = limit;
- this[kCallback] = common.mustCall(cb);
- }
-
- dec() {
- assert(this[kLimit] > 0, "Countdown expired");
- if (--this[kLimit] === 0) this[kCallback]();
- return this[kLimit];
- }
-
- get remaining() {
- return this[kLimit];
- }
-}
-
-module.exports = Countdown;
diff --git a/test/js/node/cluster/upstream/common/index.js b/test/js/node/cluster/upstream/common/index.js
deleted file mode 100644
index 46df521726..0000000000
--- a/test/js/node/cluster/upstream/common/index.js
+++ /dev/null
@@ -1,248 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// /* eslint-disable node-core/crypto-check */
-"use strict";
-const process = global.process; // Some tests tamper with the process global.
-
-const assert = require("assert");
-const { exec, execSync, spawn, spawnSync } = require("child_process");
-const fs = require("fs");
-const net = require("net");
-// Do not require 'os' until needed so that test-os-checked-function can
-// monkey patch it. If 'os' is required here, that test will fail.
-const path = require("path");
-const { inspect } = require("util");
-const { isMainThread } = require("worker_threads");
-
-// Some tests assume a umask of 0o022 so set that up front. Tests that need a
-// different umask will set it themselves.
-//
-// Workers can read, but not set the umask, so check that this is the main
-// thread.
-if (isMainThread) process.umask(0o022);
-
-const noop = () => {};
-
-const isWindows = process.platform === "win32";
-const isSunOS = process.platform === "sunos";
-const isFreeBSD = process.platform === "freebsd";
-const isOpenBSD = process.platform === "openbsd";
-const isLinux = process.platform === "linux";
-const isOSX = process.platform === "darwin";
-const isPi = (() => {
- try {
- // Normal Raspberry Pi detection is to find the `Raspberry Pi` string in
- // the contents of `/sys/firmware/devicetree/base/model` but that doesn't
- // work inside a container. Match the chipset model number instead.
- const cpuinfo = fs.readFileSync("/proc/cpuinfo", { encoding: "utf8" });
- const ok = /^Hardware\s*:\s*(.*)$/im.exec(cpuinfo)?.[1] === "BCM2835";
- /^/.test(""); // Clear RegExp.$_, some tests expect it to be empty.
- return ok;
- } catch {
- return false;
- }
-})();
-
-const isDumbTerminal = process.env.TERM === "dumb";
-
-const mustCallChecks = [];
-
-function runCallChecks(exitCode) {
- if (exitCode !== 0) return;
-
- const failed = mustCallChecks.filter(function (context) {
- if ("minimum" in context) {
- context.messageSegment = `at least ${context.minimum}`;
- return context.actual < context.minimum;
- }
- context.messageSegment = `exactly ${context.exact}`;
- return context.actual !== context.exact;
- });
-
- failed.forEach(function (context) {
- console.log(
- "Mismatched %s function calls. Expected %s, actual %d.",
- context.name,
- context.messageSegment,
- context.actual,
- );
- console.log(context.stack.split("\n").slice(2).join("\n"));
- });
-
- if (failed.length) process.exit(1);
-}
-
-function mustCall(fn, exact) {
- return _mustCallInner(fn, exact, "exact");
-}
-
-function mustSucceed(fn, exact) {
- return mustCall(function (err, ...args) {
- assert.ifError(err);
- if (typeof fn === "function") return fn.apply(this, args);
- }, exact);
-}
-
-function _mustCallInner(fn, criteria = 1, field) {
- if (process._exiting) throw new Error("Cannot use common.mustCall*() in process exit handler");
- if (typeof fn === "number") {
- criteria = fn;
- fn = noop;
- } else if (fn === undefined) {
- fn = noop;
- }
-
- if (typeof criteria !== "number") throw new TypeError(`Invalid ${field} value: ${criteria}`);
-
- const context = {
- [field]: criteria,
- actual: 0,
- stack: inspect(new Error()),
- name: fn.name || "",
- };
-
- // Add the exit listener only once to avoid listener leak warnings
- if (mustCallChecks.length === 0) process.on("exit", runCallChecks);
-
- mustCallChecks.push(context);
-
- const _return = function () {
- // eslint-disable-line func-style
- context.actual++;
- return fn.apply(this, arguments);
- };
- // Function instances have own properties that may be relevant.
- // Let's replicate those properties to the returned function.
- // Refs: https://tc39.es/ecma262/#sec-function-instances
- Object.defineProperties(_return, {
- name: {
- value: fn.name,
- writable: false,
- enumerable: false,
- configurable: true,
- },
- length: {
- value: fn.length,
- writable: false,
- enumerable: false,
- configurable: true,
- },
- });
- return _return;
-}
-
-function getCallSite(top) {
- const originalStackFormatter = Error.prepareStackTrace;
- Error.prepareStackTrace = (err, stack) => `${stack[0].getFileName()}:${stack[0].getLineNumber()}`;
- const err = new Error();
- Error.captureStackTrace(err, top);
- // With the V8 Error API, the stack is not formatted until it is accessed
- err.stack; // eslint-disable-line no-unused-expressions
- Error.prepareStackTrace = originalStackFormatter;
- return err.stack;
-}
-
-function mustNotCall(msg) {
- const callSite = getCallSite(mustNotCall);
- return function mustNotCall(...args) {
- const argsInfo = args.length > 0 ? `\ncalled with arguments: ${args.map(arg => inspect(arg)).join(", ")}` : "";
- assert.fail(`${msg || "function should not have been called"} at ${callSite}` + argsInfo);
- };
-}
-
-function printSkipMessage(msg) {
- console.log(`1..0 # Skipped: ${msg}`);
-}
-
-function skip(msg) {
- printSkipMessage(msg);
- process.exit(0);
-}
-
-function isAlive(pid) {
- try {
- process.kill(pid, "SIGCONT");
- return true;
- } catch {
- return false;
- }
-}
-
-function skipIf32Bits() {
- if (bits < 64) {
- skip("The tested feature is not available in 32bit builds");
- }
-}
-
-function skipIfWorker() {
- if (!isMainThread) {
- skip("This test only works on a main thread");
- }
-}
-
-function skipIfDumbTerminal() {
- if (isDumbTerminal) {
- skip("skipping - dumb terminal");
- }
-}
-
-const common = {
- isAlive,
- isDumbTerminal,
- isFreeBSD,
- isLinux,
- isMainThread,
- isOpenBSD,
- isOSX,
- isPi,
- isSunOS,
- isWindows,
- mustCall,
- mustNotCall,
- mustSucceed,
- printSkipMessage,
- skip,
- skipIf32Bits,
- skipIfDumbTerminal,
- // On IBMi, process.platform and os.platform() both return 'aix',
- // when built with Python versions earlier than 3.9.
- // It is not enough to differentiate between IBMi and real AIX system.
- get isAIX() {
- return require("os").type() === "AIX";
- },
-
- get isIBMi() {
- return require("os").type() === "OS400";
- },
-
- get isLinuxPPCBE() {
- return process.platform === "linux" && process.arch === "ppc64" && require("os").endianness() === "BE";
- },
-};
-
-const validProperties = new Set(Object.keys(common));
-module.exports = new Proxy(common, {
- get(obj, prop) {
- if (!validProperties.has(prop)) throw new Error(`Using invalid common property: '${prop}'`);
- return obj[prop];
- },
-});
diff --git a/test/js/node/cluster/upstream/common/tmpdir.js b/test/js/node/cluster/upstream/common/tmpdir.js
deleted file mode 100644
index 7de0b113a3..0000000000
--- a/test/js/node/cluster/upstream/common/tmpdir.js
+++ /dev/null
@@ -1,88 +0,0 @@
-"use strict";
-
-const { spawnSync } = require("child_process");
-const fs = require("fs");
-const path = require("path");
-const { pathToFileURL } = require("url");
-const { isMainThread } = require("worker_threads");
-
-function rmSync(pathname, useSpawn) {
- if (useSpawn) {
- const escapedPath = pathname.replaceAll("\\", "\\\\");
- spawnSync(process.execPath, [
- "-e",
- `require("fs").rmSync("${escapedPath}", { maxRetries: 3, recursive: true, force: true });`,
- ]);
- } else {
- fs.rmSync(pathname, { maxRetries: 3, recursive: true, force: true });
- }
-}
-
-const testRoot = process.env.NODE_TEST_DIR ? fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, "..");
-
-// Using a `.` prefixed name, which is the convention for "hidden" on POSIX,
-// gets tools to ignore it by default or by simple rules, especially eslint.
-const tmpdirName = ".tmp." + (process.env.TEST_SERIAL_ID || process.env.TEST_THREAD_ID || "0");
-const tmpPath = path.join(testRoot, tmpdirName);
-
-let firstRefresh = true;
-function refresh(useSpawn = false) {
- rmSync(tmpPath, useSpawn);
- fs.mkdirSync(tmpPath);
-
- if (firstRefresh) {
- firstRefresh = false;
- // Clean only when a test uses refresh. This allows for child processes to
- // use the tmpdir and only the parent will clean on exit.
- process.on("exit", () => {
- return onexit(useSpawn);
- });
- }
-}
-
-function onexit(useSpawn) {
- // Change directory to avoid possible EBUSY
- if (isMainThread) process.chdir(testRoot);
-
- try {
- rmSync(tmpPath, useSpawn);
- } catch (e) {
- console.error("Can't clean tmpdir:", tmpPath);
-
- const files = fs.readdirSync(tmpPath);
- console.error("Files blocking:", files);
-
- if (files.some(f => f.startsWith(".nfs"))) {
- // Warn about NFS "silly rename"
- console.error('Note: ".nfs*" might be files that were open and ' + "unlinked but not closed.");
- console.error("See http://nfs.sourceforge.net/#faq_d2 for details.");
- }
-
- console.error();
- throw e;
- }
-}
-
-function resolve(...paths) {
- return path.resolve(tmpPath, ...paths);
-}
-
-function hasEnoughSpace(size) {
- const { bavail, bsize } = fs.statfsSync(tmpPath);
- return bavail >= Math.ceil(size / bsize);
-}
-
-function fileURL(...paths) {
- // When called without arguments, add explicit trailing slash
- const fullPath = path.resolve(tmpPath + path.sep, ...paths);
-
- return pathToFileURL(fullPath);
-}
-
-module.exports = {
- fileURL,
- hasEnoughSpace,
- path: tmpPath,
- refresh,
- resolve,
-};
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-advanced-serialization.js b/test/js/node/cluster/upstream/parallel/test-cluster-advanced-serialization.js
deleted file mode 100644
index 8a368d44c7..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-advanced-serialization.js
+++ /dev/null
@@ -1,28 +0,0 @@
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- cluster.settings.serialization = "advanced";
- const worker = cluster.fork();
- const circular = {};
- circular.circular = circular;
-
- worker.on(
- "online",
- common.mustCall(() => {
- worker.send(circular);
-
- worker.on(
- "message",
- common.mustCall(msg => {
- assert.deepStrictEqual(msg, circular);
- worker.kill();
- }),
- );
- }),
- );
-} else {
- process.on("message", msg => process.send(msg));
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-bind-privileged-port.js b/test/js/node/cluster/upstream/parallel/test-cluster-bind-privileged-port.js
deleted file mode 100644
index f3a788984b..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-bind-privileged-port.js
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-if (common.isLinux) return; // TODO: bun
-const assert = require("assert");
-const cluster = require("cluster");
-const net = require("net");
-const { readFileSync } = require("fs");
-
-if (common.isLinux) {
- try {
- const unprivilegedPortStart = parseInt(readFileSync("/proc/sys/net/ipv4/ip_unprivileged_port_start"));
- if (unprivilegedPortStart <= 42) {
- common.skip("Port 42 is unprivileged");
- }
- } catch {
- // Do nothing, feature doesn't exist, minimum is 1024 so 42 is usable.
- // Continue...
- }
-}
-
-// Skip on OS X Mojave. https://github.com/nodejs/node/issues/21679
-if (common.isOSX) common.skip("macOS may allow ordinary processes to use any port");
-
-if (common.isIBMi) common.skip("IBMi may allow ordinary processes to use any port");
-
-if (common.isWindows) common.skip("not reliable on Windows.");
-
-if (process.getuid() === 0) common.skip("Test is not supposed to be run as root.");
-
-if (cluster.isPrimary) {
- cluster.fork().on(
- "exit",
- common.mustCall(exitCode => {
- assert.strictEqual(exitCode, 0);
- }),
- );
-} else {
- const s = net.createServer(common.mustNotCall());
- s.listen(42, common.mustNotCall("listen should have failed"));
- s.on(
- "error",
- common.mustCall(err => {
- assert.strictEqual(err.code, "EACCES");
- process.disconnect();
- }),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-call-and-destroy.js b/test/js/node/cluster/upstream/parallel/test-cluster-call-and-destroy.js
deleted file mode 100644
index 6d9ff44e67..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-call-and-destroy.js
+++ /dev/null
@@ -1,18 +0,0 @@
-"use strict";
-const common = require("../common");
-const cluster = require("cluster");
-const assert = require("assert");
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
- worker.on(
- "disconnect",
- common.mustCall(() => {
- assert.strictEqual(worker.isConnected(), false);
- worker.destroy();
- }),
- );
-} else {
- assert.strictEqual(cluster.worker.isConnected(), true);
- cluster.worker.disconnect();
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-child-index-dgram.js b/test/js/node/cluster/upstream/parallel/test-cluster-child-index-dgram.js
deleted file mode 100644
index 426c8de9f4..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-child-index-dgram.js
+++ /dev/null
@@ -1,43 +0,0 @@
-"use strict";
-const common = require("../common");
-const Countdown = require("../common/countdown");
-if (common.isWindows) common.skip("dgram clustering is currently not supported on Windows.");
-
-const cluster = require("cluster");
-const dgram = require("dgram");
-
-// Test an edge case when using `cluster` and `dgram.Socket.bind()`
-// the port of `0`.
-const kPort = 0;
-
-function child() {
- const kTime = 2;
- const countdown = new Countdown(kTime * 2, () => {
- process.exit(0);
- });
- for (let i = 0; i < kTime; i += 1) {
- const socket = new dgram.Socket("udp4");
- socket.bind(
- kPort,
- common.mustCall(() => {
- // `process.nextTick()` or `socket2.close()` would throw
- // ERR_SOCKET_DGRAM_NOT_RUNNING
- process.nextTick(() => {
- socket.close(countdown.dec());
- const socket2 = new dgram.Socket("udp4");
- socket2.bind(
- kPort,
- common.mustCall(() => {
- process.nextTick(() => {
- socket2.close(countdown.dec());
- });
- }),
- );
- });
- }),
- );
- }
-}
-
-if (cluster.isMaster) cluster.fork(__filename);
-else child();
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-child-index-net.js b/test/js/node/cluster/upstream/parallel/test-cluster-child-index-net.js
deleted file mode 100644
index 961924a2d6..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-child-index-net.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-const common = require("../common");
-const Countdown = require("../common/countdown");
-const cluster = require("cluster");
-const net = require("net");
-
-// Test an edge case when using `cluster` and `net.Server.listen()` to
-// the port of `0`.
-const kPort = 0;
-
-function child() {
- const kTime = 2;
- const countdown = new Countdown(kTime * 2, () => {
- process.exit(0);
- });
- for (let i = 0; i < kTime; i += 1) {
- const server = net.createServer();
- server.listen(
- kPort,
- common.mustCall(() => {
- server.close(countdown.dec());
- const server2 = net.createServer();
- server2.listen(
- kPort,
- common.mustCall(() => {
- server2.close(countdown.dec());
- }),
- );
- }),
- );
- }
-}
-
-if (cluster.isMaster) cluster.fork(__filename);
-else child();
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-concurrent-disconnect.js b/test/js/node/cluster/upstream/parallel/test-cluster-concurrent-disconnect.js
deleted file mode 100644
index 1e1daa9ef4..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-concurrent-disconnect.js
+++ /dev/null
@@ -1,58 +0,0 @@
-"use strict";
-
-// Ref: https://github.com/nodejs/node/issues/32106
-
-const common = require("../common");
-if (common.isLinux) return; // TODO: bun
-if (common.isWindows) return; // TODO: bun
-
-const assert = require("assert");
-const cluster = require("cluster");
-const os = require("os");
-
-if (cluster.isPrimary) {
- const workers = [];
- const numCPUs = os.availableParallelism();
- let waitOnline = numCPUs;
- for (let i = 0; i < numCPUs; i++) {
- const worker = cluster.fork();
- workers[i] = worker;
- worker.once(
- "online",
- common.mustCall(() => {
- if (--waitOnline === 0)
- for (const worker of workers) if (worker.isConnected()) worker.send(i % 2 ? "disconnect" : "destroy");
- }),
- );
-
- // These errors can occur due to the nature of the test, we might be trying
- // to send messages when the worker is disconnecting.
- worker.on("error", err => {
- assert.strictEqual(err.syscall, "write");
- if (common.isOSX) {
- assert(["EPIPE", "ENOTCONN"].includes(err.code), err);
- } else {
- assert(["EPIPE", "ECONNRESET"].includes(err.code), err);
- }
- });
-
- worker.once(
- "disconnect",
- common.mustCall(() => {
- for (const worker of workers) if (worker.isConnected()) worker.send("disconnect");
- }),
- );
-
- worker.once(
- "exit",
- common.mustCall((code, signal) => {
- assert.strictEqual(code, 0);
- assert.strictEqual(signal, null);
- }),
- );
- }
-} else {
- process.on("message", msg => {
- if (cluster.worker.isConnected()) cluster.worker[msg]();
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-cwd.js b/test/js/node/cluster/upstream/parallel/test-cluster-cwd.js
deleted file mode 100644
index d28bfdf545..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-cwd.js
+++ /dev/null
@@ -1,29 +0,0 @@
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-const tmpdir = require("../common/tmpdir");
-
-if (cluster.isPrimary) {
- tmpdir.refresh();
-
- assert.strictEqual(cluster.settings.cwd, undefined);
- cluster.fork().on(
- "message",
- common.mustCall(msg => {
- assert.strictEqual(msg, process.cwd());
- }),
- );
-
- cluster.setupPrimary({ cwd: tmpdir.path });
- assert.strictEqual(cluster.settings.cwd, tmpdir.path);
- cluster.fork().on(
- "message",
- common.mustCall(msg => {
- assert.strictEqual(msg, tmpdir.path);
- }),
- );
-} else {
- process.send(process.cwd());
- process.disconnect();
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-disconnect-exitedAfterDisconnect-race.js b/test/js/node/cluster/upstream/parallel/test-cluster-disconnect-exitedAfterDisconnect-race.js
deleted file mode 100644
index f461734eb6..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-disconnect-exitedAfterDisconnect-race.js
+++ /dev/null
@@ -1,33 +0,0 @@
-"use strict";
-
-const common = require("../common");
-
-// Test should fail in Node.js 5.4.1 and pass in later versions.
-
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- cluster.on("exit", (worker, code) => {
- assert.strictEqual(code, 0, `worker exited with code: ${code}, expected 0`);
- });
-
- return cluster.fork();
-}
-
-let eventFired = false;
-
-cluster.worker.disconnect();
-
-process.nextTick(
- common.mustCall(() => {
- assert.ok(!eventFired, "disconnect event should wait for ack");
- }),
-);
-
-cluster.worker.on(
- "disconnect",
- common.mustCall(() => {
- eventFired = true;
- }),
-);
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-disconnect-leak.js b/test/js/node/cluster/upstream/parallel/test-cluster-disconnect-leak.js
deleted file mode 100644
index d1b4812004..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-disconnect-leak.js
+++ /dev/null
@@ -1,27 +0,0 @@
-"use strict";
-
-// Test fails in Node v5.4.0 and passes in v5.4.1 and newer.
-
-const common = require("../common");
-const net = require("net");
-const cluster = require("cluster");
-
-cluster.schedulingPolicy = cluster.SCHED_NONE;
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
-
- // This is the important part of the test: Confirm that `disconnect` fires.
- worker.on("disconnect", common.mustCall());
-
- // These are just some extra stuff we're checking for good measure...
- worker.on("exit", common.mustCall());
- cluster.on("exit", common.mustCall());
-
- cluster.disconnect();
- return;
-}
-
-const server = net.createServer();
-
-server.listen(0);
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-fork-env.js b/test/js/node/cluster/upstream/parallel/test-cluster-fork-env.js
deleted file mode 100644
index 8bf9ef15d7..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-fork-env.js
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-require("../common");
-
-// This test checks that arguments provided to cluster.fork() will create
-// new environment variables and override existing environment variables
-// in the created worker process.
-
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isWorker) {
- const result = cluster.worker.send({
- prop: process.env.cluster_test_prop,
- overwrite: process.env.cluster_test_overwrite,
- });
-
- assert.strictEqual(result, true);
-} else if (cluster.isPrimary) {
- const checks = {
- using: false,
- overwrite: false,
- };
-
- // To check that the cluster extend on the process.env we will overwrite a
- // property
- process.env.cluster_test_overwrite = "old";
-
- // Fork worker
- const worker = cluster.fork({
- "cluster_test_prop": "custom",
- "cluster_test_overwrite": "new",
- });
-
- // Checks worker env
- worker.on("message", function (data) {
- checks.using = data.prop === "custom";
- checks.overwrite = data.overwrite === "new";
- process.exit(0);
- });
-
- process.once("exit", function () {
- assert.ok(checks.using, "The worker did not receive the correct env.");
- assert.ok(checks.overwrite, "The custom environment did not overwrite the existing environment.");
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-fork-windowsHide.js b/test/js/node/cluster/upstream/parallel/test-cluster-fork-windowsHide.js
deleted file mode 100644
index 273e8146a7..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-fork-windowsHide.js
+++ /dev/null
@@ -1,76 +0,0 @@
-"use strict";
-const common = require("../common");
-if (common.isWindows) return; // TODO: bun
-const assert = require("assert");
-const child_process = require("child_process");
-const cluster = require("cluster");
-
-if (!process.argv[2]) {
- // It seems Windows only allocate new console window for
- // attaching processes spawned by detached processes. i.e.
- // - If process D is spawned by process C with `detached: true`,
- // and process W is spawned by process D with `detached: false`,
- // W will get a new black console window popped up.
- // - If D is spawned by C with `detached: false` or W is spawned
- // by D with `detached: true`, no console window will pop up for W.
- //
- // So, we have to spawn a detached process first to run the actual test.
- const primary = child_process.spawn(process.argv[0], [process.argv[1], "--cluster"], {
- detached: true,
- stdio: ["ignore", "ignore", "ignore", "ipc"],
- });
-
- const messageHandlers = {
- workerOnline: common.mustCall(),
- mainWindowHandle: common.mustCall(msg => {
- assert.match(msg.value, /0\s*/);
- }),
- workerExit: common.mustCall(msg => {
- assert.strictEqual(msg.code, 0);
- assert.strictEqual(msg.signal, null);
- }),
- };
-
- primary.on("message", msg => {
- const handler = messageHandlers[msg.type];
- assert.ok(handler);
- handler(msg);
- });
-
- primary.on(
- "exit",
- common.mustCall((code, signal) => {
- assert.strictEqual(code, 0);
- assert.strictEqual(signal, null);
- }),
- );
-} else if (cluster.isPrimary) {
- cluster.setupPrimary({
- silent: true,
- windowsHide: true,
- });
-
- const worker = cluster.fork();
- worker.on("exit", (code, signal) => {
- process.send({ type: "workerExit", code: code, signal: signal });
- });
-
- worker.on("online", msg => {
- process.send({ type: "workerOnline" });
-
- let output = "0";
- if (process.platform === "win32") {
- output = child_process.execSync(
- "powershell -NoProfile -c " + `"(Get-Process -Id ${worker.process.pid}).MainWindowHandle"`,
- { windowsHide: true, encoding: "utf8" },
- );
- }
-
- process.send({ type: "mainWindowHandle", value: output });
- worker.send("shutdown");
- });
-} else {
- cluster.worker.on("message", msg => {
- cluster.worker.disconnect();
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-invalid-message.js b/test/js/node/cluster/upstream/parallel/test-cluster-invalid-message.js
deleted file mode 100644
index fdfe1ada62..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-invalid-message.js
+++ /dev/null
@@ -1,28 +0,0 @@
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
-
- worker.on(
- "exit",
- common.mustCall((code, signal) => {
- assert.strictEqual(code, 0);
- assert.strictEqual(signal, null);
- }),
- );
-
- worker.on("online", () => {
- worker.send(
- {
- cmd: "NODE_CLUSTER",
- ack: -1,
- },
- () => {
- worker.disconnect();
- },
- );
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-kill-disconnect.js b/test/js/node/cluster/upstream/parallel/test-cluster-kill-disconnect.js
deleted file mode 100644
index e1c0a313e2..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-kill-disconnect.js
+++ /dev/null
@@ -1,34 +0,0 @@
-"use strict";
-const common = require("../common");
-
-// Check that cluster works perfectly for both `kill` and `disconnect` cases.
-// Also take into account that the `disconnect` event may be received after the
-// `exit` event.
-// https://github.com/nodejs/node/issues/3238
-
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- function forkWorker(action) {
- const worker = cluster.fork({ action });
- worker.on(
- "disconnect",
- common.mustCall(() => {
- assert.strictEqual(worker.exitedAfterDisconnect, true);
- }),
- );
-
- worker.on(
- "exit",
- common.mustCall(() => {
- assert.strictEqual(worker.exitedAfterDisconnect, true);
- }),
- );
- }
-
- forkWorker("disconnect");
- forkWorker("kill");
-} else {
- cluster.worker[process.env.action]();
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-kill-infinite-loop.js b/test/js/node/cluster/upstream/parallel/test-cluster-kill-infinite-loop.js
deleted file mode 100644
index 837b11f2a1..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-kill-infinite-loop.js
+++ /dev/null
@@ -1,27 +0,0 @@
-"use strict";
-const common = require("../common");
-const cluster = require("cluster");
-const assert = require("assert");
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
-
- worker.on(
- "online",
- common.mustCall(() => {
- // Use worker.process.kill() instead of worker.kill() because the latter
- // waits for a graceful disconnect, which will never happen.
- worker.process.kill();
- }),
- );
-
- worker.on(
- "exit",
- common.mustCall((code, signal) => {
- assert.strictEqual(code, null);
- assert.strictEqual(signal, "SIGTERM");
- }),
- );
-} else {
- while (true);
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-listening-port.js b/test/js/node/cluster/upstream/parallel/test-cluster-listening-port.js
deleted file mode 100644
index ecf9398cd7..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-listening-port.js
+++ /dev/null
@@ -1,22 +0,0 @@
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-const net = require("net");
-
-if (cluster.isPrimary) {
- cluster.fork();
- cluster.on(
- "listening",
- common.mustCall(function (worker, address) {
- const port = address.port;
- // Ensure that the port is not 0 or null
- assert(port);
- // Ensure that the port is numerical
- assert.strictEqual(typeof port, "number");
- worker.kill();
- }),
- );
-} else {
- net.createServer(common.mustNotCall()).listen(0);
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-primary-error.js b/test/js/node/cluster/upstream/parallel/test-cluster-primary-error.js
deleted file mode 100644
index 763ae3eab3..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-primary-error.js
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-const totalWorkers = 2;
-
-// Cluster setup
-if (cluster.isWorker) {
- const http = require("http");
- http.Server(() => {}).listen(0, "127.0.0.1");
-} else if (process.argv[2] === "cluster") {
- // Send PID to testcase process
- let forkNum = 0;
- cluster.on(
- "fork",
- common.mustCall(function forkEvent(worker) {
- // Send PID
- process.send({
- cmd: "worker",
- workerPID: worker.process.pid,
- });
-
- // Stop listening when done
- if (++forkNum === totalWorkers) {
- cluster.removeListener("fork", forkEvent);
- }
- }, totalWorkers),
- );
-
- // Throw accidental error when all workers are listening
- let listeningNum = 0;
- cluster.on(
- "listening",
- common.mustCall(function listeningEvent() {
- // When all workers are listening
- if (++listeningNum === totalWorkers) {
- // Stop listening
- cluster.removeListener("listening", listeningEvent);
-
- // Throw accidental error
- process.nextTick(() => {
- throw new Error("accidental error");
- });
- }
- }, totalWorkers),
- );
-
- // Startup a basic cluster
- cluster.fork();
- cluster.fork();
-} else {
- // This is the testcase
-
- const fork = require("child_process").fork;
-
- // List all workers
- const workers = [];
-
- // Spawn a cluster process
- const primary = fork(process.argv[1], ["cluster"], { silent: true });
-
- // Handle messages from the cluster
- primary.on(
- "message",
- common.mustCall(data => {
- // Add worker pid to list and progress tracker
- if (data.cmd === "worker") {
- workers.push(data.workerPID);
- }
- }, totalWorkers),
- );
-
- // When cluster is dead
- primary.on(
- "exit",
- common.mustCall(code => {
- // Check that the cluster died accidentally (non-zero exit code)
- assert.strictEqual(code, 1);
-
- // XXX(addaleax): The fact that this uses raw PIDs makes the test inherently
- // flaky – another process might end up being started right after the
- // workers finished and receive the same PID.
- const pollWorkers = () => {
- // When primary is dead all workers should be dead too
- if (workers.some(pid => common.isAlive(pid))) {
- setTimeout(pollWorkers, 50);
- }
- };
-
- // Loop indefinitely until worker exit
- pollWorkers();
- }),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-primary-kill.js b/test/js/node/cluster/upstream/parallel/test-cluster-primary-kill.js
deleted file mode 100644
index 1a3a26f34d..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-primary-kill.js
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isWorker) {
- // Keep the worker alive
- const http = require("http");
- http.Server().listen(0, "127.0.0.1");
-} else if (process.argv[2] === "cluster") {
- const worker = cluster.fork();
-
- // send PID info to testcase process
- process.send({
- pid: worker.process.pid,
- });
-
- // Terminate the cluster process
- worker.once(
- "listening",
- common.mustCall(() => {
- setTimeout(() => {
- process.exit(0);
- }, 1000);
- }),
- );
-} else {
- // This is the testcase
- const fork = require("child_process").fork;
-
- // Spawn a cluster process
- const primary = fork(process.argv[1], ["cluster"]);
-
- // get pid info
- let pid = null;
- primary.once("message", data => {
- pid = data.pid;
- });
-
- // When primary is dead
- let alive = true;
- primary.on(
- "exit",
- common.mustCall(code => {
- // Make sure that the primary died on purpose
- assert.strictEqual(code, 0);
-
- // Check worker process status
- const pollWorker = () => {
- alive = common.isAlive(pid);
- if (alive) {
- setTimeout(pollWorker, 50);
- }
- };
- // Loop indefinitely until worker exit.
- pollWorker();
- }),
- );
-
- process.once("exit", () => {
- assert.strictEqual(typeof pid, "number", `got ${pid} instead of a worker pid`);
- assert.strictEqual(alive, false, `worker was alive after primary died (alive = ${alive})`);
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-process-disconnect.js b/test/js/node/cluster/upstream/parallel/test-cluster-process-disconnect.js
deleted file mode 100644
index bcaf7df146..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-process-disconnect.js
+++ /dev/null
@@ -1,24 +0,0 @@
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
- worker.on(
- "exit",
- common.mustCall((code, signal) => {
- assert.strictEqual(code, 0, `Worker did not exit normally with code: ${code}`);
- assert.strictEqual(signal, null, `Worker did not exit normally with signal: ${signal}`);
- }),
- );
-} else {
- const net = require("net");
- const server = net.createServer();
- server.listen(
- 0,
- common.mustCall(() => {
- process.disconnect();
- }),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-rr-handle-keep-loop-alive.js b/test/js/node/cluster/upstream/parallel/test-cluster-rr-handle-keep-loop-alive.js
deleted file mode 100644
index 8bb183af33..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-rr-handle-keep-loop-alive.js
+++ /dev/null
@@ -1,26 +0,0 @@
-"use strict";
-
-const common = require("../common");
-const cluster = require("cluster");
-const net = require("net");
-const assert = require("assert");
-
-cluster.schedulingPolicy = cluster.SCHED_RR;
-
-if (cluster.isPrimary) {
- let exited = false;
- const worker = cluster.fork();
- worker.on("exit", () => {
- exited = true;
- });
- setTimeout(() => {
- assert.ok(!exited);
- worker.kill();
- }, 3000);
-} else {
- const server = net.createServer(common.mustNotCall());
- server.listen(
- 0,
- common.mustCall(() => process.channel.unref()),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-rr-ref.js b/test/js/node/cluster/upstream/parallel/test-cluster-rr-ref.js
deleted file mode 100644
index d5f0cbd083..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-rr-ref.js
+++ /dev/null
@@ -1,20 +0,0 @@
-"use strict";
-
-const common = require("../common");
-const cluster = require("cluster");
-const net = require("net");
-
-if (cluster.isPrimary) {
- cluster.fork().on("message", function (msg) {
- if (msg === "done") this.kill();
- });
-} else {
- const server = net.createServer(common.mustNotCall());
- server.listen(0, function () {
- server.unref();
- server.ref();
- server.close(function () {
- process.send("done");
- });
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-send-deadlock.js b/test/js/node/cluster/upstream/parallel/test-cluster-send-deadlock.js
deleted file mode 100644
index c5838a666c..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-send-deadlock.js
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// Testing mutual send of handles: from primary to worker, and from worker to
-// primary.
-
-require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-const net = require("net");
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
- worker.on("exit", (code, signal) => {
- assert.strictEqual(code, 0, `Worker exited with an error code: ${code}`);
- assert(!signal, `Worker exited by a signal: ${signal}`);
- server.close();
- });
-
- const server = net.createServer(socket => {
- worker.send("handle", socket);
- });
-
- server.listen(0, () => {
- worker.send({ message: "listen", port: server.address().port });
- });
-} else {
- process.on("message", (msg, handle) => {
- if (msg.message && msg.message === "listen") {
- assert(msg.port);
- const client1 = net.connect(
- {
- host: "localhost",
- port: msg.port,
- },
- () => {
- const client2 = net.connect(
- {
- host: "localhost",
- port: msg.port,
- },
- () => {
- client1.on("close", onclose);
- client2.on("close", onclose);
- client1.end();
- client2.end();
- },
- );
- },
- );
- let waiting = 2;
- const onclose = () => {
- if (--waiting === 0) cluster.worker.disconnect();
- };
- } else {
- process.send("reply", handle);
- }
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-argv.js b/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-argv.js
deleted file mode 100644
index 8908aa7372..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-argv.js
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-setTimeout(common.mustNotCall("setup not emitted"), 1000).unref();
-
-cluster.on(
- "setup",
- common.mustCall(function () {
- const clusterArgs = cluster.settings.args;
- const realArgs = process.argv;
- assert.strictEqual(clusterArgs[clusterArgs.length - 1], realArgs[realArgs.length - 1]);
- }),
-);
-
-assert.notStrictEqual(process.argv[process.argv.length - 1], "OMG,OMG");
-process.argv.push("OMG,OMG");
-process.argv.push("OMG,OMG");
-cluster.setupPrimary();
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-cumulative.js b/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-cumulative.js
deleted file mode 100644
index f9b43121fb..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-cumulative.js
+++ /dev/null
@@ -1,62 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-assert(cluster.isPrimary);
-
-// cluster.settings should not be initialized until needed
-assert.deepStrictEqual(cluster.settings, {});
-
-cluster.setupPrimary();
-assert.deepStrictEqual(cluster.settings, {
- args: process.argv.slice(2),
- exec: process.argv[1],
- execArgv: process.execArgv,
- silent: false,
-});
-console.log("ok sets defaults");
-
-cluster.setupPrimary({ exec: "overridden" });
-assert.strictEqual(cluster.settings.exec, "overridden");
-console.log("ok overrides defaults");
-
-cluster.setupPrimary({ args: ["foo", "bar"] });
-assert.strictEqual(cluster.settings.exec, "overridden");
-assert.deepStrictEqual(cluster.settings.args, ["foo", "bar"]);
-
-cluster.setupPrimary({ execArgv: ["baz", "bang"] });
-assert.strictEqual(cluster.settings.exec, "overridden");
-assert.deepStrictEqual(cluster.settings.args, ["foo", "bar"]);
-assert.deepStrictEqual(cluster.settings.execArgv, ["baz", "bang"]);
-console.log("ok preserves unchanged settings on repeated calls");
-
-cluster.setupPrimary();
-assert.deepStrictEqual(cluster.settings, {
- args: ["foo", "bar"],
- exec: "overridden",
- execArgv: ["baz", "bang"],
- silent: false,
-});
-console.log("ok preserves current settings");
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-emit.js b/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-emit.js
deleted file mode 100644
index 305ebfced2..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary-emit.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-assert(cluster.isPrimary);
-
-function emitAndCatch(next) {
- cluster.once(
- "setup",
- common.mustCall(function (settings) {
- assert.strictEqual(settings.exec, "new-exec");
- setImmediate(next);
- }),
- );
- cluster.setupPrimary({ exec: "new-exec" });
-}
-
-function emitAndCatch2(next) {
- cluster.once(
- "setup",
- common.mustCall(function (settings) {
- assert("exec" in settings);
- setImmediate(next);
- }),
- );
- cluster.setupPrimary();
-}
-
-emitAndCatch(
- common.mustCall(function () {
- emitAndCatch2(common.mustCall());
- }),
-);
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary.js b/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary.js
deleted file mode 100644
index ccb103cf08..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-setup-primary.js
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isWorker) {
- // Just keep the worker alive
- process.send(process.argv[2]);
-} else if (cluster.isPrimary) {
- const checks = {
- args: false,
- setupEvent: false,
- settingsObject: false,
- };
-
- const totalWorkers = 2;
- let settings;
-
- // Setup primary
- cluster.setupPrimary({
- args: ["custom argument"],
- silent: true,
- });
-
- cluster.once("setup", function () {
- checks.setupEvent = true;
-
- settings = cluster.settings;
- if (
- settings &&
- settings.args &&
- settings.args[0] === "custom argument" &&
- settings.silent === true &&
- settings.exec === process.argv[1]
- ) {
- checks.settingsObject = true;
- }
- });
-
- let correctInput = 0;
-
- cluster.on(
- "online",
- common.mustCall(function listener(worker) {
- worker.once("message", function (data) {
- correctInput += data === "custom argument" ? 1 : 0;
- if (correctInput === totalWorkers) {
- checks.args = true;
- }
- worker.kill();
- });
- }, totalWorkers),
- );
-
- // Start all workers
- cluster.fork();
- cluster.fork();
-
- // Check all values
- process.once("exit", function () {
- const argsMsg =
- "Arguments was not send for one or more worker. " +
- `${correctInput} workers receive argument, ` +
- `but ${totalWorkers} were expected.`;
- assert.ok(checks.args, argsMsg);
-
- assert.ok(checks.setupEvent, "The setup event was never emitted");
-
- const settingObjectMsg = "The settingsObject do not have correct " + `properties : ${JSON.stringify(settings)}`;
- assert.ok(checks.settingsObject, settingObjectMsg);
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-shared-handle-bind-privileged-port.js b/test/js/node/cluster/upstream/parallel/test-cluster-shared-handle-bind-privileged-port.js
deleted file mode 100644
index e69c79d697..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-shared-handle-bind-privileged-port.js
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-if (common.isLinux) return; // TODO: bun
-
-// Skip on OS X Mojave. https://github.com/nodejs/node/issues/21679
-if (common.isOSX) common.skip("macOS may allow ordinary processes to use any port");
-
-if (common.isIBMi) common.skip("IBMi may allow ordinary processes to use any port");
-
-if (common.isWindows) common.skip("not reliable on Windows");
-
-if (process.getuid() === 0) common.skip("as this test should not be run as `root`");
-
-const assert = require("assert");
-const cluster = require("cluster");
-const net = require("net");
-
-if (cluster.isPrimary) {
- // Primary opens and binds the socket and shares it with the worker.
- cluster.schedulingPolicy = cluster.SCHED_NONE;
- cluster.fork().on(
- "exit",
- common.mustCall(function (exitCode) {
- assert.strictEqual(exitCode, 0);
- }),
- );
-} else {
- const s = net.createServer(common.mustNotCall());
- s.listen(42, common.mustNotCall("listen should have failed"));
- s.on(
- "error",
- common.mustCall(function (err) {
- assert.strictEqual(err.code, "EACCES");
- process.disconnect();
- }),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-uncaught-exception.js b/test/js/node/cluster/upstream/parallel/test-cluster-uncaught-exception.js
deleted file mode 100644
index ee1dee617e..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-uncaught-exception.js
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// Installing a custom uncaughtException handler should override the default
-// one that the cluster module installs.
-// https://github.com/joyent/node/issues/2556
-
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-const fork = require("child_process").fork;
-
-const MAGIC_EXIT_CODE = 42;
-
-const isTestRunner = process.argv[2] !== "child";
-
-if (isTestRunner) {
- const primary = fork(__filename, ["child"]);
- primary.on(
- "exit",
- common.mustCall(code => {
- assert.strictEqual(code, MAGIC_EXIT_CODE);
- }),
- );
-} else if (cluster.isPrimary) {
- process.on(
- "uncaughtException",
- common.mustCall(() => {
- process.nextTick(() => process.exit(MAGIC_EXIT_CODE));
- }),
- );
- cluster.fork();
- throw new Error("kill primary");
-} else {
- // worker
- process.exit();
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-death.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-death.js
deleted file mode 100644
index bab5c8df8a..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-death.js
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (!cluster.isPrimary) {
- process.exit(42);
-} else {
- const worker = cluster.fork();
- worker.on(
- "exit",
- common.mustCall(function (exitCode, signalCode) {
- assert.strictEqual(exitCode, 42);
- assert.strictEqual(signalCode, null);
- }),
- );
- cluster.on(
- "exit",
- common.mustCall(function (worker_) {
- assert.strictEqual(worker_, worker);
- }),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-disconnect-on-error.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-disconnect-on-error.js
deleted file mode 100644
index f9e3a0de2c..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-disconnect-on-error.js
+++ /dev/null
@@ -1,44 +0,0 @@
-"use strict";
-const common = require("../common");
-const http = require("http");
-const cluster = require("cluster");
-const assert = require("assert");
-
-cluster.schedulingPolicy = cluster.SCHED_NONE;
-
-const server = http.createServer();
-if (cluster.isPrimary) {
- let worker;
-
- server.listen(
- 0,
- common.mustSucceed(() => {
- assert(worker);
-
- worker.send({ port: server.address().port });
- }),
- );
-
- worker = cluster.fork();
- worker.on(
- "exit",
- common.mustCall(() => {
- server.close();
- }),
- );
-} else {
- process.on(
- "message",
- common.mustCall(msg => {
- assert(msg.port);
-
- server.listen(msg.port);
- server.on(
- "error",
- common.mustCall(e => {
- cluster.worker.disconnect();
- }),
- );
- }),
- );
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-disconnect.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-disconnect.js
deleted file mode 100644
index 35cae334d9..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-disconnect.js
+++ /dev/null
@@ -1,118 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isWorker) {
- const http = require("http");
- http.Server(() => {}).listen(0, "127.0.0.1");
-
- cluster.worker.on(
- "disconnect",
- common.mustCall(() => {
- process.exit(42);
- }),
- );
-} else if (cluster.isPrimary) {
- const checks = {
- cluster: {
- emitDisconnect: false,
- emitExit: false,
- callback: false,
- },
- worker: {
- emitDisconnect: false,
- emitDisconnectInsideWorker: false,
- emitExit: false,
- state: false,
- voluntaryMode: false,
- died: false,
- },
- };
-
- // start worker
- const worker = cluster.fork();
-
- // Disconnect worker when it is ready
- worker.once(
- "listening",
- common.mustCall(() => {
- const w = worker.disconnect();
- assert.strictEqual(worker, w, `${worker.id} did not return a reference`);
- }),
- );
-
- // Check cluster events
- cluster.once(
- "disconnect",
- common.mustCall(() => {
- checks.cluster.emitDisconnect = true;
- }),
- );
- cluster.once(
- "exit",
- common.mustCall(() => {
- checks.cluster.emitExit = true;
- }),
- );
-
- // Check worker events and properties
- worker.once(
- "disconnect",
- common.mustCall(() => {
- checks.worker.emitDisconnect = true;
- checks.worker.voluntaryMode = worker.exitedAfterDisconnect;
- checks.worker.state = worker.state;
- }),
- );
-
- // Check that the worker died
- worker.once(
- "exit",
- common.mustCall(code => {
- checks.worker.emitExit = true;
- checks.worker.died = !common.isAlive(worker.process.pid);
- checks.worker.emitDisconnectInsideWorker = code === 42;
- }),
- );
-
- process.once("exit", () => {
- const w = checks.worker;
- const c = checks.cluster;
-
- // events
- assert.ok(w.emitDisconnect, "Disconnect event did not emit");
- assert.ok(w.emitDisconnectInsideWorker, "Disconnect event did not emit inside worker");
- assert.ok(c.emitDisconnect, "Disconnect event did not emit");
- assert.ok(w.emitExit, "Exit event did not emit");
- assert.ok(c.emitExit, "Exit event did not emit");
-
- // flags
- assert.strictEqual(w.state, "disconnected");
- assert.strictEqual(w.voluntaryMode, true);
-
- // is process alive
- assert.ok(w.died, "The worker did not die");
- });
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-exit.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-exit.js
deleted file mode 100644
index e6e61ca604..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-exit.js
+++ /dev/null
@@ -1,142 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// test-cluster-worker-exit.js
-// verifies that, when a child process exits (by calling `process.exit(code)`)
-// - the primary receives the proper events in the proper order, no duplicates
-// - the exitCode and signalCode are correct in the 'exit' event
-// - the worker.exitedAfterDisconnect flag, and worker.state are correct
-// - the worker process actually goes away
-
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-const EXIT_CODE = 42;
-
-if (cluster.isWorker) {
- const http = require("http");
- const server = http.Server(() => {});
-
- server.once(
- "listening",
- common.mustCall(() => {
- process.exit(EXIT_CODE);
- }),
- );
- server.listen(0, "127.0.0.1");
-} else if (cluster.isPrimary) {
- const expected_results = {
- cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"],
- cluster_emitExit: [1, "the cluster did not emit 'exit'"],
- cluster_exitCode: [EXIT_CODE, "the cluster exited w/ incorrect exitCode"],
- cluster_signalCode: [null, "the cluster exited w/ incorrect signalCode"],
- worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"],
- worker_emitExit: [1, "the worker did not emit 'exit'"],
- worker_state: ["disconnected", "the worker state is incorrect"],
- worker_exitedAfterDisconnect: [false, "the .exitedAfterDisconnect flag is incorrect"],
- worker_died: [true, "the worker is still running"],
- worker_exitCode: [EXIT_CODE, "the worker exited w/ incorrect exitCode"],
- worker_signalCode: [null, "the worker exited w/ incorrect signalCode"],
- };
- const results = {
- cluster_emitDisconnect: 0,
- cluster_emitExit: 0,
- worker_emitDisconnect: 0,
- worker_emitExit: 0,
- };
-
- // start worker
- const worker = cluster.fork();
-
- // Check cluster events
- cluster.on(
- "disconnect",
- common.mustCall(() => {
- results.cluster_emitDisconnect += 1;
- }),
- );
- cluster.on(
- "exit",
- common.mustCall(worker => {
- results.cluster_exitCode = worker.process.exitCode;
- results.cluster_signalCode = worker.process.signalCode;
- results.cluster_emitExit += 1;
- }),
- );
-
- // Check worker events and properties
- worker.on(
- "disconnect",
- common.mustCall(() => {
- results.worker_emitDisconnect += 1;
- results.worker_exitedAfterDisconnect = worker.exitedAfterDisconnect;
- results.worker_state = worker.state;
- if (results.worker_emitExit > 0) {
- process.nextTick(() => finish_test());
- }
- }),
- );
-
- // Check that the worker died
- worker.once(
- "exit",
- common.mustCall((exitCode, signalCode) => {
- results.worker_exitCode = exitCode;
- results.worker_signalCode = signalCode;
- results.worker_emitExit += 1;
- results.worker_died = !common.isAlive(worker.process.pid);
- if (results.worker_emitDisconnect > 0) {
- process.nextTick(() => finish_test());
- }
- }),
- );
-
- const finish_test = () => {
- try {
- checkResults(expected_results, results);
- } catch (exc) {
- if (exc.name !== "AssertionError") {
- console.trace(exc);
- }
-
- process.exit(1);
- return;
- }
- process.exit(0);
- };
-}
-
-// Some helper functions ...
-
-function checkResults(expected_results, results) {
- for (const k in expected_results) {
- const actual = results[k];
- const expected = expected_results[k];
-
- assert.strictEqual(
- actual,
- expected && expected.length ? expected[0] : expected,
- `${expected[1] || ""} [expected: ${expected[0]} / actual: ${actual}]`,
- );
- }
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-isdead.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-isdead.js
deleted file mode 100644
index 079a154443..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-isdead.js
+++ /dev/null
@@ -1,34 +0,0 @@
-"use strict";
-require("../common");
-const cluster = require("cluster");
-const assert = require("assert");
-
-if (cluster.isPrimary) {
- const worker = cluster.fork();
- let workerDead = worker.isDead();
- assert.ok(
- !workerDead,
- `isDead() returned ${workerDead}. isDead() should return ` + "false right after the worker has been created.",
- );
-
- worker.on("exit", function () {
- workerDead = worker.isDead();
- assert.ok(
- workerDead,
- `isDead() returned ${workerDead}. After an event has been ` + "emitted, isDead should return true",
- );
- });
-
- worker.on("message", function (msg) {
- if (msg === "readyToDie") {
- worker.kill();
- }
- });
-} else if (cluster.isWorker) {
- const workerDead = cluster.worker.isDead();
- assert.ok(
- !workerDead,
- `isDead() returned ${workerDead}. isDead() should return ` + "false when called from within a worker",
- );
- process.send("readyToDie");
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-kill-signal.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-kill-signal.js
deleted file mode 100644
index 1562a5e9f3..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-kill-signal.js
+++ /dev/null
@@ -1,56 +0,0 @@
-"use strict";
-// test-cluster-worker-kill-signal.js
-// verifies that when we're killing a worker using Worker.prototype.kill
-// and the worker's process was killed with the given signal (SIGKILL)
-
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isWorker) {
- // Make the worker run something
- const http = require("http");
- const server = http.Server(() => {});
-
- server.once("listening", common.mustCall());
- server.listen(0, "127.0.0.1");
-} else if (cluster.isMaster) {
- const KILL_SIGNAL = "SIGKILL";
-
- // Start worker
- const worker = cluster.fork();
-
- // When the worker is up and running, kill it
- worker.once(
- "listening",
- common.mustCall(() => {
- worker.kill(KILL_SIGNAL);
- }),
- );
-
- // Check worker events and properties
- worker.on(
- "disconnect",
- common.mustCall(() => {
- assert.strictEqual(worker.exitedAfterDisconnect, false);
- assert.strictEqual(worker.state, "disconnected");
- }, 1),
- );
-
- // Check that the worker died
- worker.once(
- "exit",
- common.mustCall((exitCode, signalCode) => {
- const isWorkerProcessStillAlive = common.isAlive(worker.process.pid);
- const numOfRunningWorkers = Object.keys(cluster.workers).length;
-
- assert.strictEqual(exitCode, null);
- assert.strictEqual(signalCode, KILL_SIGNAL);
- assert.strictEqual(isWorkerProcessStillAlive, false);
- assert.strictEqual(numOfRunningWorkers, 0);
- }, 1),
- );
-
- // Check if the cluster was killed as well
- cluster.on("exit", common.mustCall(1));
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-kill.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-kill.js
deleted file mode 100644
index 1ba588b874..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-kill.js
+++ /dev/null
@@ -1,126 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// test-cluster-worker-kill.js
-// verifies that, when a child process is killed (we use SIGKILL)
-// - the primary receives the proper events in the proper order, no duplicates
-// - the exitCode and signalCode are correct in the 'exit' event
-// - the worker.exitedAfterDisconnect flag, and worker.state are correct
-// - the worker process actually goes away
-
-const common = require("../common");
-const assert = require("assert");
-const cluster = require("cluster");
-
-if (cluster.isWorker) {
- const http = require("http");
- const server = http.Server(() => {});
- server.once("listening", common.mustCall());
- server.listen(0, "127.0.0.1");
-} else if (cluster.isPrimary) {
- const KILL_SIGNAL = "SIGKILL";
- const expected_results = {
- cluster_emitDisconnect: [1, "the cluster did not emit 'disconnect'"],
- cluster_emitExit: [1, "the cluster did not emit 'exit'"],
- cluster_exitCode: [null, "the cluster exited w/ incorrect exitCode"],
- cluster_signalCode: [KILL_SIGNAL, "the cluster exited w/ incorrect signalCode"],
- worker_emitDisconnect: [1, "the worker did not emit 'disconnect'"],
- worker_emitExit: [1, "the worker did not emit 'exit'"],
- worker_state: ["disconnected", "the worker state is incorrect"],
- worker_exitedAfter: [false, "the .exitedAfterDisconnect flag is incorrect"],
- worker_died: [true, "the worker is still running"],
- worker_exitCode: [null, "the worker exited w/ incorrect exitCode"],
- worker_signalCode: [KILL_SIGNAL, "the worker exited w/ incorrect signalCode"],
- };
- const results = {
- cluster_emitDisconnect: 0,
- cluster_emitExit: 0,
- worker_emitDisconnect: 0,
- worker_emitExit: 0,
- };
-
- // start worker
- const worker = cluster.fork();
- // When the worker is up and running, kill it
- worker.once(
- "listening",
- common.mustCall(() => {
- worker.process.kill(KILL_SIGNAL);
- }),
- );
-
- // Check cluster events
- cluster.on(
- "disconnect",
- common.mustCall(() => {
- results.cluster_emitDisconnect += 1;
- }),
- );
- cluster.on(
- "exit",
- common.mustCall(worker => {
- results.cluster_exitCode = worker.process.exitCode;
- results.cluster_signalCode = worker.process.signalCode;
- results.cluster_emitExit += 1;
- }),
- );
-
- // Check worker events and properties
- worker.on(
- "disconnect",
- common.mustCall(() => {
- results.worker_emitDisconnect += 1;
- results.worker_exitedAfter = worker.exitedAfterDisconnect;
- results.worker_state = worker.state;
- }),
- );
-
- // Check that the worker died
- worker.once(
- "exit",
- common.mustCall((exitCode, signalCode) => {
- results.worker_exitCode = exitCode;
- results.worker_signalCode = signalCode;
- results.worker_emitExit += 1;
- results.worker_died = !common.isAlive(worker.process.pid);
- }),
- );
-
- process.on("exit", () => {
- checkResults(expected_results, results);
- });
-}
-
-// Some helper functions ...
-
-function checkResults(expected_results, results) {
- for (const k in expected_results) {
- const actual = results[k];
- const expected = expected_results[k];
-
- assert.strictEqual(
- actual,
- expected && expected.length ? expected[0] : expected,
- `${expected[1] || ""} [expected: ${expected[0]} / actual: ${actual}]`,
- );
- }
-}
diff --git a/test/js/node/cluster/upstream/parallel/test-cluster-worker-no-exit.js b/test/js/node/cluster/upstream/parallel/test-cluster-worker-no-exit.js
deleted file mode 100644
index 8dcfc45f2c..0000000000
--- a/test/js/node/cluster/upstream/parallel/test-cluster-worker-no-exit.js
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const common = require("../common");
-if (common.isOSX) return; // TODO: bun
-if (common.isLinux) return; // TODO: bun
-if (common.isWindows) return; // TODO: bun
-const assert = require("assert");
-const cluster = require("cluster");
-const net = require("net");
-
-let destroyed;
-let success;
-let worker;
-let server;
-
-// Workers do not exit on disconnect, they exit under normal node rules: when
-// they have nothing keeping their loop alive, like an active connection
-//
-// test this by:
-//
-// 1 creating a server, so worker can make a connection to something
-// 2 disconnecting worker
-// 3 wait to confirm it did not exit
-// 4 destroy connection
-// 5 confirm it does exit
-if (cluster.isPrimary) {
- server = net
- .createServer(function (conn) {
- server.close();
- worker.disconnect();
- worker
- .once("disconnect", function () {
- setTimeout(function () {
- conn.destroy();
- destroyed = true;
- }, 1000);
- })
- .once("exit", function () {
- // Worker should not exit while it has a connection
- assert(destroyed, "worker exited before connection destroyed");
- success = true;
- });
- })
- .listen(0, function () {
- const port = this.address().port;
-
- worker = cluster.fork().on("online", function () {
- this.send({ port });
- });
- });
- process.on("exit", function () {
- assert(success);
- });
-} else {
- process.on("message", function (msg) {
- // We shouldn't exit, not while a network connection exists
- net.connect(msg.port);
- });
-}
diff --git a/test/js/node/crypto/node-crypto.test.js b/test/js/node/crypto/node-crypto.test.js
index ba7386a333..f8cb1fb62f 100644
--- a/test/js/node/crypto/node-crypto.test.js
+++ b/test/js/node/crypto/node-crypto.test.js
@@ -1,7 +1,7 @@
import { describe, expect, it } from "bun:test";
import crypto from "node:crypto";
-import { PassThrough } from "node:stream";
+import { PassThrough, Readable } from "node:stream";
import util from "node:util";
it("crypto.randomBytes should return a Buffer", () => {
@@ -478,6 +478,27 @@ describe("createHash", () => {
copy.update("world");
expect(copy.digest("hex")).toBe(hash.digest("hex"));
});
+
+ it("uses the Transform options object", () => {
+ const hasher = crypto.createHash("sha256", { defaultEncoding: "binary" });
+ hasher.on("readable", () => {
+ const data = hasher.read();
+ if (data) {
+ expect(data.toString("hex")).toBe("4d4d75d742863ab9656f3d5f76dff8589c3922e95a24ea6812157ffe4aaa3b6b");
+ }
+ });
+ const stream = Readable.from("ï");
+ stream.pipe(hasher);
+ });
+});
+
+describe("Hash", () => {
+ it("should have correct method names", () => {
+ const hash = crypto.createHash("sha256");
+ expect(hash.update.name).toBe("update");
+ expect(hash.digest.name).toBe("digest");
+ expect(hash.copy.name).toBe("copy");
+ });
});
it("crypto.createHmac", () => {
diff --git a/test/js/node/http/node-http.test.ts b/test/js/node/http/node-http.test.ts
index 7400f06eb3..1457d2e862 100644
--- a/test/js/node/http/node-http.test.ts
+++ b/test/js/node/http/node-http.test.ts
@@ -2435,3 +2435,124 @@ it("should work when sending https.request with agent:false", async () => {
await promise;
});
+it("client should use chunked encoded if more than one write is called", async () => {
+ function sleep(ms) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+ }
+ // Bun.serve is used here until #15576 or similar fix is merged
+ using server = Bun.serve({
+ port: 0,
+ hostname: "127.0.0.1",
+ fetch(req) {
+ if (req.headers.get("transfer-encoding") !== "chunked") {
+ return new Response("should be chunked encoding", { status: 500 });
+ }
+ return new Response(req.body);
+ },
+ });
+
+ // Options for the HTTP request
+ const options = {
+ hostname: "127.0.0.1", // Replace with the target server
+ port: server.port,
+ path: "/api/data",
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ };
+
+ const { promise, resolve, reject } = Promise.withResolvers();
+
+ // Create the request
+ const req = http.request(options, res => {
+ if (res.statusCode !== 200) {
+ reject(new Error("Body should be chunked"));
+ }
+ const chunks = [];
+ // Collect the response data
+ res.on("data", chunk => {
+ chunks.push(chunk);
+ });
+
+ res.on("end", () => {
+ resolve(chunks);
+ });
+ });
+
+ // Handle errors
+ req.on("error", reject);
+
+ // Write chunks to the request body
+ req.write("Hello");
+ req.write(" ");
+ await sleep(100);
+ req.write("World");
+ req.write(" ");
+ await sleep(100);
+ req.write("BUN!");
+ // End the request and signal no more data will be sent
+ req.end();
+
+ const chunks = await promise;
+ expect(chunks.length).toBeGreaterThan(1);
+ expect(chunks[chunks.length - 1]?.toString()).toEndWith("BUN!");
+ expect(Buffer.concat(chunks).toString()).toBe("Hello World BUN!");
+});
+
+it("client should use content-length if only one write is called", async () => {
+ await using server = http.createServer((req, res) => {
+ if (req.headers["transfer-encoding"] === "chunked") {
+ return res.writeHead(500).end();
+ }
+ res.writeHead(200);
+ req.on("data", data => {
+ res.write(data);
+ });
+ req.on("end", () => {
+ res.end();
+ });
+ });
+
+ await once(server.listen(0, "127.0.0.1"), "listening");
+
+ // Options for the HTTP request
+ const options = {
+ hostname: "127.0.0.1", // Replace with the target server
+ port: server.address().port,
+ path: "/api/data",
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ };
+
+ const { promise, resolve, reject } = Promise.withResolvers();
+
+ // Create the request
+ const req = http.request(options, res => {
+ if (res.statusCode !== 200) {
+ reject(new Error("Body should not be chunked"));
+ }
+ const chunks = [];
+ // Collect the response data
+ res.on("data", chunk => {
+ chunks.push(chunk);
+ });
+
+ res.on("end", () => {
+ resolve(chunks);
+ });
+ });
+ // Handle errors
+ req.on("error", reject);
+ // Write chunks to the request body
+ req.write("Hello World BUN!");
+ // End the request and signal no more data will be sent
+ req.end();
+
+ const chunks = await promise;
+ expect(chunks.length).toBe(1);
+ expect(chunks[0]?.toString()).toBe("Hello World BUN!");
+ expect(Buffer.concat(chunks).toString()).toBe("Hello World BUN!");
+});
diff --git a/test/js/node/net/node-net-allowHalfOpen.test.js b/test/js/node/net/node-net-allowHalfOpen.test.js
new file mode 100644
index 0000000000..3485bdc37b
--- /dev/null
+++ b/test/js/node/net/node-net-allowHalfOpen.test.js
@@ -0,0 +1,115 @@
+import net from "node:net";
+import { tempDirWithFiles, nodeExe } from "harness";
+import { expect, test } from "bun:test";
+
+async function nodeRun(callback, clients = 1) {
+ const cwd = tempDirWithFiles("server", {
+ "index.mjs": `
+ import net from "node:net";
+ let clients = ${clients};
+ const server = net.createServer({ allowHalfOpen: true }, socket => {
+ // Listen for data from the client
+ socket.on("data", data => {
+ console.log(data.toString());
+ });
+
+ socket.on("end", () => {
+ console.log("Received FIN");
+ if(--clients == 0) {
+ server.close();
+ }
+ });
+ socket.on("error", console.error);
+
+ // start sending FIN
+ socket.end();
+ });
+ server.listen(0, "127.0.0.1", ()=> {
+ console.log(server.address().port?.toString());
+ })
+ `,
+ });
+ const process = Bun.spawn([nodeExe(), "index.mjs"], {
+ cwd,
+ stdin: "ignore",
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+
+ const reader = process.stdout.getReader();
+ let continueReading = true;
+ let stdout = "";
+ let port = 0;
+ do {
+ const { done, value } = await reader.read();
+
+ continueReading = !done;
+ const decoder = new TextDecoder();
+ if (value) {
+ if (!port) {
+ port = parseInt(decoder.decode(value), 10);
+ callback(port);
+ } else {
+ stdout += decoder.decode(value);
+ }
+ }
+ } while (continueReading);
+
+ return {
+ stdout,
+ stderr: (await Bun.readableStreamToText(process.stderr)).trim(),
+ code: await process.exited,
+ };
+}
+
+async function doHalfOpenRequest(port, allowHalfOpen) {
+ const { promise, resolve, reject } = Promise.withResolvers();
+
+ const client = net.connect({ host: "127.0.0.1", port, allowHalfOpen }, () => {
+ client.write("Hello, World");
+ });
+ client.on("error", reject);
+ client.on("close", resolve);
+ client.on("end", () => {
+ // delay the write response
+ setTimeout(() => {
+ client.write("Write after end");
+ client.end();
+ }, 10);
+ });
+ await promise;
+}
+
+test("allowHalfOpen: true should work on client-side", async () => {
+ const { promise: portPromise, resolve } = Promise.withResolvers();
+ const process = nodeRun(resolve, 1);
+
+ const port = await portPromise;
+ await doHalfOpenRequest(port, true);
+ const result = await process;
+ expect(result.code).toBe(0);
+ expect(result.stderr).toBe("");
+ expect(
+ result.stdout
+ .split("\n")
+ .map(s => s.trim())
+ .filter(s => s),
+ ).toEqual(["Hello, World", "Write after end", "Received FIN"]);
+});
+
+test("allowHalfOpen: false should work on client-side", async () => {
+ const { promise: portPromise, resolve } = Promise.withResolvers();
+ const process = nodeRun(resolve, 1);
+
+ const port = await portPromise;
+ await doHalfOpenRequest(port, false);
+ const result = await process;
+ expect(result.code).toBe(0);
+ expect(result.stderr).toBe("");
+ expect(
+ result.stdout
+ .split("\n")
+ .map(s => s.trim())
+ .filter(s => s),
+ ).toEqual(["Hello, World", "Received FIN"]);
+});
diff --git a/test/js/node/process/process.test.js b/test/js/node/process/process.test.js
index a2dac046fa..09f9bb28f4 100644
--- a/test/js/node/process/process.test.js
+++ b/test/js/node/process/process.test.js
@@ -118,11 +118,15 @@ it("process.chdir() on root dir", () => {
}
});
-it("process.hrtime()", () => {
+it("process.hrtime()", async () => {
const start = process.hrtime();
const end = process.hrtime(start);
- const end2 = process.hrtime();
expect(end[0]).toBe(0);
+
+ // Flaky on Ubuntu.
+ await Bun.sleep(0);
+ const end2 = process.hrtime();
+
expect(end2[1] > start[1]).toBe(true);
});
diff --git a/test/js/node/test/common/assertSnapshot.js b/test/js/node/test/common/assertSnapshot.js
index 88f40281e0..a22455160b 100644
--- a/test/js/node/test/common/assertSnapshot.js
+++ b/test/js/node/test/common/assertSnapshot.js
@@ -25,7 +25,7 @@ function replaceWindowsPaths(str) {
}
function replaceFullPaths(str) {
- return str.replaceAll(process.cwd(), '');
+ return str.replaceAll(path.resolve(__dirname, '../..'), '');
}
function transform(...args) {
@@ -78,8 +78,11 @@ async function spawnAndAssert(filename, transform = (x) => x, { tty = false, ...
return;
}
const flags = common.parseTestFlags(filename);
- const executable = tty ? 'tools/pseudo-tty.py' : process.execPath;
- const args = tty ? [process.execPath, ...flags, filename] : [...flags, filename];
+ const executable = tty ? (process.env.PYTHON || 'python3') : process.execPath;
+ const args =
+ tty ?
+ [path.join(__dirname, '../..', 'tools/pseudo-tty.py'), process.execPath, ...flags, filename] :
+ [...flags, filename];
const { stdout, stderr } = await common.spawnPromisified(executable, args, options);
await assertSnapshot(transform(`${stdout}${stderr}`), filename);
}
diff --git a/test/js/node/test/common/duplexpair.js b/test/js/node/test/common/duplexpair.js
deleted file mode 100644
index 1f41ed32f1..0000000000
--- a/test/js/node/test/common/duplexpair.js
+++ /dev/null
@@ -1,48 +0,0 @@
-'use strict';
-const { Duplex } = require('stream');
-const assert = require('assert');
-
-const kCallback = Symbol('Callback');
-const kOtherSide = Symbol('Other');
-
-class DuplexSocket extends Duplex {
- constructor() {
- super();
- this[kCallback] = null;
- this[kOtherSide] = null;
- }
-
- _read() {
- const callback = this[kCallback];
- if (callback) {
- this[kCallback] = null;
- callback();
- }
- }
-
- _write(chunk, encoding, callback) {
- assert.notStrictEqual(this[kOtherSide], null);
- assert.strictEqual(this[kOtherSide][kCallback], null);
- if (chunk.length === 0) {
- process.nextTick(callback);
- } else {
- this[kOtherSide].push(chunk);
- this[kOtherSide][kCallback] = callback;
- }
- }
-
- _final(callback) {
- this[kOtherSide].on('end', callback);
- this[kOtherSide].push(null);
- }
-}
-
-function makeDuplexPair() {
- const clientSide = new DuplexSocket();
- const serverSide = new DuplexSocket();
- clientSide[kOtherSide] = serverSide;
- serverSide[kOtherSide] = clientSide;
- return { clientSide, serverSide };
-}
-
-module.exports = makeDuplexPair;
diff --git a/test/js/node/test/common/globals.js b/test/js/node/test/common/globals.js
index 42caece2b8..5d1c4415ee 100644
--- a/test/js/node/test/common/globals.js
+++ b/test/js/node/test/common/globals.js
@@ -79,7 +79,6 @@ const webIdlExposedWildcard = new Set([
'TextDecoder',
'AbortController',
'AbortSignal',
- 'CustomEvent',
'EventTarget',
'Event',
'URL',
@@ -127,7 +126,6 @@ const webIdlExposedWindow = new Set([
'Response',
'WebSocket',
'EventSource',
- 'CloseEvent',
]);
const nodeGlobals = new Set([
diff --git a/test/js/node/test/common/index.js b/test/js/node/test/common/index.js
index c67a5b8a81..38a48e8901 100644
--- a/test/js/node/test/common/index.js
+++ b/test/js/node/test/common/index.js
@@ -141,7 +141,7 @@ const isSunOS = process.platform === 'sunos';
const isFreeBSD = process.platform === 'freebsd';
const isOpenBSD = process.platform === 'openbsd';
const isLinux = process.platform === 'linux';
-const isOSX = process.platform === 'darwin';
+const isMacOS = process.platform === 'darwin';
const isASan = process.config.variables.asan === 1;
const isPi = (() => {
try {
@@ -338,10 +338,9 @@ if (global.structuredClone) {
knownGlobals.push(global.structuredClone);
}
-// BUN:TODO: uncommenting this crashes bun
-// if (global.EventSource) {
-// knownGlobals.push(EventSource);
-// }
+if (global.EventSource) {
+ knownGlobals.push(EventSource);
+}
if (global.fetch) {
knownGlobals.push(fetch);
@@ -967,13 +966,18 @@ function getPrintedStackTrace(stderr) {
* @param {object} mod result returned by require()
* @param {object} expectation shape of expected namespace.
*/
-function expectRequiredModule(mod, expectation) {
+function expectRequiredModule(mod, expectation, checkESModule = true) {
+ const clone = { ...mod };
+ if (Object.hasOwn(mod, 'default') && checkESModule) {
+ assert.strictEqual(mod.__esModule, true);
+ delete clone.__esModule;
+ }
assert(isModuleNamespaceObject(mod));
- assert.deepStrictEqual({ ...mod }, { ...expectation });
+ assert.deepStrictEqual(clone, { ...expectation });
}
const common = {
- allowGlobals: [],
+ allowGlobals,
buildType,
canCreateSymLink,
childShouldThrowAndAbort,
@@ -1001,7 +1005,7 @@ const common = {
isLinux,
isMainThread,
isOpenBSD,
- isOSX,
+ isMacOS,
isPi,
isSunOS,
isWindows,
diff --git a/test/js/node/test/common/index.mjs b/test/js/node/test/common/index.mjs
index 430527faf8..007ce233fb 100644
--- a/test/js/node/test/common/index.mjs
+++ b/test/js/node/test/common/index.mjs
@@ -30,7 +30,7 @@ const {
isLinuxPPCBE,
isMainThread,
isOpenBSD,
- isOSX,
+ isMacOS,
isSunOS,
isWindows,
localIPv6Hosts,
@@ -85,7 +85,7 @@ export {
isLinuxPPCBE,
isMainThread,
isOpenBSD,
- isOSX,
+ isMacOS,
isSunOS,
isWindows,
localIPv6Hosts,
diff --git a/test/js/node/test/common/process-exit-code-cases.js b/test/js/node/test/common/process-exit-code-cases.js
new file mode 100644
index 0000000000..54cfe2655b
--- /dev/null
+++ b/test/js/node/test/common/process-exit-code-cases.js
@@ -0,0 +1,138 @@
+'use strict';
+
+const assert = require('assert');
+
+function getTestCases(isWorker = false) {
+ const cases = [];
+ function exitsOnExitCodeSet() {
+ process.exitCode = 42;
+ process.on('exit', (code) => {
+ assert.strictEqual(process.exitCode, 42);
+ assert.strictEqual(code, 42);
+ });
+ }
+ cases.push({ func: exitsOnExitCodeSet, result: 42 });
+
+ function changesCodeViaExit() {
+ process.exitCode = 99;
+ process.on('exit', (code) => {
+ assert.strictEqual(process.exitCode, 42);
+ assert.strictEqual(code, 42);
+ });
+ process.exit(42);
+ }
+ cases.push({ func: changesCodeViaExit, result: 42 });
+
+ function changesCodeZeroExit() {
+ process.exitCode = 99;
+ process.on('exit', (code) => {
+ assert.strictEqual(process.exitCode, 0);
+ assert.strictEqual(code, 0);
+ });
+ process.exit(0);
+ }
+ cases.push({ func: changesCodeZeroExit, result: 0 });
+
+ function exitWithOneOnUncaught() {
+ process.exitCode = 99;
+ process.on('exit', (code) => {
+ // Cannot use assert because it will be uncaughtException -> 1 exit code
+ // that will render this test useless
+ if (code !== 1 || process.exitCode !== 1) {
+ console.log('wrong code! expected 1 for uncaughtException');
+ process.exit(99);
+ }
+ });
+ throw new Error('ok');
+ }
+ cases.push({
+ func: exitWithOneOnUncaught,
+ result: 1,
+ error: /^Error: ok$/,
+ });
+
+ function changeCodeInsideExit() {
+ process.exitCode = 95;
+ process.on('exit', (code) => {
+ assert.strictEqual(process.exitCode, 95);
+ assert.strictEqual(code, 95);
+ process.exitCode = 99;
+ });
+ }
+ cases.push({ func: changeCodeInsideExit, result: 99 });
+
+ function zeroExitWithUncaughtHandler() {
+ const noop = () => { };
+ process.on('exit', (code) => {
+ process.off('uncaughtException', noop);
+ assert.strictEqual(process.exitCode, undefined);
+ assert.strictEqual(code, 0);
+ });
+ process.on('uncaughtException', noop);
+ throw new Error('ok');
+ }
+ cases.push({ func: zeroExitWithUncaughtHandler, result: 0 });
+
+ function changeCodeInUncaughtHandler() {
+ const modifyExitCode = () => { process.exitCode = 97; };
+ process.on('exit', (code) => {
+ process.off('uncaughtException', modifyExitCode);
+ assert.strictEqual(process.exitCode, 97);
+ assert.strictEqual(code, 97);
+ });
+ process.on('uncaughtException', modifyExitCode);
+ throw new Error('ok');
+ }
+ cases.push({ func: changeCodeInUncaughtHandler, result: 97 });
+
+ function changeCodeInExitWithUncaught() {
+ process.on('exit', (code) => {
+ assert.strictEqual(process.exitCode, 1);
+ assert.strictEqual(code, 1);
+ process.exitCode = 98;
+ });
+ throw new Error('ok');
+ }
+ cases.push({
+ func: changeCodeInExitWithUncaught,
+ result: 98,
+ error: /^Error: ok$/,
+ });
+
+ function exitWithZeroInExitWithUncaught() {
+ process.on('exit', (code) => {
+ assert.strictEqual(process.exitCode, 1);
+ assert.strictEqual(code, 1);
+ process.exitCode = 0;
+ });
+ throw new Error('ok');
+ }
+ cases.push({
+ func: exitWithZeroInExitWithUncaught,
+ result: 0,
+ error: /^Error: ok$/,
+ });
+
+ function exitWithThrowInUncaughtHandler() {
+ process.on('uncaughtException', () => {
+ throw new Error('ok');
+ });
+ throw new Error('bad');
+ }
+ cases.push({
+ func: exitWithThrowInUncaughtHandler,
+ result: isWorker ? 1 : 7,
+ error: /^Error: ok$/,
+ });
+
+ function exitWithUndefinedFatalException() {
+ process._fatalException = undefined;
+ throw new Error('ok');
+ }
+ cases.push({
+ func: exitWithUndefinedFatalException,
+ result: 6,
+ });
+ return cases;
+}
+exports.getTestCases = getTestCases;
diff --git a/test/js/node/test/common/sea.js b/test/js/node/test/common/sea.js
index 863047ab36..53bfd93d92 100644
--- a/test/js/node/test/common/sea.js
+++ b/test/js/node/test/common/sea.js
@@ -5,7 +5,7 @@ const fixtures = require('../common/fixtures');
const tmpdir = require('../common/tmpdir');
const { inspect } = require('util');
-const { readFileSync, copyFileSync } = require('fs');
+const { readFileSync, copyFileSync, statSync } = require('fs');
const {
spawnSyncAndExitWithoutError,
} = require('../common/child_process');
@@ -50,12 +50,23 @@ function skipIfSingleExecutableIsNotSupported() {
common.skip('UndefinedBehavior Sanitizer is not supported');
}
+ try {
+ readFileSync(process.execPath);
+ } catch (e) {
+ if (e.code === 'ERR_FS_FILE_TOO_LARGE') {
+ common.skip('The Node.js binary is too large to be supported by postject');
+ }
+ }
+
tmpdir.refresh();
// The SEA tests involve making a copy of the executable and writing some fixtures
- // to the tmpdir. To be safe, ensure that at least 120MB disk space is available.
- if (!tmpdir.hasEnoughSpace(120 * 1024 * 1024)) {
- common.skip('Available disk space < 120MB');
+ // to the tmpdir. To be safe, ensure that the disk space has at least a copy of the
+ // executable and some extra space for blobs and configs is available.
+ const stat = statSync(process.execPath);
+ const expectedSpace = stat.size + 10 * 1024 * 1024;
+ if (!tmpdir.hasEnoughSpace(expectedSpace)) {
+ common.skip(`Available disk space < ${Math.floor(expectedSpace / 1024 / 1024)} MB`);
}
}
diff --git a/test/js/node/test/common/shared-lib-util.js b/test/js/node/test/common/shared-lib-util.js
index 3ecd38791c..b5d947a266 100644
--- a/test/js/node/test/common/shared-lib-util.js
+++ b/test/js/node/test/common/shared-lib-util.js
@@ -22,7 +22,7 @@ function addLibraryPath(env) {
env.LIBPATH =
(env.LIBPATH ? env.LIBPATH + path.delimiter : '') +
kExecPath;
- // For Mac OSX.
+ // For macOS.
env.DYLD_LIBRARY_PATH =
(env.DYLD_LIBRARY_PATH ? env.DYLD_LIBRARY_PATH + path.delimiter : '') +
kExecPath;
diff --git a/test/js/node/test/parallel/.gitignore b/test/js/node/test/parallel/.gitignore
deleted file mode 100644
index fd3ec92e0c..0000000000
--- a/test/js/node/test/parallel/.gitignore
+++ /dev/null
@@ -1,67 +0,0 @@
-# Not working yet:
-child-process-double-pipe.test.js
-child-process-exec-cwd.test.js
-child-process-exec-timeout-expire.test.js
-child-process-spawn-controller.test.js
-child-process-stdio-inherit.test.js
-cluster-fork-env.test.js
-cluster-kill-infinite-loop.test.js
-file-write-stream4.test.js
-file-write-stream5.test.js
-filehandle-close.test.js
-fs-existssync-false.test.js
-fs-fmap.test.js
-fs-read-stream-fd.test.js
-fs-readdir-ucs2.test.js
-fs-watch-recursive-add-file-to-new-folder.test.js
-fs-watch-recursive-symlink.test.js
-http-parser-finish-error.test.js
-http-request-agent.test.js
-http2-connect-options.test.js
-https-server-connections-checking-leak.test.js
-module-circular-symlinks.test.js
-module-prototype-mutation.test.js
-net-listen-error.test.js
-net-server-close.test.js
-permission-fs-windows-path.test.js
-pipe-abstract-socket-http.test.js
-pipe-file-to-http.test.js
-process-ppid.test.js
-require-invalid-package.test.js
-require-long-path.test.js
-snapshot-dns-lookup-localhost.test.js
-trace-events-net-abstract-socket.test.js
-trace-events-worker-metadata-with-name.test.js
-windows-failed-heap-allocation.test.js
-worker-dns-terminate.test.js
-worker-esm-exit.test.js
-worker-message-port-wasm-module.test.js
-
-# Failing on Windows:
-pipe-head.test.js
-http-client-response-domain.test.js
-require-extensions-same-filename-as-dir-trailing-slash.test.js
-fs-realpath-on-substed-drive.test.js
-fs-symlink-dir-junction.test.js
-
-# macOS not working yet
-node-dns.test.js
-
-# Things we don't support:
-repl*
-inspector*
-npm*
-*changelog*
-permission*
-shadow-realm*
-trace-events*
-cli-node-options*
-corepack*
-eslint*
-coverage*
-buffer-zero-fill-cli*
-icu-minimum-version.test.js
-release-npm.test.js
-
-# Bad tests
-tls-wrap-no-abort.test.js
diff --git a/test/js/node/test/parallel/arm-math-illegal-instruction.test.js b/test/js/node/test/parallel/arm-math-illegal-instruction.test.js
deleted file mode 100644
index 58199f8742..0000000000
--- a/test/js/node/test/parallel/arm-math-illegal-instruction.test.js
+++ /dev/null
@@ -1,21 +0,0 @@
-//#FILE: test-arm-math-illegal-instruction.js
-//#SHA1: 08aea7234b93dfe296564c6dd21a58bc91acd9dd
-//-----------------
-"use strict";
-
-// This test ensures Math functions don't fail with an "illegal instruction"
-// error on ARM devices (primarily on the Raspberry Pi 1)
-// See https://github.com/nodejs/node/issues/1376
-// and https://code.google.com/p/v8/issues/detail?id=4019
-
-test("Math functions do not fail with illegal instruction on ARM devices", () => {
- // Iterate over all Math functions
- Object.getOwnPropertyNames(Math).forEach(functionName => {
- if (!/[A-Z]/.test(functionName)) {
- // The function names don't have capital letters.
- expect(() => Math[functionName](-0.5)).not.toThrow();
- }
- });
-});
-
-//<#END_FILE: test-arm-math-illegal-instruction.js
diff --git a/test/js/node/test/parallel/assert-esm-cjs-message-verify.test.js b/test/js/node/test/parallel/assert-esm-cjs-message-verify.test.js
deleted file mode 100644
index 93537273a8..0000000000
--- a/test/js/node/test/parallel/assert-esm-cjs-message-verify.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-assert-esm-cjs-message-verify.js
-//#SHA1: 3d120c4813c4051523045df80fc501e9921b878f
-//-----------------
-"use strict";
-
-const { spawnPromisified } = require("../common");
-const tmpdir = require("../common/tmpdir");
-const assert = require("assert");
-const { writeFileSync, unlink } = require("fs");
-const { join } = require("path");
-
-tmpdir.refresh();
-
-const fileImports = {
- cjs: 'const assert = require("assert");',
- mjs: 'import assert from "assert";',
-};
-
-const fileNames = [];
-
-for (const [ext, header] of Object.entries(fileImports)) {
- const fileName = `test-file.${ext}`;
- // Store the generated filesnames in an array
- fileNames.push(join(tmpdir.path, fileName));
-
- writeFileSync(tmpdir.resolve(fileName), `${header}\nassert.ok(0 === 2);`);
-}
-
-describe("ensure the assert.ok throwing similar error messages for esm and cjs files", () => {
- const nodejsPath = process.execPath;
- const errorsMessages = [];
-
- test("should return code 1 for each command", async () => {
- for (const fileName of fileNames) {
- const { stderr, code } = await spawnPromisified(nodejsPath, [fileName]);
- expect(code).toBe(1);
- // For each error message, filter the lines which will starts with AssertionError
- errorsMessages.push(stderr.split("\n").find(s => s.startsWith("AssertionError")));
- }
- });
-
- afterAll(() => {
- expect(errorsMessages).toHaveLength(2);
- expect(errorsMessages[0]).toEqual(errorsMessages[1]);
-
- for (const fileName of fileNames) {
- unlink(fileName, () => {});
- }
-
- tmpdir.refresh();
- });
-});
-
-//<#END_FILE: test-assert-esm-cjs-message-verify.js
diff --git a/test/js/node/test/parallel/assert-strict-exists.test.js b/test/js/node/test/parallel/assert-strict-exists.test.js
deleted file mode 100644
index 3595cf38ec..0000000000
--- a/test/js/node/test/parallel/assert-strict-exists.test.js
+++ /dev/null
@@ -1,13 +0,0 @@
-//#FILE: test-assert-strict-exists.js
-//#SHA1: 390d3a53b3e79630cbb673eed78ac5857a49352f
-//-----------------
-"use strict";
-
-test("assert/strict is the same as assert.strict", () => {
- const assert = require("assert");
- const assertStrict = require("assert/strict");
-
- expect(assertStrict).toBe(assert.strict);
-});
-
-//<#END_FILE: test-assert-strict-exists.js
diff --git a/test/js/node/test/parallel/async-hooks-recursive-stack-runinasyncscope.test.js b/test/js/node/test/parallel/async-hooks-recursive-stack-runinasyncscope.test.js
deleted file mode 100644
index 30f03f8332..0000000000
--- a/test/js/node/test/parallel/async-hooks-recursive-stack-runinasyncscope.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//#FILE: test-async-hooks-recursive-stack-runInAsyncScope.js
-//#SHA1: 7258dfd5a442e34e60920fb484336420db8754e2
-//-----------------
-"use strict";
-
-const async_hooks = require("async_hooks");
-
-// This test verifies that the async ID stack can grow indefinitely.
-
-function recurse(n) {
- const a = new async_hooks.AsyncResource("foobar");
- a.runInAsyncScope(() => {
- expect(a.asyncId()).toBe(async_hooks.executionAsyncId());
- expect(a.triggerAsyncId()).toBe(async_hooks.triggerAsyncId());
- if (n >= 0) recurse(n - 1);
- expect(a.asyncId()).toBe(async_hooks.executionAsyncId());
- expect(a.triggerAsyncId()).toBe(async_hooks.triggerAsyncId());
- });
-}
-
-test("async ID stack can grow indefinitely", () => {
- expect(() => recurse(1000)).not.toThrow();
-});
-
-//<#END_FILE: test-async-hooks-recursive-stack-runInAsyncScope.js
diff --git a/test/js/node/test/parallel/async-hooks-run-in-async-scope-this-arg.test.js b/test/js/node/test/parallel/async-hooks-run-in-async-scope-this-arg.test.js
deleted file mode 100644
index 41479c5c05..0000000000
--- a/test/js/node/test/parallel/async-hooks-run-in-async-scope-this-arg.test.js
+++ /dev/null
@@ -1,24 +0,0 @@
-//#FILE: test-async-hooks-run-in-async-scope-this-arg.js
-//#SHA1: a716f9818bdd704e1cf7ca188ffd4ccb9501a8a7
-//-----------------
-"use strict";
-
-// Test that passing thisArg to runInAsyncScope() works.
-
-const { AsyncResource } = require("async_hooks");
-
-const thisArg = {};
-
-const res = new AsyncResource("fhqwhgads");
-
-function callback() {
- expect(this).toBe(thisArg);
-}
-
-test("runInAsyncScope with thisArg", () => {
- const callbackSpy = jest.fn(callback);
- res.runInAsyncScope(callbackSpy, thisArg);
- expect(callbackSpy).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-async-hooks-run-in-async-scope-this-arg.js
diff --git a/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-1.test.js b/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-1.test.js
deleted file mode 100644
index c8988c5655..0000000000
--- a/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-1.test.js
+++ /dev/null
@@ -1,30 +0,0 @@
-//#FILE: test-async-hooks-worker-asyncfn-terminate-1.js
-//#SHA1: 556f29e8c45107ff3448d713145f6f4e070e8073
-//-----------------
-"use strict";
-
-const { Worker } = require("worker_threads");
-
-test("Worker with async function and async_hooks terminates correctly", () => {
- const w = new Worker(
- `
- const { createHook } = require('async_hooks');
-
- setImmediate(async () => {
- createHook({ init() {} }).enable();
- await 0;
- process.exit();
- });
- `,
- { eval: true },
- );
-
- return new Promise(resolve => {
- w.on("exit", () => {
- expect(true).toBe(true); // Ensures the 'exit' event was called
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-async-hooks-worker-asyncfn-terminate-1.js
diff --git a/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-2.test.js b/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-2.test.js
deleted file mode 100644
index 2140f81307..0000000000
--- a/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-2.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-async-hooks-worker-asyncfn-terminate-2.js
-//#SHA1: 2329c972e1256f3aadc37e92f0ff1219d8519328
-//-----------------
-"use strict";
-
-const { Worker } = require("worker_threads");
-
-// Like test-async-hooks-worker-promise.js but with the `await` and `createHook`
-// lines switched, because that resulted in different assertion failures
-// (one a Node.js assertion and one a V8 DCHECK) and it seems prudent to
-// cover both of those failures.
-
-test("Worker with async function and createHook", () => {
- const w = new Worker(
- `
- const { createHook } = require('async_hooks');
-
- setImmediate(async () => {
- await 0;
- createHook({ init() {} }).enable();
- process.exit();
- });
- `,
- { eval: true },
- );
-
- w.postMessage({});
-
- return new Promise(resolve => {
- w.on("exit", () => {
- expect(true).toBe(true); // Equivalent to common.mustCall()
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-async-hooks-worker-asyncfn-terminate-2.js
diff --git a/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-3.test.js b/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-3.test.js
deleted file mode 100644
index ecc905292a..0000000000
--- a/test/js/node/test/parallel/async-hooks-worker-asyncfn-terminate-3.test.js
+++ /dev/null
@@ -1,33 +0,0 @@
-//#FILE: test-async-hooks-worker-asyncfn-terminate-3.js
-//#SHA1: bd68d52f5ecd5cb22738f78ee855706ed424cbf0
-//-----------------
-"use strict";
-
-const { Worker } = require("worker_threads");
-
-// Like test-async-hooks-worker-promise.js but with an additional statement
-// after the `process.exit()` call, that shouldn't really make a difference
-// but apparently does.
-
-test("Worker with async function and process.exit()", done => {
- const w = new Worker(
- `
- const { createHook } = require('async_hooks');
-
- setImmediate(async () => {
- createHook({ init() {} }).enable();
- await 0;
- process.exit();
- process._rawDebug('THIS SHOULD NEVER BE REACHED');
- });
- `,
- { eval: true },
- );
-
- w.on("exit", () => {
- expect(true).toBe(true); // Ensure the exit event is called
- done();
- });
-});
-
-//<#END_FILE: test-async-hooks-worker-asyncfn-terminate-3.js
diff --git a/test/js/node/test/parallel/async-local-storage-deep-stack.test.js b/test/js/node/test/parallel/async-local-storage-deep-stack.test.js
deleted file mode 100644
index 9c3926b18b..0000000000
--- a/test/js/node/test/parallel/async-local-storage-deep-stack.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//#FILE: test-async-local-storage-deep-stack.js
-//#SHA1: 305d85dc794f55b19fffebfbb720ba0c83714f63
-//-----------------
-"use strict";
-
-const { AsyncLocalStorage } = require("async_hooks");
-
-// Regression test for: https://github.com/nodejs/node/issues/34556
-
-test("AsyncLocalStorage deep stack", () => {
- const als = new AsyncLocalStorage();
-
- const done = jest.fn();
-
- function run(count) {
- if (count !== 0) return als.run({}, run, --count);
- done();
- }
-
- run(1000);
-
- expect(done).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-async-local-storage-deep-stack.js
diff --git a/test/js/node/test/parallel/async-local-storage-http-multiclients.test.js b/test/js/node/test/parallel/async-local-storage-http-multiclients.test.js
deleted file mode 100644
index b90b19ea6b..0000000000
--- a/test/js/node/test/parallel/async-local-storage-http-multiclients.test.js
+++ /dev/null
@@ -1,89 +0,0 @@
-//#FILE: test-async-local-storage-http-multiclients.js
-//#SHA1: adf8feaec8fa034cbb22fd0f3e2a5ed224c1905e
-//-----------------
-"use strict";
-
-const { AsyncLocalStorage } = require("async_hooks");
-const http = require("http");
-
-const NUM_CLIENTS = 10;
-
-// Run multiple clients that receive data from a server
-// in multiple chunks, in a single non-closure function.
-// Use the AsyncLocalStorage (ALS) APIs to maintain the context
-// and data download. Make sure that individual clients
-// receive their respective data, with no conflicts.
-
-describe("AsyncLocalStorage with multiple HTTP clients", () => {
- const cls = new AsyncLocalStorage();
- let server;
- let index = 0;
-
- beforeAll(() => {
- // Set up a server that sends large buffers of data, filled
- // with cardinal numbers, increasing per request
- server = http.createServer((q, r) => {
- // Send a large chunk as response, otherwise the data
- // may be sent in a single chunk, and the callback in the
- // client may be called only once, defeating the purpose of test
- r.end((index++ % 10).toString().repeat(1024 * 1024));
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- it("should handle multiple clients correctly", async () => {
- const clientPromises = [];
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- for (let i = 0; i < NUM_CLIENTS; i++) {
- clientPromises.push(
- new Promise(resolve => {
- cls.run(new Map(), () => {
- const options = { port: server.address().port };
- const req = http.get(options, res => {
- const store = cls.getStore();
- store.set("data", "");
-
- // Make ondata and onend non-closure
- // functions and fully dependent on ALS
- res.setEncoding("utf8");
- res.on("data", ondata);
- res.on("end", () => {
- onend();
- resolve();
- });
- });
- req.end();
- });
- }),
- );
- }
-
- await Promise.all(clientPromises);
- });
-
- // Accumulate the current data chunk with the store data
- function ondata(d) {
- const store = cls.getStore();
- expect(store).not.toBeUndefined();
- let chunk = store.get("data");
- chunk += d;
- store.set("data", chunk);
- }
-
- // Retrieve the store data, and test for homogeneity
- function onend() {
- const store = cls.getStore();
- expect(store).not.toBeUndefined();
- const data = store.get("data");
- expect(data).toBe(data[0].repeat(data.length));
- }
-});
-
-//<#END_FILE: test-async-local-storage-http-multiclients.js
diff --git a/test/js/node/test/parallel/async-local-storage-snapshot.test.js b/test/js/node/test/parallel/async-local-storage-snapshot.test.js
deleted file mode 100644
index 8b4d0b80bd..0000000000
--- a/test/js/node/test/parallel/async-local-storage-snapshot.test.js
+++ /dev/null
@@ -1,24 +0,0 @@
-//#FILE: test-async-local-storage-snapshot.js
-//#SHA1: f8d967194bfb0b73994d296b03c0c43afa5127e5
-//-----------------
-"use strict";
-
-const { AsyncLocalStorage } = require("async_hooks");
-
-describe("AsyncLocalStorage snapshot", () => {
- test("should preserve the original context when using snapshot", () => {
- const asyncLocalStorage = new AsyncLocalStorage();
-
- const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
-
- const result = asyncLocalStorage.run(321, () => {
- return runInAsyncScope(() => {
- return asyncLocalStorage.getStore();
- });
- });
-
- expect(result).toBe(123);
- });
-});
-
-//<#END_FILE: test-async-local-storage-snapshot.js
diff --git a/test/js/node/test/parallel/atomics-wake.test.js b/test/js/node/test/parallel/atomics-wake.test.js
deleted file mode 100644
index 7c690a086a..0000000000
--- a/test/js/node/test/parallel/atomics-wake.test.js
+++ /dev/null
@@ -1,11 +0,0 @@
-//#FILE: test-atomics-wake.js
-//#SHA1: 311b66a7cd5fbc08a20b77de98a66f9cba763f8f
-//-----------------
-"use strict";
-
-// https://github.com/nodejs/node/issues/21219
-test("Atomics.wake should be undefined", () => {
- expect(Atomics.wake).toBeUndefined();
-});
-
-//<#END_FILE: test-atomics-wake.js
diff --git a/test/js/node/test/parallel/bad-unicode.test.js b/test/js/node/test/parallel/bad-unicode.test.js
deleted file mode 100644
index 26c70dbf53..0000000000
--- a/test/js/node/test/parallel/bad-unicode.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-bad-unicode.js
-//#SHA1: e9b8765f74af6588aff1bd7bfcbc6a19187d100e
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-test("eval with bad unicode throws SyntaxError", () => {
- expect(() => {
- eval('"\\uc/ef"');
- }).toThrow(
- expect.objectContaining({
- name: "SyntaxError",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-bad-unicode.js
diff --git a/test/js/node/test/parallel/beforeexit-event-exit.test.js b/test/js/node/test/parallel/beforeexit-event-exit.test.js
deleted file mode 100644
index c7a0ad2a9c..0000000000
--- a/test/js/node/test/parallel/beforeexit-event-exit.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-//#FILE: test-beforeexit-event-exit.js
-//#SHA1: 27b6351612c5ec4f51d3317ca1c89511b833eaab
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-test("beforeExit event should not be called when process.exit() is called", () => {
- const mockBeforeExit = jest.fn();
- process.on("beforeExit", mockBeforeExit);
-
- // Spy on process.exit to prevent actual exit
- const exitSpy = jest.spyOn(process, "exit").mockImplementation(() => {});
-
- process.exit();
-
- expect(mockBeforeExit).not.toHaveBeenCalled();
- expect(exitSpy).toHaveBeenCalled();
-
- // Clean up
- process.removeListener("beforeExit", mockBeforeExit);
- exitSpy.mockRestore();
-});
-
-//<#END_FILE: test-beforeexit-event-exit.js
diff --git a/test/js/node/test/parallel/binding-constants.test.js b/test/js/node/test/parallel/binding-constants.test.js
deleted file mode 100644
index e3cabf4e2b..0000000000
--- a/test/js/node/test/parallel/binding-constants.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-//#FILE: test-binding-constants.js
-//#SHA1: 84b14e2a54ec767074f2a4103eaa0b419655cf8b
-//-----------------
-"use strict";
-
-// Note: This test originally used internal bindings which are not recommended for use in tests.
-// The test has been modified to focus on the public API and behavior that can be tested without internals.
-
-test("constants object structure", () => {
- const constants = process.binding("constants");
-
- expect(Object.keys(constants).sort()).toEqual(["crypto", "fs", "os", "trace", "zlib"]);
-
- expect(Object.keys(constants.os).sort()).toEqual(["UV_UDP_REUSEADDR", "dlopen", "errno", "priority", "signals"]);
-});
-
-test("constants objects do not inherit from Object.prototype", () => {
- const constants = process.binding("constants");
- const inheritedProperties = Object.getOwnPropertyNames(Object.prototype);
-
- function testObject(obj) {
- expect(obj).toBeTruthy();
- expect(Object.prototype.toString.call(obj)).toBe("[object Object]");
- expect(Object.getPrototypeOf(obj)).toBeNull();
-
- inheritedProperties.forEach(property => {
- expect(property in obj).toBe(false);
- });
- }
-
- [
- constants,
- constants.crypto,
- constants.fs,
- constants.os,
- constants.trace,
- constants.zlib,
- constants.os.dlopen,
- constants.os.errno,
- constants.os.signals,
- ].forEach(testObject);
-});
-
-//<#END_FILE: test-binding-constants.js
diff --git a/test/js/node/test/parallel/blob-createobjecturl.test.js b/test/js/node/test/parallel/blob-createobjecturl.test.js
deleted file mode 100644
index 9f94ba18f5..0000000000
--- a/test/js/node/test/parallel/blob-createobjecturl.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-blob-createobjecturl.js
-//#SHA1: d2030ca0ad6757dd9d338bc2e65cd3ff8917009d
-//-----------------
-// Flags: --no-warnings
-"use strict";
-
-// Because registering a Blob URL requires generating a random
-// UUID, it can only be done if crypto support is enabled.
-if (typeof crypto === "undefined") {
- test.skip("missing crypto");
-}
-
-const { URL } = require("url");
-const { Blob, resolveObjectURL } = require("buffer");
-
-test("Blob URL creation and resolution", async () => {
- const blob = new Blob(["hello"]);
- const id = URL.createObjectURL(blob);
- expect(typeof id).toBe("string");
- const otherBlob = resolveObjectURL(id);
- expect(otherBlob).toBeInstanceOf(Blob);
- expect(otherBlob.constructor).toBe(Blob);
- expect(otherBlob.size).toBe(5);
- expect(Buffer.from(await otherBlob.arrayBuffer()).toString()).toBe("hello");
- URL.revokeObjectURL(id);
-
- // should do nothing
- URL.revokeObjectURL(id);
-
- expect(resolveObjectURL(id)).toBeUndefined();
-
- // Leaving a Blob registered should not cause an assert
- // when Node.js exists
- URL.createObjectURL(new Blob());
-});
-
-test("resolveObjectURL with invalid inputs", () => {
- ["not a url", undefined, 1, "blob:nodedata:1:wrong", {}].forEach(i => {
- expect(resolveObjectURL(i)).toBeUndefined();
- });
-});
-
-test("createObjectURL with invalid inputs", () => {
- [undefined, 1, "", false, {}].forEach(i => {
- expect(() => URL.createObjectURL(i)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-blob-createobjecturl.js
diff --git a/test/js/node/test/parallel/buffer-arraybuffer.test.js b/test/js/node/test/parallel/buffer-arraybuffer.test.js
deleted file mode 100644
index d33487198f..0000000000
--- a/test/js/node/test/parallel/buffer-arraybuffer.test.js
+++ /dev/null
@@ -1,158 +0,0 @@
-//#FILE: test-buffer-arraybuffer.js
-//#SHA1: 2297240ef18399097bd3383db051d8e37339a123
-//-----------------
-"use strict";
-
-const LENGTH = 16;
-
-test("Buffer from ArrayBuffer", () => {
- const ab = new ArrayBuffer(LENGTH);
- const dv = new DataView(ab);
- const ui = new Uint8Array(ab);
- const buf = Buffer.from(ab);
-
- expect(buf).toBeInstanceOf(Buffer);
- expect(buf.parent).toBe(buf.buffer);
- expect(buf.buffer).toBe(ab);
- expect(buf.length).toBe(ab.byteLength);
-
- buf.fill(0xc);
- for (let i = 0; i < LENGTH; i++) {
- expect(ui[i]).toBe(0xc);
- ui[i] = 0xf;
- expect(buf[i]).toBe(0xf);
- }
-
- buf.writeUInt32LE(0xf00, 0);
- buf.writeUInt32BE(0xb47, 4);
- buf.writeDoubleLE(3.1415, 8);
-
- expect(dv.getUint32(0, true)).toBe(0xf00);
- expect(dv.getUint32(4)).toBe(0xb47);
- expect(dv.getFloat64(8, true)).toBe(3.1415);
-});
-
-test.todo("Buffer.from with invalid ArrayBuffer", () => {
- expect(() => {
- function AB() {}
- Object.setPrototypeOf(AB, ArrayBuffer);
- Object.setPrototypeOf(AB.prototype, ArrayBuffer.prototype);
- Buffer.from(new AB());
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringContaining(
- "The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.",
- ),
- }),
- );
-});
-
-test("Buffer.from with byteOffset and length arguments", () => {
- const ab = new Uint8Array(5);
- ab[0] = 1;
- ab[1] = 2;
- ab[2] = 3;
- ab[3] = 4;
- ab[4] = 5;
- const buf = Buffer.from(ab.buffer, 1, 3);
- expect(buf.length).toBe(3);
- expect(buf[0]).toBe(2);
- expect(buf[1]).toBe(3);
- expect(buf[2]).toBe(4);
- buf[0] = 9;
- expect(ab[1]).toBe(9);
-
- expect(() => Buffer.from(ab.buffer, 6)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- // code: "ERR_BUFFER_OUT_OF_BOUNDS",
- // message: expect.stringContaining('"offset" is outside of buffer bounds'),
- }),
- );
-
- expect(() => Buffer.from(ab.buffer, 3, 6)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- // code: "ERR_BUFFER_OUT_OF_BOUNDS",
- // message: expect.stringContaining('"length" is outside of buffer bounds'),
- }),
- );
-});
-
-test("Deprecated Buffer() constructor", () => {
- const ab = new Uint8Array(5);
- ab[0] = 1;
- ab[1] = 2;
- ab[2] = 3;
- ab[3] = 4;
- ab[4] = 5;
- const buf = Buffer(ab.buffer, 1, 3);
- expect(buf.length).toBe(3);
- expect(buf[0]).toBe(2);
- expect(buf[1]).toBe(3);
- expect(buf[2]).toBe(4);
- buf[0] = 9;
- expect(ab[1]).toBe(9);
-
- expect(() => Buffer(ab.buffer, 6)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- // code: "ERR_BUFFER_OUT_OF_BOUNDS",
- // message: expect.stringContaining('"offset" is outside of buffer bounds'),
- }),
- );
-
- expect(() => Buffer(ab.buffer, 3, 6)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- // code: "ERR_BUFFER_OUT_OF_BOUNDS",
- // message: expect.stringContaining('"length" is outside of buffer bounds'),
- }),
- );
-});
-
-test("Buffer.from with non-numeric byteOffset", () => {
- const ab = new ArrayBuffer(10);
- const expected = Buffer.from(ab, 0);
- expect(Buffer.from(ab, "fhqwhgads")).toEqual(expected);
- expect(Buffer.from(ab, NaN)).toEqual(expected);
- expect(Buffer.from(ab, {})).toEqual(expected);
- expect(Buffer.from(ab, [])).toEqual(expected);
-
- expect(Buffer.from(ab, [1])).toEqual(Buffer.from(ab, 1));
-
- expect(() => Buffer.from(ab, Infinity)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- // code: "ERR_BUFFER_OUT_OF_BOUNDS",
- // message: expect.stringContaining('"offset" is outside of buffer bounds'),
- }),
- );
-});
-
-test("Buffer.from with non-numeric length", () => {
- const ab = new ArrayBuffer(10);
- const expected = Buffer.from(ab, 0, 0);
- expect(Buffer.from(ab, 0, "fhqwhgads")).toEqual(expected);
- expect(Buffer.from(ab, 0, NaN)).toEqual(expected);
- expect(Buffer.from(ab, 0, {})).toEqual(expected);
- expect(Buffer.from(ab, 0, [])).toEqual(expected);
-
- expect(Buffer.from(ab, 0, [1])).toEqual(Buffer.from(ab, 0, 1));
-
- expect(() => Buffer.from(ab, 0, Infinity)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- // code: "ERR_BUFFER_OUT_OF_BOUNDS",
- // message: expect.stringContaining('"length" is outside of buffer bounds'),
- }),
- );
-});
-
-test("Buffer.from with array-like entry and NaN length", () => {
- expect(Buffer.from({ length: NaN })).toEqual(Buffer.alloc(0));
-});
-
-//<#END_FILE: test-buffer-arraybuffer.js
diff --git a/test/js/node/test/parallel/buffer-bytelength.test.js b/test/js/node/test/parallel/buffer-bytelength.test.js
deleted file mode 100644
index 5934db1dc8..0000000000
--- a/test/js/node/test/parallel/buffer-bytelength.test.js
+++ /dev/null
@@ -1,131 +0,0 @@
-//#FILE: test-buffer-bytelength.js
-//#SHA1: bcc75ad2f868ac9414c789c29f23ee9c806c749d
-//-----------------
-"use strict";
-
-const SlowBuffer = require("buffer").SlowBuffer;
-const vm = require("vm");
-
-test("Buffer.byteLength with invalid arguments", () => {
- [[32, "latin1"], [NaN, "utf8"], [{}, "latin1"], []].forEach(args => {
- expect(() => Buffer.byteLength(...args)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringContaining(
- 'The "string" argument must be of type string or an instance of Buffer or ArrayBuffer.',
- ),
- }),
- );
- });
-});
-
-test("ArrayBuffer.isView for various Buffer types", () => {
- expect(ArrayBuffer.isView(new Buffer(10))).toBe(true);
- expect(ArrayBuffer.isView(new SlowBuffer(10))).toBe(true);
- expect(ArrayBuffer.isView(Buffer.alloc(10))).toBe(true);
- expect(ArrayBuffer.isView(Buffer.allocUnsafe(10))).toBe(true);
- expect(ArrayBuffer.isView(Buffer.allocUnsafeSlow(10))).toBe(true);
- expect(ArrayBuffer.isView(Buffer.from(""))).toBe(true);
-});
-
-test("Buffer.byteLength for various buffer types", () => {
- const incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]);
- expect(Buffer.byteLength(incomplete)).toBe(5);
-
- const ascii = Buffer.from("abc");
- expect(Buffer.byteLength(ascii)).toBe(3);
-
- const buffer = new ArrayBuffer(8);
- expect(Buffer.byteLength(buffer)).toBe(8);
-});
-
-test("Buffer.byteLength for TypedArrays", () => {
- expect(Buffer.byteLength(new Int8Array(8))).toBe(8);
- expect(Buffer.byteLength(new Uint8Array(8))).toBe(8);
- expect(Buffer.byteLength(new Uint8ClampedArray(2))).toBe(2);
- expect(Buffer.byteLength(new Int16Array(8))).toBe(16);
- expect(Buffer.byteLength(new Uint16Array(8))).toBe(16);
- expect(Buffer.byteLength(new Int32Array(8))).toBe(32);
- expect(Buffer.byteLength(new Uint32Array(8))).toBe(32);
- expect(Buffer.byteLength(new Float32Array(8))).toBe(32);
- expect(Buffer.byteLength(new Float64Array(8))).toBe(64);
-});
-
-test("Buffer.byteLength for DataView", () => {
- const dv = new DataView(new ArrayBuffer(2));
- expect(Buffer.byteLength(dv)).toBe(2);
-});
-
-test("Buffer.byteLength for zero length string", () => {
- expect(Buffer.byteLength("", "ascii")).toBe(0);
- expect(Buffer.byteLength("", "HeX")).toBe(0);
-});
-
-test("Buffer.byteLength for utf8", () => {
- expect(Buffer.byteLength("∑éllö wørl∂!", "utf-8")).toBe(19);
- expect(Buffer.byteLength("κλμνξο", "utf8")).toBe(12);
- expect(Buffer.byteLength("挵挶挷挸挹", "utf-8")).toBe(15);
- expect(Buffer.byteLength("𠝹𠱓𠱸", "UTF8")).toBe(12);
- expect(Buffer.byteLength("hey there")).toBe(9);
- expect(Buffer.byteLength("𠱸挶νξ#xx :)")).toBe(17);
- expect(Buffer.byteLength("hello world", "")).toBe(11);
- expect(Buffer.byteLength("hello world", "abc")).toBe(11);
- expect(Buffer.byteLength("ßœ∑≈", "unkn0wn enc0ding")).toBe(10);
-});
-
-test("Buffer.byteLength for base64", () => {
- expect(Buffer.byteLength("aGVsbG8gd29ybGQ=", "base64")).toBe(11);
- expect(Buffer.byteLength("aGVsbG8gd29ybGQ=", "BASE64")).toBe(11);
- expect(Buffer.byteLength("bm9kZS5qcyByb2NrcyE=", "base64")).toBe(14);
- expect(Buffer.byteLength("aGkk", "base64")).toBe(3);
- expect(Buffer.byteLength("bHNrZGZsa3NqZmtsc2xrZmFqc2RsZmtqcw==", "base64")).toBe(25);
-});
-
-test("Buffer.byteLength for base64url", () => {
- expect(Buffer.byteLength("aGVsbG8gd29ybGQ", "base64url")).toBe(11);
- expect(Buffer.byteLength("aGVsbG8gd29ybGQ", "BASE64URL")).toBe(11);
- expect(Buffer.byteLength("bm9kZS5qcyByb2NrcyE", "base64url")).toBe(14);
- expect(Buffer.byteLength("aGkk", "base64url")).toBe(3);
- expect(Buffer.byteLength("bHNrZGZsa3NqZmtsc2xrZmFqc2RsZmtqcw", "base64url")).toBe(25);
-});
-
-test("Buffer.byteLength for special padding", () => {
- expect(Buffer.byteLength("aaa=", "base64")).toBe(2);
- expect(Buffer.byteLength("aaaa==", "base64")).toBe(3);
- expect(Buffer.byteLength("aaa=", "base64url")).toBe(2);
- expect(Buffer.byteLength("aaaa==", "base64url")).toBe(3);
-});
-
-test("Buffer.byteLength for various encodings", () => {
- expect(Buffer.byteLength("Il était tué")).toBe(14);
- expect(Buffer.byteLength("Il était tué", "utf8")).toBe(14);
-
- ["ascii", "latin1", "binary"]
- .reduce((es, e) => es.concat(e, e.toUpperCase()), [])
- .forEach(encoding => {
- expect(Buffer.byteLength("Il était tué", encoding)).toBe(12);
- });
-
- ["ucs2", "ucs-2", "utf16le", "utf-16le"]
- .reduce((es, e) => es.concat(e, e.toUpperCase()), [])
- .forEach(encoding => {
- expect(Buffer.byteLength("Il était tué", encoding)).toBe(24);
- });
-});
-
-test("Buffer.byteLength for ArrayBuffer from different context", () => {
- const arrayBuf = vm.runInNewContext("new ArrayBuffer()");
- expect(Buffer.byteLength(arrayBuf)).toBe(0);
-});
-
-test("Buffer.byteLength for invalid encodings", () => {
- for (let i = 1; i < 10; i++) {
- const encoding = String(i).repeat(i);
-
- expect(Buffer.isEncoding(encoding)).toBe(false);
- expect(Buffer.byteLength("foo", encoding)).toBe(Buffer.byteLength("foo", "utf8"));
- }
-});
-
-//<#END_FILE: test-buffer-bytelength.js
diff --git a/test/js/node/test/parallel/buffer-compare-offset.test.js b/test/js/node/test/parallel/buffer-compare-offset.test.js
deleted file mode 100644
index df674d2f59..0000000000
--- a/test/js/node/test/parallel/buffer-compare-offset.test.js
+++ /dev/null
@@ -1,95 +0,0 @@
-//#FILE: test-buffer-compare-offset.js
-//#SHA1: 460e187ac1a40db0dbc00801ad68f1272d27c3cd
-//-----------------
-"use strict";
-
-const assert = require("assert");
-
-describe("Buffer.compare with offset", () => {
- const a = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
- const b = Buffer.from([5, 6, 7, 8, 9, 0, 1, 2, 3, 4]);
-
- test("basic comparison", () => {
- expect(a.compare(b)).toBe(-1);
- });
-
- test("comparison with default arguments", () => {
- expect(a.compare(b, 0)).toBe(-1);
- expect(() => a.compare(b, "0")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- expect(a.compare(b, undefined)).toBe(-1);
- });
-
- test("comparison with specified ranges", () => {
- expect(a.compare(b, 0, undefined, 0)).toBe(-1);
- expect(a.compare(b, 0, 0, 0)).toBe(1);
- expect(() => a.compare(b, 0, "0", "0")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- expect(a.compare(b, 6, 10)).toBe(1);
- expect(a.compare(b, 6, 10, 0, 0)).toBe(-1);
- expect(a.compare(b, 0, 0, 0, 0)).toBe(0);
- expect(a.compare(b, 1, 1, 2, 2)).toBe(0);
- expect(a.compare(b, 0, 5, 4)).toBe(1);
- expect(a.compare(b, 5, undefined, 1)).toBe(1);
- expect(a.compare(b, 2, 4, 2)).toBe(-1);
- expect(a.compare(b, 0, 7, 4)).toBe(-1);
- expect(a.compare(b, 0, 7, 4, 6)).toBe(-1);
- });
-
- test("invalid arguments", () => {
- expect(() => a.compare(b, 0, null)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- expect(() => a.compare(b, 0, { valueOf: () => 5 })).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- expect(() => a.compare(b, Infinity, -Infinity)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- }),
- );
- expect(a.compare(b, 0xff)).toBe(1);
- expect(() => a.compare(b, "0xff")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- expect(() => a.compare(b, 0, "0xff")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- });
-
- test("out of range arguments", () => {
- const oor = expect.objectContaining({ code: "ERR_OUT_OF_RANGE" });
- expect(() => a.compare(b, 0, 100, 0)).toThrow(oor);
- expect(() => a.compare(b, 0, 1, 0, 100)).toThrow(oor);
- expect(() => a.compare(b, -1)).toThrow(oor);
- expect(() => a.compare(b, 0, Infinity)).toThrow(oor);
- expect(() => a.compare(b, 0, 1, -1)).toThrow(oor);
- expect(() => a.compare(b, -Infinity, Infinity)).toThrow(oor);
- });
-
- test("missing target argument", () => {
- expect(() => a.compare()).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringContaining('The "target" argument must be an instance of Buffer or Uint8Array'),
- }),
- );
- });
-});
-
-//<#END_FILE: test-buffer-compare-offset.js
diff --git a/test/js/node/test/parallel/buffer-compare.test.js b/test/js/node/test/parallel/buffer-compare.test.js
deleted file mode 100644
index 9f6d0c70be..0000000000
--- a/test/js/node/test/parallel/buffer-compare.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-buffer-compare.js
-//#SHA1: eab68d7262240af3d53eabedb0e7a515b2d84adf
-//-----------------
-"use strict";
-
-test("Buffer compare", () => {
- const b = Buffer.alloc(1, "a");
- const c = Buffer.alloc(1, "c");
- const d = Buffer.alloc(2, "aa");
- const e = new Uint8Array([0x61, 0x61]); // ASCII 'aa', same as d
-
- expect(b.compare(c)).toBe(-1);
- expect(c.compare(d)).toBe(1);
- expect(d.compare(b)).toBe(1);
- expect(d.compare(e)).toBe(0);
- expect(b.compare(d)).toBe(-1);
- expect(b.compare(b)).toBe(0);
-
- expect(Buffer.compare(b, c)).toBe(-1);
- expect(Buffer.compare(c, d)).toBe(1);
- expect(Buffer.compare(d, b)).toBe(1);
- expect(Buffer.compare(b, d)).toBe(-1);
- expect(Buffer.compare(c, c)).toBe(0);
- expect(Buffer.compare(e, e)).toBe(0);
- expect(Buffer.compare(d, e)).toBe(0);
- expect(Buffer.compare(d, b)).toBe(1);
-
- expect(Buffer.compare(Buffer.alloc(0), Buffer.alloc(0))).toBe(0);
- expect(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1))).toBe(-1);
- expect(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0))).toBe(1);
-
- expect(() => Buffer.compare(Buffer.alloc(1), "abc")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.stringContaining('The "buf2" argument must be an instance of Buffer or Uint8Array.'),
- }),
- );
-
- expect(() => Buffer.compare("abc", Buffer.alloc(1))).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.stringContaining('The "buf1" argument must be an instance of Buffer or Uint8Array.'),
- }),
- );
-
- expect(() => Buffer.alloc(1).compare("abc")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringContaining('The "target" argument must be an instance of Buffer or Uint8Array.'),
- }),
- );
-});
-
-//<#END_FILE: test-buffer-compare.js
diff --git a/test/js/node/test/parallel/buffer-constants.test.js b/test/js/node/test/parallel/buffer-constants.test.js
deleted file mode 100644
index 5c7c8a18d1..0000000000
--- a/test/js/node/test/parallel/buffer-constants.test.js
+++ /dev/null
@@ -1,28 +0,0 @@
-//#FILE: test-buffer-constants.js
-//#SHA1: a5818d34d1588306e48d574ec76b69b2ee4dc51c
-//-----------------
-"use strict";
-
-const { kMaxLength, kStringMaxLength } = require("buffer");
-const { MAX_LENGTH, MAX_STRING_LENGTH } = require("buffer").constants;
-
-test("Buffer constants", () => {
- expect(typeof MAX_LENGTH).toBe("number");
- expect(typeof MAX_STRING_LENGTH).toBe("number");
- expect(MAX_STRING_LENGTH).toBeLessThanOrEqual(MAX_LENGTH);
-
- expect(() => " ".repeat(MAX_STRING_LENGTH + 1)).toThrow(
- expect.objectContaining({
- name: "RangeError",
- message: expect.any(String),
- }),
- );
-
- expect(() => " ".repeat(MAX_STRING_LENGTH)).not.toThrow();
-
- // Legacy values match:
- expect(kMaxLength).toBe(MAX_LENGTH);
- expect(kStringMaxLength).toBe(MAX_STRING_LENGTH);
-});
-
-//<#END_FILE: test-buffer-constants.js
diff --git a/test/js/node/test/parallel/buffer-copy.test.js b/test/js/node/test/parallel/buffer-copy.test.js
deleted file mode 100644
index afb49923d2..0000000000
--- a/test/js/node/test/parallel/buffer-copy.test.js
+++ /dev/null
@@ -1,204 +0,0 @@
-//#FILE: test-buffer-copy.js
-//#SHA1: bff8bfe75b7289a279d9fc1a1bf2293257282d27
-//-----------------
-"use strict";
-
-test("Buffer copy operations", () => {
- const b = Buffer.allocUnsafe(1024);
- const c = Buffer.allocUnsafe(512);
-
- let cntr = 0;
-
- // Copy 512 bytes, from 0 to 512.
- b.fill(++cntr);
- c.fill(++cntr);
- const copied = b.copy(c, 0, 0, 512);
- expect(copied).toBe(512);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(b[i]);
- }
-
- // Current behavior is to coerce values to integers.
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedWithStrings = b.copy(c, "0", "0", "512");
- expect(copiedWithStrings).toBe(512);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(b[i]);
- }
-
- // Floats will be converted to integers via `Math.floor`
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedWithFloat = b.copy(c, 0, 0, 512.5);
- expect(copiedWithFloat).toBe(512);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(b[i]);
- }
-
- // Copy c into b, without specifying sourceEnd
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedWithoutSourceEnd = c.copy(b, 0, 0);
- expect(copiedWithoutSourceEnd).toBe(c.length);
- for (let i = 0; i < c.length; i++) {
- expect(b[i]).toBe(c[i]);
- }
-
- // Copy c into b, without specifying sourceStart
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedWithoutSourceStart = c.copy(b, 0);
- expect(copiedWithoutSourceStart).toBe(c.length);
- for (let i = 0; i < c.length; i++) {
- expect(b[i]).toBe(c[i]);
- }
-
- // Copied source range greater than source length
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedWithGreaterRange = c.copy(b, 0, 0, c.length + 1);
- expect(copiedWithGreaterRange).toBe(c.length);
- for (let i = 0; i < c.length; i++) {
- expect(b[i]).toBe(c[i]);
- }
-
- // Copy longer buffer b to shorter c without targetStart
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedLongerToShorter = b.copy(c);
- expect(copiedLongerToShorter).toBe(c.length);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(b[i]);
- }
-
- // Copy starting near end of b to c
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedNearEnd = b.copy(c, 0, b.length - Math.floor(c.length / 2));
- expect(copiedNearEnd).toBe(Math.floor(c.length / 2));
- for (let i = 0; i < Math.floor(c.length / 2); i++) {
- expect(c[i]).toBe(b[b.length - Math.floor(c.length / 2) + i]);
- }
- for (let i = Math.floor(c.length / 2) + 1; i < c.length; i++) {
- expect(c[c.length - 1]).toBe(c[i]);
- }
-
- // Try to copy 513 bytes, and check we don't overrun c
- b.fill(++cntr);
- c.fill(++cntr);
- const copiedOverrun = b.copy(c, 0, 0, 513);
- expect(copiedOverrun).toBe(c.length);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(b[i]);
- }
-
- // Copy 768 bytes from b into b
- b.fill(++cntr);
- b.fill(++cntr, 256);
- const copiedIntoSelf = b.copy(b, 0, 256, 1024);
- expect(copiedIntoSelf).toBe(768);
- for (let i = 0; i < b.length; i++) {
- expect(b[i]).toBe(cntr);
- }
-
- // Copy string longer than buffer length (failure will segfault)
- const bb = Buffer.allocUnsafe(10);
- bb.fill("hello crazy world");
-
- // Try to copy from before the beginning of b. Should not throw.
- expect(() => b.copy(c, 0, 100, 10)).not.toThrow();
-
- // Throw with invalid source type
- expect(() => Buffer.prototype.copy.call(0)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_THIS", //TODO:"ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-
- // Copy throws at negative targetStart
- expect(() => Buffer.allocUnsafe(10).copy(Buffer.allocUnsafe(5), -1, 0)).toThrow({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: `The value of "targetStart" is out of range. It must be >= 0 and <= 5. Received -1`,
- });
-
- // Copy throws at negative sourceStart
- expect(() => Buffer.allocUnsafe(10).copy(Buffer.allocUnsafe(5), 0, -1)).toThrow({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: `The value of "sourceStart" is out of range. It must be >= 0 and <= 10. Received -1`,
- });
-
- // Copy throws if sourceStart is greater than length of source
- expect(() => Buffer.allocUnsafe(10).copy(Buffer.allocUnsafe(5), 0, 100)).toThrow({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: `The value of "sourceStart" is out of range. It must be >= 0 and <= 10. Received 100`,
- });
-
- // Check sourceEnd resets to targetEnd if former is greater than the latter
- b.fill(++cntr);
- c.fill(++cntr);
- b.copy(c, 0, 0, 1025);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(b[i]);
- }
-
- // Throw with negative sourceEnd
- expect(() => b.copy(c, 0, 0, -1)).toThrow({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: `The value of "sourceEnd" is out of range. It must be >= 0 and <= 1024. Received -1`,
- });
-
- // When sourceStart is greater than sourceEnd, zero copied
- expect(b.copy(c, 0, 100, 10)).toBe(0);
-
- // When targetStart > targetLength, zero copied
- expect(b.copy(c, 512, 0, 10)).toBe(0);
-
- // Test that the `target` can be a Uint8Array.
- const d = new Uint8Array(c);
- // copy 512 bytes, from 0 to 512.
- b.fill(++cntr);
- d.fill(++cntr);
- const copiedToUint8Array = b.copy(d, 0, 0, 512);
- expect(copiedToUint8Array).toBe(512);
- for (let i = 0; i < d.length; i++) {
- expect(d[i]).toBe(b[i]);
- }
-
- // Test that the source can be a Uint8Array, too.
- const e = new Uint8Array(b);
- // copy 512 bytes, from 0 to 512.
- e.fill(++cntr);
- c.fill(++cntr);
- const copiedFromUint8Array = Buffer.prototype.copy.call(e, c, 0, 0, 512);
- expect(copiedFromUint8Array).toBe(512);
- for (let i = 0; i < c.length; i++) {
- expect(c[i]).toBe(e[i]);
- }
-
- // https://github.com/nodejs/node/issues/23668: Do not crash for invalid input.
- c.fill("c");
- b.copy(c, "not a valid offset");
- // Make sure this acted like a regular copy with `0` offset.
- expect(c).toEqual(b.slice(0, c.length));
-
- c.fill("C");
- expect(c.toString()).toBe("C".repeat(c.length));
- expect(() => {
- b.copy(c, {
- [Symbol.toPrimitive]() {
- throw new Error("foo");
- },
- });
- }).toThrow("foo");
- // No copying took place:
- expect(c.toString()).toBe("C".repeat(c.length));
-});
-
-//<#END_FILE: test-buffer-copy.js
diff --git a/test/js/node/test/parallel/buffer-equals.test.js b/test/js/node/test/parallel/buffer-equals.test.js
deleted file mode 100644
index 8fbd4c13c4..0000000000
--- a/test/js/node/test/parallel/buffer-equals.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-buffer-equals.js
-//#SHA1: 917344b9c4ba47f1e30d02ec6adfad938b2d342a
-//-----------------
-"use strict";
-
-test("Buffer.equals", () => {
- const b = Buffer.from("abcdf");
- const c = Buffer.from("abcdf");
- const d = Buffer.from("abcde");
- const e = Buffer.from("abcdef");
-
- expect(b.equals(c)).toBe(true);
- expect(c.equals(d)).toBe(false);
- expect(d.equals(e)).toBe(false);
- expect(d.equals(d)).toBe(true);
- expect(d.equals(new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]))).toBe(true);
-
- expect(() => Buffer.alloc(1).equals("abc")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringContaining(
- `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received`,
- ),
- }),
- );
-});
-
-//<#END_FILE: test-buffer-equals.js
diff --git a/test/js/node/test/parallel/buffer-failed-alloc-typed-arrays.test.js b/test/js/node/test/parallel/buffer-failed-alloc-typed-arrays.test.js
deleted file mode 100644
index 8dfcd1d03a..0000000000
--- a/test/js/node/test/parallel/buffer-failed-alloc-typed-arrays.test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-//#FILE: test-buffer-failed-alloc-typed-arrays.js
-//#SHA1: caa3a29c5ca1921e9ab5324d464067a364b8e687
-//-----------------
-"use strict";
-
-const { Buffer } = require("buffer");
-const SlowBuffer = require("buffer").SlowBuffer;
-
-// Test failed or zero-sized Buffer allocations not affecting typed arrays.
-// This test exists because of a regression that occurred. Because Buffer
-// instances are allocated with the same underlying allocator as TypedArrays,
-// but Buffer's can optional be non-zero filled, there was a regression that
-// occurred when a Buffer allocated failed, the internal flag specifying
-// whether or not to zero-fill was not being reset, causing TypedArrays to
-// allocate incorrectly.
-
-test("failed or zero-sized Buffer allocations do not affect typed arrays", () => {
- const zeroArray = new Uint32Array(10).fill(0);
- const sizes = [1e20, 0, 0.1, -1, "a", undefined, null, NaN];
- const allocators = [Buffer, SlowBuffer, Buffer.alloc, Buffer.allocUnsafe, Buffer.allocUnsafeSlow];
-
- for (const allocator of allocators) {
- for (const size of sizes) {
- try {
- // Some of these allocations are known to fail. If they do,
- // Uint32Array should still produce a zeroed out result.
- allocator(size);
- } catch {
- expect(new Uint32Array(10)).toEqual(zeroArray);
- }
- }
- }
-});
-
-//<#END_FILE: test-buffer-failed-alloc-typed-arrays.js
diff --git a/test/js/node/test/parallel/buffer-fill.test.js b/test/js/node/test/parallel/buffer-fill.test.js
deleted file mode 100644
index f045645d93..0000000000
--- a/test/js/node/test/parallel/buffer-fill.test.js
+++ /dev/null
@@ -1,428 +0,0 @@
-//#FILE: test-buffer-fill.js
-//#SHA1: 983940aa8a47c4d0985c2c4b4d1bc323a4e7d0f5
-//-----------------
-"use strict";
-
-const SIZE = 28;
-
-let buf1, buf2;
-
-beforeEach(() => {
- buf1 = Buffer.allocUnsafe(SIZE);
- buf2 = Buffer.allocUnsafe(SIZE);
-});
-
-// Helper functions
-function genBuffer(size, args) {
- const b = Buffer.allocUnsafe(size);
- return b.fill(0).fill.apply(b, args);
-}
-
-function bufReset() {
- buf1.fill(0);
- buf2.fill(0);
-}
-
-function writeToFill(string, offset, end, encoding) {
- if (typeof offset === "string") {
- encoding = offset;
- offset = 0;
- end = buf2.length;
- } else if (typeof end === "string") {
- encoding = end;
- end = buf2.length;
- } else if (end === undefined) {
- end = buf2.length;
- }
-
- if (offset < 0 || end > buf2.length) throw new RangeError("ERR_OUT_OF_RANGE");
-
- if (end <= offset) return buf2;
-
- offset >>>= 0;
- end >>>= 0;
- expect(offset).toBeLessThanOrEqual(buf2.length);
-
- const length = end - offset < 0 ? 0 : end - offset;
-
- let wasZero = false;
- do {
- const written = buf2.write(string, offset, length, encoding);
- offset += written;
- if (written === 0) {
- if (wasZero) throw new Error("Could not write all data to Buffer");
- else wasZero = true;
- }
- } while (offset < buf2.length);
-
- return buf2;
-}
-
-function testBufs(string, offset, length, encoding) {
- bufReset();
- buf1.fill.apply(buf1, arguments);
- expect(buf1.fill.apply(buf1, arguments)).toEqual(writeToFill.apply(null, arguments));
-}
-
-// Tests
-test("Default encoding", () => {
- testBufs("abc");
- testBufs("\u0222aa");
- testBufs("a\u0234b\u0235c\u0236");
- testBufs("abc", 4);
- testBufs("abc", 5);
- testBufs("abc", SIZE);
- testBufs("\u0222aa", 2);
- testBufs("\u0222aa", 8);
- testBufs("a\u0234b\u0235c\u0236", 4);
- testBufs("a\u0234b\u0235c\u0236", 12);
- testBufs("abc", 4, 1);
- testBufs("abc", 5, 1);
- testBufs("\u0222aa", 8, 1);
- testBufs("a\u0234b\u0235c\u0236", 4, 1);
- testBufs("a\u0234b\u0235c\u0236", 12, 1);
-});
-
-test("UTF8 encoding", () => {
- testBufs("abc", "utf8");
- testBufs("\u0222aa", "utf8");
- testBufs("a\u0234b\u0235c\u0236", "utf8");
- testBufs("abc", 4, "utf8");
- testBufs("abc", 5, "utf8");
- testBufs("abc", SIZE, "utf8");
- testBufs("\u0222aa", 2, "utf8");
- testBufs("\u0222aa", 8, "utf8");
- testBufs("a\u0234b\u0235c\u0236", 4, "utf8");
- testBufs("a\u0234b\u0235c\u0236", 12, "utf8");
- testBufs("abc", 4, 1, "utf8");
- testBufs("abc", 5, 1, "utf8");
- testBufs("\u0222aa", 8, 1, "utf8");
- testBufs("a\u0234b\u0235c\u0236", 4, 1, "utf8");
- testBufs("a\u0234b\u0235c\u0236", 12, 1, "utf8");
- expect(Buffer.allocUnsafe(1).fill(0).fill("\u0222")[0]).toBe(0xc8);
-});
-
-test("BINARY encoding", () => {
- testBufs("abc", "binary");
- testBufs("\u0222aa", "binary");
- testBufs("a\u0234b\u0235c\u0236", "binary");
- testBufs("abc", 4, "binary");
- testBufs("abc", 5, "binary");
- testBufs("abc", SIZE, "binary");
- testBufs("\u0222aa", 2, "binary");
- testBufs("\u0222aa", 8, "binary");
- testBufs("a\u0234b\u0235c\u0236", 4, "binary");
- testBufs("a\u0234b\u0235c\u0236", 12, "binary");
- testBufs("abc", 4, 1, "binary");
- testBufs("abc", 5, 1, "binary");
- testBufs("\u0222aa", 8, 1, "binary");
- testBufs("a\u0234b\u0235c\u0236", 4, 1, "binary");
- testBufs("a\u0234b\u0235c\u0236", 12, 1, "binary");
-});
-
-test("LATIN1 encoding", () => {
- testBufs("abc", "latin1");
- testBufs("\u0222aa", "latin1");
- testBufs("a\u0234b\u0235c\u0236", "latin1");
- testBufs("abc", 4, "latin1");
- testBufs("abc", 5, "latin1");
- testBufs("abc", SIZE, "latin1");
- testBufs("\u0222aa", 2, "latin1");
- testBufs("\u0222aa", 8, "latin1");
- testBufs("a\u0234b\u0235c\u0236", 4, "latin1");
- testBufs("a\u0234b\u0235c\u0236", 12, "latin1");
- testBufs("abc", 4, 1, "latin1");
- testBufs("abc", 5, 1, "latin1");
- testBufs("\u0222aa", 8, 1, "latin1");
- testBufs("a\u0234b\u0235c\u0236", 4, 1, "latin1");
- testBufs("a\u0234b\u0235c\u0236", 12, 1, "latin1");
-});
-
-test("UCS2 encoding", () => {
- testBufs("abc", "ucs2");
- testBufs("\u0222aa", "ucs2");
- testBufs("a\u0234b\u0235c\u0236", "ucs2");
- testBufs("abc", 4, "ucs2");
- testBufs("abc", SIZE, "ucs2");
- testBufs("\u0222aa", 2, "ucs2");
- testBufs("\u0222aa", 8, "ucs2");
- testBufs("a\u0234b\u0235c\u0236", 4, "ucs2");
- testBufs("a\u0234b\u0235c\u0236", 12, "ucs2");
- testBufs("abc", 4, 1, "ucs2");
- testBufs("abc", 5, 1, "ucs2");
- testBufs("\u0222aa", 8, 1, "ucs2");
- testBufs("a\u0234b\u0235c\u0236", 4, 1, "ucs2");
- testBufs("a\u0234b\u0235c\u0236", 12, 1, "ucs2");
- expect(Buffer.allocUnsafe(1).fill("\u0222", "ucs2")[0]).toBe(0x22);
-});
-
-test("HEX encoding", () => {
- testBufs("616263", "hex");
- testBufs("c8a26161", "hex");
- testBufs("61c8b462c8b563c8b6", "hex");
- testBufs("616263", 4, "hex");
- testBufs("616263", 5, "hex");
- testBufs("616263", SIZE, "hex");
- testBufs("c8a26161", 2, "hex");
- testBufs("c8a26161", 8, "hex");
- testBufs("61c8b462c8b563c8b6", 4, "hex");
- testBufs("61c8b462c8b563c8b6", 12, "hex");
- testBufs("616263", 4, 1, "hex");
- testBufs("616263", 5, 1, "hex");
- testBufs("c8a26161", 8, 1, "hex");
- testBufs("61c8b462c8b563c8b6", 4, 1, "hex");
- testBufs("61c8b462c8b563c8b6", 12, 1, "hex");
-});
-
-test("Invalid HEX encoding", () => {
- expect(() => {
- const buf = Buffer.allocUnsafe(SIZE);
- buf.fill("yKJh", "hex");
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_VALUE",
- name: "TypeError",
- }),
- );
-
- expect(() => {
- const buf = Buffer.allocUnsafe(SIZE);
- buf.fill("\u0222", "hex");
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_VALUE",
- name: "TypeError",
- }),
- );
-});
-
-test("BASE64 encoding", () => {
- testBufs("YWJj", "base64");
- testBufs("yKJhYQ==", "base64");
- testBufs("Yci0Ysi1Y8i2", "base64");
- testBufs("YWJj", 4, "base64");
- testBufs("YWJj", SIZE, "base64");
- testBufs("yKJhYQ==", 2, "base64");
- testBufs("yKJhYQ==", 8, "base64");
- testBufs("Yci0Ysi1Y8i2", 4, "base64");
- testBufs("Yci0Ysi1Y8i2", 12, "base64");
- testBufs("YWJj", 4, 1, "base64");
- testBufs("YWJj", 5, 1, "base64");
- testBufs("yKJhYQ==", 8, 1, "base64");
- testBufs("Yci0Ysi1Y8i2", 4, 1, "base64");
- testBufs("Yci0Ysi1Y8i2", 12, 1, "base64");
-});
-
-test("BASE64URL encoding", () => {
- testBufs("YWJj", "base64url");
- testBufs("yKJhYQ", "base64url");
- testBufs("Yci0Ysi1Y8i2", "base64url");
- testBufs("YWJj", 4, "base64url");
- testBufs("YWJj", SIZE, "base64url");
- testBufs("yKJhYQ", 2, "base64url");
- testBufs("yKJhYQ", 8, "base64url");
- testBufs("Yci0Ysi1Y8i2", 4, "base64url");
- testBufs("Yci0Ysi1Y8i2", 12, "base64url");
- testBufs("YWJj", 4, 1, "base64url");
- testBufs("YWJj", 5, 1, "base64url");
- testBufs("yKJhYQ", 8, 1, "base64url");
- testBufs("Yci0Ysi1Y8i2", 4, 1, "base64url");
- testBufs("Yci0Ysi1Y8i2", 12, 1, "base64url");
-});
-
-test("Buffer fill", () => {
- function deepStrictEqualValues(buf, arr) {
- for (const [index, value] of buf.entries()) {
- expect(value).toBe(arr[index]);
- }
- }
-
- const buf2Fill = Buffer.allocUnsafe(1).fill(2);
- deepStrictEqualValues(genBuffer(4, [buf2Fill]), [2, 2, 2, 2]);
- deepStrictEqualValues(genBuffer(4, [buf2Fill, 1]), [0, 2, 2, 2]);
- deepStrictEqualValues(genBuffer(4, [buf2Fill, 1, 3]), [0, 2, 2, 0]);
- deepStrictEqualValues(genBuffer(4, [buf2Fill, 1, 1]), [0, 0, 0, 0]);
- const hexBufFill = Buffer.allocUnsafe(2).fill(0).fill("0102", "hex");
- deepStrictEqualValues(genBuffer(4, [hexBufFill]), [1, 2, 1, 2]);
- deepStrictEqualValues(genBuffer(4, [hexBufFill, 1]), [0, 1, 2, 1]);
- deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, 3]), [0, 1, 2, 0]);
- deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, 1]), [0, 0, 0, 0]);
-});
-
-test("Check exceptions", () => {
- [
- [0, -1],
- [0, 0, buf1.length + 1],
- ["", -1],
- ["", 0, buf1.length + 1],
- ["", 1, -1],
- ].forEach(args => {
- expect(() => buf1.fill(...args)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- }),
- );
- });
-
- expect(() => buf1.fill("a", 0, buf1.length, "node rocks!")).toThrow(
- expect.objectContaining({
- code: "ERR_UNKNOWN_ENCODING",
- name: "TypeError",
- message: "Unknown encoding: node rocks!",
- }),
- );
-
- [
- ["a", 0, 0, NaN],
- ["a", 0, 0, false],
- ].forEach(args => {
- expect(() => buf1.fill(...args)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.stringContaining('The "encoding" argument must be of type string'),
- }),
- );
- });
-
- expect(() => buf1.fill("a", 0, 0, "foo")).toThrow(
- expect.objectContaining({
- code: "ERR_UNKNOWN_ENCODING",
- name: "TypeError",
- message: "Unknown encoding: foo",
- }),
- );
-});
-
-test("Out of range errors", () => {
- expect(() => Buffer.allocUnsafe(8).fill("a", -1)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- }),
- );
- expect(() => Buffer.allocUnsafe(8).fill("a", 0, 9)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- }),
- );
-});
-
-test("Empty fill", () => {
- Buffer.allocUnsafe(8).fill("");
- Buffer.alloc(8, "");
-});
-
-test("Buffer allocation and fill", () => {
- const buf = Buffer.alloc(64, 10);
- for (let i = 0; i < buf.length; i++) expect(buf[i]).toBe(10);
-
- buf.fill(11, 0, buf.length >> 1);
- for (let i = 0; i < buf.length >> 1; i++) expect(buf[i]).toBe(11);
- for (let i = (buf.length >> 1) + 1; i < buf.length; i++) expect(buf[i]).toBe(10);
-
- buf.fill("h");
- for (let i = 0; i < buf.length; i++) expect(buf[i]).toBe("h".charCodeAt(0));
-
- buf.fill(0);
- for (let i = 0; i < buf.length; i++) expect(buf[i]).toBe(0);
-
- buf.fill(null);
- for (let i = 0; i < buf.length; i++) expect(buf[i]).toBe(0);
-
- buf.fill(1, 16, 32);
- for (let i = 0; i < 16; i++) expect(buf[i]).toBe(0);
- for (let i = 16; i < 32; i++) expect(buf[i]).toBe(1);
- for (let i = 32; i < buf.length; i++) expect(buf[i]).toBe(0);
-});
-
-test("Buffer fill with string", () => {
- const buf = Buffer.alloc(10, "abc");
- expect(buf.toString()).toBe("abcabcabca");
- buf.fill("է");
- expect(buf.toString()).toBe("էէէէէ");
-});
-
-test("Buffer fill with invalid end", () => {
- expect(() => {
- const end = {
- [Symbol.toPrimitive]() {
- return 1;
- },
- };
- Buffer.alloc(1).fill(Buffer.alloc(1), 0, end);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.stringContaining('The "end" argument must be of type number. Received'),
- }),
- );
-});
-
-test.todo("Buffer fill with invalid length", () => {
- expect(() => {
- const buf = Buffer.from("w00t");
- Object.defineProperty(buf, "length", {
- value: 1337,
- enumerable: true,
- });
- buf.fill("");
- }).toThrow(
- expect.objectContaining({
- code: "ERR_BUFFER_OUT_OF_BOUNDS",
- name: "RangeError",
- message: "Attempt to access memory outside buffer bounds",
- }),
- );
-});
-
-test("Buffer fill with utf16le encoding", () => {
- expect(Buffer.allocUnsafeSlow(16).fill("ab", "utf16le")).toEqual(
- Buffer.from("61006200610062006100620061006200", "hex"),
- );
-
- expect(Buffer.allocUnsafeSlow(15).fill("ab", "utf16le")).toEqual(
- Buffer.from("610062006100620061006200610062", "hex"),
- );
-
- expect(Buffer.allocUnsafeSlow(16).fill("ab", "utf16le")).toEqual(
- Buffer.from("61006200610062006100620061006200", "hex"),
- );
- expect(Buffer.allocUnsafeSlow(16).fill("a", "utf16le")).toEqual(
- Buffer.from("61006100610061006100610061006100", "hex"),
- );
-
- expect(Buffer.allocUnsafeSlow(16).fill("a", "utf16le").toString("utf16le")).toBe("a".repeat(8));
- expect(Buffer.allocUnsafeSlow(16).fill("a", "latin1").toString("latin1")).toBe("a".repeat(16));
- expect(Buffer.allocUnsafeSlow(16).fill("a", "utf8").toString("utf8")).toBe("a".repeat(16));
-
- expect(Buffer.allocUnsafeSlow(16).fill("Љ", "utf16le").toString("utf16le")).toBe("Љ".repeat(8));
- expect(Buffer.allocUnsafeSlow(16).fill("Љ", "latin1").toString("latin1")).toBe("\t".repeat(16));
- expect(Buffer.allocUnsafeSlow(16).fill("Љ", "utf8").toString("utf8")).toBe("Љ".repeat(8));
-});
-
-test("Buffer fill with invalid hex encoding", () => {
- expect(() => {
- const buf = Buffer.from("a".repeat(1000));
- buf.fill("This is not correctly encoded", "hex");
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_VALUE",
- name: "TypeError",
- }),
- );
-});
-
-test("Buffer fill with empty values", () => {
- const bufEmptyString = Buffer.alloc(5, "");
- expect(bufEmptyString.toString()).toBe("\x00\x00\x00\x00\x00");
-
- const bufEmptyArray = Buffer.alloc(5, []);
- expect(bufEmptyArray.toString()).toBe("\x00\x00\x00\x00\x00");
-
- const bufEmptyBuffer = Buffer.alloc(5, Buffer.alloc(5));
- expect(bufEmptyBuffer.toString()).toBe("\x00\x00\x00\x00\x00");
-
- const bufZero = Buffer.alloc(5, 0);
- expect(bufZero.toString()).toBe("\x00\x00\x00\x00\x00");
-});
-
-//<#END_FILE: test-buffer-fill.js
diff --git a/test/js/node/test/parallel/buffer-from.test.js b/test/js/node/test/parallel/buffer-from.test.js
deleted file mode 100644
index 0d089d4e8c..0000000000
--- a/test/js/node/test/parallel/buffer-from.test.js
+++ /dev/null
@@ -1,168 +0,0 @@
-//#FILE: test-buffer-from.js
-//#SHA1: fdbb08fe98b94d1566ade587f17bb970130e1edd
-//-----------------
-"use strict";
-
-const { runInNewContext } = require("vm");
-
-const checkString = "test";
-
-const check = Buffer.from(checkString);
-
-class MyString extends String {
- constructor() {
- super(checkString);
- }
-}
-
-class MyPrimitive {
- [Symbol.toPrimitive]() {
- return checkString;
- }
-}
-
-class MyBadPrimitive {
- [Symbol.toPrimitive]() {
- return 1;
- }
-}
-
-test("Buffer.from with various string-like inputs", () => {
- expect(Buffer.from(new String(checkString))).toStrictEqual(check);
- expect(Buffer.from(new MyString())).toStrictEqual(check);
- expect(Buffer.from(new MyPrimitive())).toStrictEqual(check);
- // expect(Buffer.from(runInNewContext("new String(checkString)", { checkString }))).toStrictEqual(check); //TODO:
-});
-
-describe("Buffer.from with invalid inputs", () => {
- const invalidInputs = [
- {},
- new Boolean(true),
- {
- valueOf() {
- return null;
- },
- },
- {
- valueOf() {
- return undefined;
- },
- },
- { valueOf: null },
- { __proto__: null },
- new Number(true),
- new MyBadPrimitive(),
- Symbol(),
- 5n,
- (one, two, three) => {},
- undefined,
- null,
- ];
-
- for (const input of invalidInputs) {
- test(`${Bun.inspect(input)}`, () => {
- expect(() => Buffer.from(input)).toThrow(
- expect.objectContaining({
- // code: "ERR_INVALID_ARG_TYPE", //TODO:
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- expect(() => Buffer.from(input, "hex")).toThrow(
- expect.objectContaining({
- // code: "ERR_INVALID_ARG_TYPE", //TODO:
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
- }
-});
-
-test("Buffer.allocUnsafe and Buffer.from with valid inputs", () => {
- expect(() => Buffer.allocUnsafe(10)).not.toThrow();
- expect(() => Buffer.from("deadbeaf", "hex")).not.toThrow();
-});
-
-test("Buffer.copyBytesFrom with Uint16Array", () => {
- const u16 = new Uint16Array([0xffff]);
- const b16 = Buffer.copyBytesFrom(u16);
- u16[0] = 0;
- expect(b16.length).toBe(2);
- expect(b16[0]).toBe(255);
- expect(b16[1]).toBe(255);
-});
-
-test("Buffer.copyBytesFrom with Uint16Array and offset", () => {
- const u16 = new Uint16Array([0, 0xffff]);
- const b16 = Buffer.copyBytesFrom(u16, 1, 5);
- u16[0] = 0xffff;
- u16[1] = 0;
- expect(b16.length).toBe(2);
- expect(b16[0]).toBe(255);
- expect(b16[1]).toBe(255);
-});
-
-test("Buffer.copyBytesFrom with Uint32Array", () => {
- const u32 = new Uint32Array([0xffffffff]);
- const b32 = Buffer.copyBytesFrom(u32);
- u32[0] = 0;
- expect(b32.length).toBe(4);
- expect(b32[0]).toBe(255);
- expect(b32[1]).toBe(255);
- expect(b32[2]).toBe(255);
- expect(b32[3]).toBe(255);
-});
-
-test("Buffer.copyBytesFrom with invalid inputs", () => {
- expect(() => Buffer.copyBytesFrom()).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
-
- const invalidInputs = ["", Symbol(), true, false, {}, [], () => {}, 1, 1n, null, undefined];
- invalidInputs.forEach(notTypedArray => {
- expect(() => Buffer.copyBytesFrom(notTypedArray)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- });
-
- const invalidSecondArgs = ["", Symbol(), true, false, {}, [], () => {}, 1n];
- invalidSecondArgs.forEach(notANumber => {
- expect(() => Buffer.copyBytesFrom(new Uint8Array(1), notANumber)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- });
-
- const outOfRangeInputs = [-1, NaN, 1.1, -Infinity];
- outOfRangeInputs.forEach(outOfRange => {
- expect(() => Buffer.copyBytesFrom(new Uint8Array(1), outOfRange)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- }),
- );
- });
-
- invalidSecondArgs.forEach(notANumber => {
- expect(() => Buffer.copyBytesFrom(new Uint8Array(1), 0, notANumber)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- });
-
- outOfRangeInputs.forEach(outOfRange => {
- expect(() => Buffer.copyBytesFrom(new Uint8Array(1), 0, outOfRange)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- }),
- );
- });
-});
-
-//<#END_FILE: test-buffer-from.js
diff --git a/test/js/node/test/parallel/buffer-inheritance.test.js b/test/js/node/test/parallel/buffer-inheritance.test.js
deleted file mode 100644
index 5939621c9f..0000000000
--- a/test/js/node/test/parallel/buffer-inheritance.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-buffer-inheritance.js
-//#SHA1: 01cba7d2cb76cb1d00fa91b3666dc58333b66e1b
-//-----------------
-"use strict";
-
-test("Buffer inheritance", () => {
- function T(n) {
- const ui8 = new Uint8Array(n);
- Object.setPrototypeOf(ui8, T.prototype);
- return ui8;
- }
- Object.setPrototypeOf(T.prototype, Buffer.prototype);
- Object.setPrototypeOf(T, Buffer);
-
- T.prototype.sum = function sum() {
- let cntr = 0;
- for (let i = 0; i < this.length; i++) cntr += this[i];
- return cntr;
- };
-
- const vals = [new T(4), T(4)];
-
- vals.forEach(function (t) {
- expect(t.constructor).toBe(T);
- expect(Object.getPrototypeOf(t)).toBe(T.prototype);
- expect(Object.getPrototypeOf(Object.getPrototypeOf(t))).toBe(Buffer.prototype);
-
- t.fill(5);
- let cntr = 0;
- for (let i = 0; i < t.length; i++) cntr += t[i];
- expect(cntr).toBe(t.length * 5);
-
- // Check this does not throw
- expect(() => t.toString()).not.toThrow();
- });
-});
-
-//<#END_FILE: test-buffer-inheritance.js
diff --git a/test/js/node/test/parallel/buffer-inspect.test.js b/test/js/node/test/parallel/buffer-inspect.test.js
deleted file mode 100644
index d1ba515755..0000000000
--- a/test/js/node/test/parallel/buffer-inspect.test.js
+++ /dev/null
@@ -1,98 +0,0 @@
-//#FILE: test-buffer-inspect.js
-//#SHA1: 8578a4ec2de348a758e5c4dcbaa13a2ee7005451
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const util = require("util");
-const buffer = require("buffer");
-
-describe("Buffer inspect", () => {
- beforeEach(() => {
- buffer.INSPECT_MAX_BYTES = 2;
- });
-
- afterEach(() => {
- buffer.INSPECT_MAX_BYTES = Infinity;
- });
-
- test("Buffer and SlowBuffer inspection with INSPECT_MAX_BYTES = 2", () => {
- const b = Buffer.allocUnsafe(4);
- b.fill("1234");
-
- const s = buffer.SlowBuffer(4);
- s.fill("1234");
-
- const expected = "Buffer(4) [Uint8Array] [ 49, 50, ... 2 more items ]";
-
- expect(util.inspect(b)).toBe(expected);
- expect(util.inspect(s)).toBe(expected);
- });
-
- test("Buffer and SlowBuffer inspection with 2 bytes", () => {
- const b = Buffer.allocUnsafe(2);
- b.fill("12");
-
- const s = buffer.SlowBuffer(2);
- s.fill("12");
-
- const expected = "Buffer(2) [Uint8Array] [ 49, 50 ]";
-
- expect(util.inspect(b)).toBe(expected);
- expect(util.inspect(s)).toBe(expected);
- });
-
- test("Buffer and SlowBuffer inspection with INSPECT_MAX_BYTES = Infinity", () => {
- const b = Buffer.allocUnsafe(2);
- b.fill("12");
-
- const s = buffer.SlowBuffer(2);
- s.fill("12");
-
- const expected = "Buffer(2) [Uint8Array] [ 49, 50 ]";
-
- buffer.INSPECT_MAX_BYTES = Infinity;
-
- expect(util.inspect(b)).toBe(expected);
- expect(util.inspect(s)).toBe(expected);
- });
-
- test("Buffer inspection with custom properties", () => {
- const b = Buffer.allocUnsafe(2);
- b.fill("12");
- b.inspect = undefined;
- b.prop = new Uint8Array(0);
-
- expect(util.inspect(b)).toBe(
- "Buffer(2) [Uint8Array] [\n 49,\n 50,\n inspect: undefined,\n prop: Uint8Array(0) []\n]",
- );
- });
-
- test("Empty Buffer inspection with custom property", () => {
- const b = Buffer.alloc(0);
- b.prop = 123;
-
- expect(util.inspect(b)).toBe("Buffer(0) [Uint8Array] [ prop: 123 ]");
- });
-});
-
-//<#END_FILE: test-buffer-inspect.js
diff --git a/test/js/node/test/parallel/buffer-isascii.test.js b/test/js/node/test/parallel/buffer-isascii.test.js
deleted file mode 100644
index a8fde2110a..0000000000
--- a/test/js/node/test/parallel/buffer-isascii.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-//#FILE: test-buffer-isascii.js
-//#SHA1: e49cbd0752feaa8042a90129dfb38610eb002ee6
-//-----------------
-"use strict";
-
-const { isAscii, Buffer } = require("buffer");
-const { TextEncoder } = require("util");
-
-const encoder = new TextEncoder();
-
-test("isAscii function", () => {
- expect(isAscii(encoder.encode("hello"))).toBe(true);
- expect(isAscii(encoder.encode("ğ"))).toBe(false);
- expect(isAscii(Buffer.from([]))).toBe(true);
-});
-
-test("isAscii with invalid inputs", () => {
- const invalidInputs = [undefined, "", "hello", false, true, 0, 1, 0n, 1n, Symbol(), () => {}, {}, [], null];
-
- invalidInputs.forEach(input => {
- expect(() => isAscii(input)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- });
-});
-
-test("isAscii with detached array buffer", () => {
- const arrayBuffer = new ArrayBuffer(1024);
- structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
-
- expect(() => isAscii(arrayBuffer)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_STATE",
- }),
- );
-});
-
-//<#END_FILE: test-buffer-isascii.js
diff --git a/test/js/node/test/parallel/buffer-isencoding.test.js b/test/js/node/test/parallel/buffer-isencoding.test.js
deleted file mode 100644
index 010d80ca3a..0000000000
--- a/test/js/node/test/parallel/buffer-isencoding.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-buffer-isencoding.js
-//#SHA1: 438625bd1ca2a23aa8716bea5334f3ac07eb040f
-//-----------------
-"use strict";
-
-describe("Buffer.isEncoding", () => {
- describe("should return true for valid encodings", () => {
- const validEncodings = [
- "hex",
- "utf8",
- "utf-8",
- "ascii",
- "latin1",
- "binary",
- "base64",
- "base64url",
- "ucs2",
- "ucs-2",
- "utf16le",
- "utf-16le",
- ];
-
- for (const enc of validEncodings) {
- test(`${enc}`, () => {
- expect(Buffer.isEncoding(enc)).toBe(true);
- });
- }
- });
-
- describe("should return false for invalid encodings", () => {
- const invalidEncodings = ["utf9", "utf-7", "Unicode-FTW", "new gnu gun", false, NaN, {}, Infinity, [], 1, 0, -1];
-
- for (const enc of invalidEncodings) {
- test(`${enc}`, () => {
- expect(Buffer.isEncoding(enc)).toBe(false);
- });
- }
- });
-});
-
-//<#END_FILE: test-buffer-isencoding.js
diff --git a/test/js/node/test/parallel/buffer-isutf8.test.js b/test/js/node/test/parallel/buffer-isutf8.test.js
deleted file mode 100644
index fa55fb4c5b..0000000000
--- a/test/js/node/test/parallel/buffer-isutf8.test.js
+++ /dev/null
@@ -1,90 +0,0 @@
-//#FILE: test-buffer-isutf8.js
-//#SHA1: 47438bb1ade853e71f1266144d24188ebe75e714
-//-----------------
-"use strict";
-
-const { isUtf8, Buffer } = require("buffer");
-const { TextEncoder } = require("util");
-
-const encoder = new TextEncoder();
-
-test("isUtf8 validation", () => {
- expect(isUtf8(encoder.encode("hello"))).toBe(true);
- expect(isUtf8(encoder.encode("ğ"))).toBe(true);
- expect(isUtf8(Buffer.from([]))).toBe(true);
-});
-
-// Taken from test/fixtures/wpt/encoding/textdecoder-fatal.any.js
-test("invalid UTF-8 sequences", () => {
- const invalidSequences = [
- [0xff], // 'invalid code'
- [0xc0], // 'ends early'
- [0xe0], // 'ends early 2'
- [0xc0, 0x00], // 'invalid trail'
- [0xc0, 0xc0], // 'invalid trail 2'
- [0xe0, 0x00], // 'invalid trail 3'
- [0xe0, 0xc0], // 'invalid trail 4'
- [0xe0, 0x80, 0x00], // 'invalid trail 5'
- [0xe0, 0x80, 0xc0], // 'invalid trail 6'
- [0xfc, 0x80, 0x80, 0x80, 0x80, 0x80], // '> 0x10FFFF'
- [0xfe, 0x80, 0x80, 0x80, 0x80, 0x80], // 'obsolete lead byte'
-
- // Overlong encodings
- [0xc0, 0x80], // 'overlong U+0000 - 2 bytes'
- [0xe0, 0x80, 0x80], // 'overlong U+0000 - 3 bytes'
- [0xf0, 0x80, 0x80, 0x80], // 'overlong U+0000 - 4 bytes'
- [0xf8, 0x80, 0x80, 0x80, 0x80], // 'overlong U+0000 - 5 bytes'
- [0xfc, 0x80, 0x80, 0x80, 0x80, 0x80], // 'overlong U+0000 - 6 bytes'
-
- [0xc1, 0xbf], // 'overlong U+007F - 2 bytes'
- [0xe0, 0x81, 0xbf], // 'overlong U+007F - 3 bytes'
- [0xf0, 0x80, 0x81, 0xbf], // 'overlong U+007F - 4 bytes'
- [0xf8, 0x80, 0x80, 0x81, 0xbf], // 'overlong U+007F - 5 bytes'
- [0xfc, 0x80, 0x80, 0x80, 0x81, 0xbf], // 'overlong U+007F - 6 bytes'
-
- [0xe0, 0x9f, 0xbf], // 'overlong U+07FF - 3 bytes'
- [0xf0, 0x80, 0x9f, 0xbf], // 'overlong U+07FF - 4 bytes'
- [0xf8, 0x80, 0x80, 0x9f, 0xbf], // 'overlong U+07FF - 5 bytes'
- [0xfc, 0x80, 0x80, 0x80, 0x9f, 0xbf], // 'overlong U+07FF - 6 bytes'
-
- [0xf0, 0x8f, 0xbf, 0xbf], // 'overlong U+FFFF - 4 bytes'
- [0xf8, 0x80, 0x8f, 0xbf, 0xbf], // 'overlong U+FFFF - 5 bytes'
- [0xfc, 0x80, 0x80, 0x8f, 0xbf, 0xbf], // 'overlong U+FFFF - 6 bytes'
-
- [0xf8, 0x84, 0x8f, 0xbf, 0xbf], // 'overlong U+10FFFF - 5 bytes'
- [0xfc, 0x80, 0x84, 0x8f, 0xbf, 0xbf], // 'overlong U+10FFFF - 6 bytes'
-
- // UTF-16 surrogates encoded as code points in UTF-8
- [0xed, 0xa0, 0x80], // 'lead surrogate'
- [0xed, 0xb0, 0x80], // 'trail surrogate'
- [0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80], // 'surrogate pair'
- ];
-
- invalidSequences.forEach(input => {
- expect(isUtf8(Buffer.from(input))).toBe(false);
- });
-});
-
-test("invalid input types", () => {
- const invalidInputs = [null, undefined, "hello", true, false];
-
- invalidInputs.forEach(input => {
- expect(() => isUtf8(input)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- });
-});
-
-test("detached array buffer", () => {
- const arrayBuffer = new ArrayBuffer(1024);
- structuredClone(arrayBuffer, { transfer: [arrayBuffer] });
- expect(() => isUtf8(arrayBuffer)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_STATE",
- }),
- );
-});
-
-//<#END_FILE: test-buffer-isutf8.js
diff --git a/test/js/node/test/parallel/buffer-iterator.test.js b/test/js/node/test/parallel/buffer-iterator.test.js
deleted file mode 100644
index ca9cacb93d..0000000000
--- a/test/js/node/test/parallel/buffer-iterator.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-//#FILE: test-buffer-iterator.js
-//#SHA1: cd9bcdf671dc11d86bd194aa3e7500041f03eb4c
-//-----------------
-"use strict";
-
-// Buffers should be iterable
-test("Buffers are iterable", () => {
- const buffer = Buffer.from([1, 2, 3, 4, 5]);
- const arr = [];
-
- for (const b of buffer) {
- arr.push(b);
- }
-
- expect(arr).toEqual([1, 2, 3, 4, 5]);
-});
-
-// Buffer iterators should be iterable
-test("Buffer iterators are iterable", () => {
- const buffer = Buffer.from([1, 2, 3, 4, 5]);
- const arr = [];
-
- for (const b of buffer[Symbol.iterator]()) {
- arr.push(b);
- }
-
- expect(arr).toEqual([1, 2, 3, 4, 5]);
-});
-
-// buffer#values() should return iterator for values
-test("buffer.values() returns iterator for values", () => {
- const buffer = Buffer.from([1, 2, 3, 4, 5]);
- const arr = [];
-
- for (const b of buffer.values()) {
- arr.push(b);
- }
-
- expect(arr).toEqual([1, 2, 3, 4, 5]);
-});
-
-// buffer#keys() should return iterator for keys
-test("buffer.keys() returns iterator for keys", () => {
- const buffer = Buffer.from([1, 2, 3, 4, 5]);
- const arr = [];
-
- for (const b of buffer.keys()) {
- arr.push(b);
- }
-
- expect(arr).toEqual([0, 1, 2, 3, 4]);
-});
-
-// buffer#entries() should return iterator for entries
-test("buffer.entries() returns iterator for entries", () => {
- const buffer = Buffer.from([1, 2, 3, 4, 5]);
- const arr = [];
-
- for (const b of buffer.entries()) {
- arr.push(b);
- }
-
- expect(arr).toEqual([
- [0, 1],
- [1, 2],
- [2, 3],
- [3, 4],
- [4, 5],
- ]);
-});
-
-//<#END_FILE: test-buffer-iterator.js
diff --git a/test/js/node/test/parallel/buffer-new.test.js b/test/js/node/test/parallel/buffer-new.test.js
deleted file mode 100644
index 7f85579624..0000000000
--- a/test/js/node/test/parallel/buffer-new.test.js
+++ /dev/null
@@ -1,14 +0,0 @@
-//#FILE: test-buffer-new.js
-//#SHA1: 56270fc6342f4ac15433cce1e1b1252ac4dcbb98
-//-----------------
-"use strict";
-
-test("Buffer constructor with invalid arguments", () => {
- expect(() => new Buffer(42, "utf8")).toThrow({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: `The "string" argument must be of type string. Received 42`,
- });
-});
-
-//<#END_FILE: test-buffer-new.js
diff --git a/test/js/node/test/parallel/buffer-no-negative-allocation.test.js b/test/js/node/test/parallel/buffer-no-negative-allocation.test.js
deleted file mode 100644
index 2158402336..0000000000
--- a/test/js/node/test/parallel/buffer-no-negative-allocation.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-//#FILE: test-buffer-no-negative-allocation.js
-//#SHA1: c7f13ec857490bc5d1ffbf8da3fff19049c421f8
-//-----------------
-"use strict";
-
-const { SlowBuffer } = require("buffer");
-
-// Test that negative Buffer length inputs throw errors.
-
-const msg = expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: expect.any(String),
-});
-
-test("Buffer constructor throws on negative or NaN length", () => {
- expect(() => Buffer(-Buffer.poolSize)).toThrow(msg);
- expect(() => Buffer(-100)).toThrow(msg);
- expect(() => Buffer(-1)).toThrow(msg);
- expect(() => Buffer(NaN)).toThrow(msg);
-});
-
-test("Buffer.alloc throws on negative or NaN length", () => {
- expect(() => Buffer.alloc(-Buffer.poolSize)).toThrow(msg);
- expect(() => Buffer.alloc(-100)).toThrow(msg);
- expect(() => Buffer.alloc(-1)).toThrow(msg);
- expect(() => Buffer.alloc(NaN)).toThrow(msg);
-});
-
-test("Buffer.allocUnsafe throws on negative or NaN length", () => {
- expect(() => Buffer.allocUnsafe(-Buffer.poolSize)).toThrow(msg);
- expect(() => Buffer.allocUnsafe(-100)).toThrow(msg);
- expect(() => Buffer.allocUnsafe(-1)).toThrow(msg);
- expect(() => Buffer.allocUnsafe(NaN)).toThrow(msg);
-});
-
-test("Buffer.allocUnsafeSlow throws on negative or NaN length", () => {
- expect(() => Buffer.allocUnsafeSlow(-Buffer.poolSize)).toThrow(msg);
- expect(() => Buffer.allocUnsafeSlow(-100)).toThrow(msg);
- expect(() => Buffer.allocUnsafeSlow(-1)).toThrow(msg);
- expect(() => Buffer.allocUnsafeSlow(NaN)).toThrow(msg);
-});
-
-test("SlowBuffer throws on negative or NaN length", () => {
- expect(() => SlowBuffer(-Buffer.poolSize)).toThrow(msg);
- expect(() => SlowBuffer(-100)).toThrow(msg);
- expect(() => SlowBuffer(-1)).toThrow(msg);
- expect(() => SlowBuffer(NaN)).toThrow(msg);
-});
-
-//<#END_FILE: test-buffer-no-negative-allocation.js
diff --git a/test/js/node/test/parallel/buffer-nopendingdep-map.test.js b/test/js/node/test/parallel/buffer-nopendingdep-map.test.js
deleted file mode 100644
index 5fc9d4efad..0000000000
--- a/test/js/node/test/parallel/buffer-nopendingdep-map.test.js
+++ /dev/null
@@ -1,23 +0,0 @@
-//#FILE: test-buffer-nopendingdep-map.js
-//#SHA1: 908b5747ec3c5873c180b66b6e50221fd29169e3
-//-----------------
-// Flags: --no-warnings --pending-deprecation
-"use strict";
-
-test("Buffer methods should not emit deprecation warnings with --pending-deprecation", () => {
- const warningListener = jest.fn();
- process.on("warning", warningListener);
-
- // With the --pending-deprecation flag, the deprecation warning for
- // new Buffer() should not be emitted when Uint8Array methods are called.
-
- Buffer.from("abc").map(i => i);
- Buffer.from("abc").filter(i => i);
- Buffer.from("abc").slice(1, 2);
-
- expect(warningListener).not.toHaveBeenCalled();
-
- process.removeListener("warning", warningListener);
-});
-
-//<#END_FILE: test-buffer-nopendingdep-map.js
diff --git a/test/js/node/test/parallel/buffer-of-no-deprecation.test.js b/test/js/node/test/parallel/buffer-of-no-deprecation.test.js
deleted file mode 100644
index 53c31f103c..0000000000
--- a/test/js/node/test/parallel/buffer-of-no-deprecation.test.js
+++ /dev/null
@@ -1,18 +0,0 @@
-//#FILE: test-buffer-of-no-deprecation.js
-//#SHA1: 7c233f8a82411a5d1c293daecef6494d02d7dabf
-//-----------------
-"use strict";
-
-test("Buffer.of() should not emit deprecation warning", () => {
- const warningListener = jest.fn();
- process.on("warning", warningListener);
-
- Buffer.of(0, 1);
-
- expect(warningListener).not.toHaveBeenCalled();
-
- // Clean up the listener
- process.removeListener("warning", warningListener);
-});
-
-//<#END_FILE: test-buffer-of-no-deprecation.js
diff --git a/test/js/node/test/parallel/buffer-over-max-length.test.js b/test/js/node/test/parallel/buffer-over-max-length.test.js
deleted file mode 100644
index 5ba6d6af4e..0000000000
--- a/test/js/node/test/parallel/buffer-over-max-length.test.js
+++ /dev/null
@@ -1,24 +0,0 @@
-//#FILE: test-buffer-over-max-length.js
-//#SHA1: 797cb237a889a5f09d34b2554a46eb4c545f885e
-//-----------------
-"use strict";
-
-const buffer = require("buffer");
-const SlowBuffer = buffer.SlowBuffer;
-
-const kMaxLength = buffer.kMaxLength;
-const bufferMaxSizeMsg = expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: expect.stringContaining(`The value of "size" is out of range.`),
-});
-
-test("Buffer creation with over max length", () => {
- expect(() => Buffer(kMaxLength + 1)).toThrow(bufferMaxSizeMsg);
- expect(() => SlowBuffer(kMaxLength + 1)).toThrow(bufferMaxSizeMsg);
- expect(() => Buffer.alloc(kMaxLength + 1)).toThrow(bufferMaxSizeMsg);
- expect(() => Buffer.allocUnsafe(kMaxLength + 1)).toThrow(bufferMaxSizeMsg);
- expect(() => Buffer.allocUnsafeSlow(kMaxLength + 1)).toThrow(bufferMaxSizeMsg);
-});
-
-//<#END_FILE: test-buffer-over-max-length.js
diff --git a/test/js/node/test/parallel/buffer-parent-property.test.js b/test/js/node/test/parallel/buffer-parent-property.test.js
deleted file mode 100644
index ebf02d3652..0000000000
--- a/test/js/node/test/parallel/buffer-parent-property.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-//#FILE: test-buffer-parent-property.js
-//#SHA1: 1496dde41464d188eecd053b64a320c71f62bd7d
-//-----------------
-"use strict";
-
-// Fix for https://github.com/nodejs/node/issues/8266
-//
-// Zero length Buffer objects should expose the `buffer` property of the
-// TypedArrays, via the `parent` property.
-
-test("Buffer parent property", () => {
- // If the length of the buffer object is zero
- expect(Buffer.alloc(0).parent).toBeInstanceOf(ArrayBuffer);
-
- // If the length of the buffer object is equal to the underlying ArrayBuffer
- expect(Buffer.alloc(Buffer.poolSize).parent).toBeInstanceOf(ArrayBuffer);
-
- // Same as the previous test, but with user created buffer
- const arrayBuffer = new ArrayBuffer(0);
- expect(Buffer.from(arrayBuffer).parent).toBe(arrayBuffer);
- expect(Buffer.from(arrayBuffer).buffer).toBe(arrayBuffer);
- expect(Buffer.from(arrayBuffer).parent).toBe(arrayBuffer);
- expect(Buffer.from(arrayBuffer).buffer).toBe(arrayBuffer);
-});
-
-//<#END_FILE: test-buffer-parent-property.js
diff --git a/test/js/node/test/parallel/buffer-prototype-inspect.test.js b/test/js/node/test/parallel/buffer-prototype-inspect.test.js
deleted file mode 100644
index f6bb9a8915..0000000000
--- a/test/js/node/test/parallel/buffer-prototype-inspect.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-buffer-prototype-inspect.js
-//#SHA1: 3809d957d94134495a61469120087c12580fa3f3
-//-----------------
-"use strict";
-
-// lib/buffer.js defines Buffer.prototype.inspect() to override how buffers are
-// presented by util.inspect().
-
-const util = require("util");
-const buffer = require("buffer");
-buffer.INSPECT_MAX_BYTES = 50;
-
-test("Buffer.prototype.inspect() for non-empty buffer", () => {
- const buf = Buffer.from("fhqwhgads");
- expect(util.inspect(buf)).toBe("Buffer(9) [Uint8Array] [\n 102, 104, 113, 119,\n 104, 103, 97, 100,\n 115\n]");
-});
-
-test("Buffer.prototype.inspect() for empty buffer", () => {
- const buf = Buffer.from("");
- expect(util.inspect(buf)).toBe("Buffer(0) [Uint8Array] []");
-});
-
-test("Buffer.prototype.inspect() for large buffer", () => {
- const buf = Buffer.from("x".repeat(51));
- expect(util.inspect(buf)).toBe(
- `Buffer(51) [Uint8Array] [\n` +
- ` 120, 120, 120, 120, 120, 120, 120, 120, 120,\n` +
- ` 120, 120, 120, 120, 120, 120, 120, 120, 120,\n` +
- ` 120, 120, 120, 120, 120, 120, 120, 120, 120,\n` +
- ` 120, 120, 120, 120, 120, 120, 120, 120, 120,\n` +
- ` 120, 120, 120, 120, 120, 120, 120, 120, 120,\n` +
- ` 120, 120, 120, 120, 120,\n` +
- ` ... 1 more item\n` +
- `]`,
- );
-});
-
-//<#END_FILE: test-buffer-prototype-inspect.js
diff --git a/test/js/node/test/parallel/buffer-safe-unsafe.test.js b/test/js/node/test/parallel/buffer-safe-unsafe.test.js
deleted file mode 100644
index 84e1db9096..0000000000
--- a/test/js/node/test/parallel/buffer-safe-unsafe.test.js
+++ /dev/null
@@ -1,27 +0,0 @@
-//#FILE: test-buffer-safe-unsafe.js
-//#SHA1: 87831e463ab52a79fca3ac2e28eec57666ea9e5e
-//-----------------
-"use strict";
-
-test("Buffer safe and unsafe allocations", () => {
- const safe = Buffer.alloc(10);
-
- function isZeroFilled(buf) {
- for (let n = 0; n < buf.length; n++) if (buf[n] !== 0) return false;
- return true;
- }
-
- expect(isZeroFilled(safe)).toBe(true);
-
- // Test that unsafe allocations doesn't affect subsequent safe allocations
- Buffer.allocUnsafe(10);
- expect(isZeroFilled(new Float64Array(10))).toBe(true);
-
- new Buffer(10);
- expect(isZeroFilled(new Float64Array(10))).toBe(true);
-
- Buffer.allocUnsafe(10);
- expect(isZeroFilled(Buffer.alloc(10))).toBe(true);
-});
-
-//<#END_FILE: test-buffer-safe-unsafe.js
diff --git a/test/js/node/test/parallel/buffer-set-inspect-max-bytes.test.js b/test/js/node/test/parallel/buffer-set-inspect-max-bytes.test.js
deleted file mode 100644
index 306fa0f81b..0000000000
--- a/test/js/node/test/parallel/buffer-set-inspect-max-bytes.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-buffer-set-inspect-max-bytes.js
-//#SHA1: de73b2a241585e1cf17a057d21cdbabbadf963bb
-//-----------------
-"use strict";
-
-const buffer = require("buffer");
-
-describe("buffer.INSPECT_MAX_BYTES", () => {
- const rangeErrorObjs = [NaN, -1];
- const typeErrorObj = "and even this";
-
- test.each(rangeErrorObjs)("throws RangeError for invalid value: %p", obj => {
- expect(() => {
- buffer.INSPECT_MAX_BYTES = obj;
- }).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: expect.any(String),
- }),
- );
- });
-
- test("throws TypeError for invalid type", () => {
- expect(() => {
- buffer.INSPECT_MAX_BYTES = typeErrorObj;
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-buffer-set-inspect-max-bytes.js
diff --git a/test/js/node/test/parallel/buffer-slice.test.js b/test/js/node/test/parallel/buffer-slice.test.js
deleted file mode 100644
index 5fde7bdf62..0000000000
--- a/test/js/node/test/parallel/buffer-slice.test.js
+++ /dev/null
@@ -1,114 +0,0 @@
-//#FILE: test-buffer-slice.js
-//#SHA1: 1f7289de3a6dd5167f3659cd5119e6489b059d43
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-test("Buffer slice operations", () => {
- expect(Buffer.from("hello", "utf8").slice(0, 0).length).toBe(0);
- expect(Buffer("hello", "utf8").slice(0, 0).length).toBe(0);
-
- const buf = Buffer.from("0123456789", "utf8");
- const expectedSameBufs = [
- [buf.slice(-10, 10), Buffer.from("0123456789", "utf8")],
- [buf.slice(-20, 10), Buffer.from("0123456789", "utf8")],
- [buf.slice(-20, -10), Buffer.from("", "utf8")],
- [buf.slice(), Buffer.from("0123456789", "utf8")],
- [buf.slice(0), Buffer.from("0123456789", "utf8")],
- [buf.slice(0, 0), Buffer.from("", "utf8")],
- [buf.slice(undefined), Buffer.from("0123456789", "utf8")],
- [buf.slice("foobar"), Buffer.from("0123456789", "utf8")],
- [buf.slice(undefined, undefined), Buffer.from("0123456789", "utf8")],
- [buf.slice(2), Buffer.from("23456789", "utf8")],
- [buf.slice(5), Buffer.from("56789", "utf8")],
- [buf.slice(10), Buffer.from("", "utf8")],
- [buf.slice(5, 8), Buffer.from("567", "utf8")],
- [buf.slice(8, -1), Buffer.from("8", "utf8")],
- [buf.slice(-10), Buffer.from("0123456789", "utf8")],
- [buf.slice(0, -9), Buffer.from("0", "utf8")],
- [buf.slice(0, -10), Buffer.from("", "utf8")],
- [buf.slice(0, -1), Buffer.from("012345678", "utf8")],
- [buf.slice(2, -2), Buffer.from("234567", "utf8")],
- [buf.slice(0, 65536), Buffer.from("0123456789", "utf8")],
- [buf.slice(65536, 0), Buffer.from("", "utf8")],
- [buf.slice(-5, -8), Buffer.from("", "utf8")],
- [buf.slice(-5, -3), Buffer.from("56", "utf8")],
- [buf.slice(-10, 10), Buffer.from("0123456789", "utf8")],
- [buf.slice("0", "1"), Buffer.from("0", "utf8")],
- [buf.slice("-5", "10"), Buffer.from("56789", "utf8")],
- [buf.slice("-10", "10"), Buffer.from("0123456789", "utf8")],
- [buf.slice("-10", "-5"), Buffer.from("01234", "utf8")],
- [buf.slice("-10", "-0"), Buffer.from("", "utf8")],
- [buf.slice("111"), Buffer.from("", "utf8")],
- [buf.slice("0", "-111"), Buffer.from("", "utf8")],
- ];
-
- for (let i = 0, s = buf.toString(); i < buf.length; ++i) {
- expectedSameBufs.push(
- [buf.slice(i), Buffer.from(s.slice(i))],
- [buf.slice(0, i), Buffer.from(s.slice(0, i))],
- [buf.slice(-i), Buffer.from(s.slice(-i))],
- [buf.slice(0, -i), Buffer.from(s.slice(0, -i))],
- );
- }
-
- for (const [buf1, buf2] of expectedSameBufs) {
- expect(Buffer.compare(buf1, buf2)).toBe(0);
- }
-
- const utf16Buf = Buffer.from("0123456789", "utf16le");
- expect(utf16Buf.slice(0, 6)).toStrictEqual(Buffer.from("012", "utf16le"));
-
- // Try to slice a zero length Buffer.
- // See https://github.com/joyent/node/issues/5881
- expect(Buffer.alloc(0).slice(0, 1).length).toBe(0);
-
- // Single argument slice
- expect(Buffer.from("abcde", "utf8").slice(1).toString("utf8")).toBe("bcde");
-
- // slice(0,0).length === 0
- expect(Buffer.from("hello", "utf8").slice(0, 0).length).toBe(0);
-
- // Regression tests for https://github.com/nodejs/node/issues/9096
- const regressionBuf = Buffer.from("abcd", "utf8");
- expect(regressionBuf.slice(regressionBuf.length / 3).toString("utf8")).toBe("bcd");
- expect(regressionBuf.slice(regressionBuf.length / 3, regressionBuf.length).toString()).toBe("bcd");
-
- const largeSliceBuf = Buffer.from("abcdefg", "utf8");
- expect(largeSliceBuf.slice(-(-1 >>> 0) - 1).toString("utf8")).toBe(largeSliceBuf.toString("utf8"));
-
- const floatSliceBuf = Buffer.from("abc", "utf8");
- expect(floatSliceBuf.slice(-0.5).toString("utf8")).toBe(floatSliceBuf.toString("utf8"));
-
- const complexBuf = Buffer.from([
- 1, 29, 0, 0, 1, 143, 216, 162, 92, 254, 248, 63, 0, 0, 0, 18, 184, 6, 0, 175, 29, 0, 8, 11, 1, 0, 0,
- ]);
- const chunk1 = Buffer.from([1, 29, 0, 0, 1, 143, 216, 162, 92, 254, 248, 63, 0]);
- const chunk2 = Buffer.from([0, 0, 18, 184, 6, 0, 175, 29, 0, 8, 11, 1, 0, 0]);
- const middle = complexBuf.length / 2;
-
- expect(complexBuf.slice(0, middle)).toStrictEqual(chunk1);
- expect(complexBuf.slice(middle)).toStrictEqual(chunk2);
-});
-
-//<#END_FILE: test-buffer-slice.js
diff --git a/test/js/node/test/parallel/buffer-slow.test.js b/test/js/node/test/parallel/buffer-slow.test.js
deleted file mode 100644
index 85f35f68e6..0000000000
--- a/test/js/node/test/parallel/buffer-slow.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-buffer-slow.js
-//#SHA1: fadf639fe26752f00488a41a29f1977f95fc1c79
-//-----------------
-"use strict";
-
-const buffer = require("buffer");
-const SlowBuffer = buffer.SlowBuffer;
-
-const ones = [1, 1, 1, 1];
-
-test("SlowBuffer should create a Buffer", () => {
- let sb = SlowBuffer(4);
- expect(sb).toBeInstanceOf(Buffer);
- expect(sb.length).toBe(4);
- sb.fill(1);
- for (const [key, value] of sb.entries()) {
- expect(value).toBe(ones[key]);
- }
-
- // underlying ArrayBuffer should have the same length
- expect(sb.buffer.byteLength).toBe(4);
-});
-
-test("SlowBuffer should work without new", () => {
- let sb = SlowBuffer(4);
- expect(sb).toBeInstanceOf(Buffer);
- expect(sb.length).toBe(4);
- sb.fill(1);
- for (const [key, value] of sb.entries()) {
- expect(value).toBe(ones[key]);
- }
-});
-
-test("SlowBuffer should work with edge cases", () => {
- expect(SlowBuffer(0).length).toBe(0);
-});
-
-test("SlowBuffer should throw with invalid length type", () => {
- const bufferInvalidTypeMsg = expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- });
-
- expect(() => SlowBuffer()).toThrow(bufferInvalidTypeMsg);
- expect(() => SlowBuffer({})).toThrow(bufferInvalidTypeMsg);
- expect(() => SlowBuffer("6")).toThrow(bufferInvalidTypeMsg);
- expect(() => SlowBuffer(true)).toThrow(bufferInvalidTypeMsg);
-});
-
-test("SlowBuffer should throw with invalid length value", () => {
- const bufferMaxSizeMsg = expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: expect.any(String),
- });
-
- expect(() => SlowBuffer(NaN)).toThrow(bufferMaxSizeMsg);
- expect(() => SlowBuffer(Infinity)).toThrow(bufferMaxSizeMsg);
- expect(() => SlowBuffer(-1)).toThrow(bufferMaxSizeMsg);
- expect(() => SlowBuffer(buffer.kMaxLength + 1)).toThrow(bufferMaxSizeMsg);
-});
-
-//<#END_FILE: test-buffer-slow.js
diff --git a/test/js/node/test/parallel/buffer-swap.test.js b/test/js/node/test/parallel/buffer-swap.test.js
deleted file mode 100644
index 89eef58dce..0000000000
--- a/test/js/node/test/parallel/buffer-swap.test.js
+++ /dev/null
@@ -1,153 +0,0 @@
-//#FILE: test-buffer-swap.js
-//#SHA1: 589e4ee82ab5f00e1cffdd4d326e21cc2f06b065
-//-----------------
-"use strict";
-
-describe("Buffer swap operations", () => {
- test("Test buffers small enough to use the JS implementation", () => {
- const buf = Buffer.from([
- 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
- ]);
-
- expect(buf.swap16()).toBe(buf);
- expect(buf).toEqual(
- Buffer.from([0x02, 0x01, 0x04, 0x03, 0x06, 0x05, 0x08, 0x07, 0x0a, 0x09, 0x0c, 0x0b, 0x0e, 0x0d, 0x10, 0x0f]),
- );
- buf.swap16(); // restore
-
- expect(buf.swap32()).toBe(buf);
- expect(buf).toEqual(
- Buffer.from([0x04, 0x03, 0x02, 0x01, 0x08, 0x07, 0x06, 0x05, 0x0c, 0x0b, 0x0a, 0x09, 0x10, 0x0f, 0x0e, 0x0d]),
- );
- buf.swap32(); // restore
-
- expect(buf.swap64()).toBe(buf);
- expect(buf).toEqual(
- Buffer.from([0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x10, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09]),
- );
- });
-
- test("Operates in-place", () => {
- const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7]);
- buf.slice(1, 5).swap32();
- expect(buf).toEqual(Buffer.from([0x1, 0x5, 0x4, 0x3, 0x2, 0x6, 0x7]));
- buf.slice(1, 5).swap16();
- expect(buf).toEqual(Buffer.from([0x1, 0x4, 0x5, 0x2, 0x3, 0x6, 0x7]));
-
- // Length assertions
- const re16 = /Buffer size must be a multiple of 16-bits/;
- const re32 = /Buffer size must be a multiple of 32-bits/;
- const re64 = /Buffer size must be a multiple of 64-bits/;
-
- expect(() => Buffer.from(buf).swap16()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- expect(() => Buffer.alloc(1025).swap16()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- expect(() => Buffer.from(buf).swap32()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- expect(() => buf.slice(1, 3).swap32()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- expect(() => Buffer.alloc(1025).swap32()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- expect(() => buf.slice(1, 3).swap64()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- expect(() => Buffer.alloc(1025).swap64()).toThrow(expect.objectContaining({ message: expect.any(String) }));
- });
-
- test("Swap64 on a slice", () => {
- const buf = Buffer.from([
- 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x01, 0x02, 0x03,
- 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
- ]);
-
- buf.slice(2, 18).swap64();
-
- expect(buf).toEqual(
- Buffer.from([
- 0x01, 0x02, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x10, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b,
- 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
- ]),
- );
- });
-
- test("Force use of native code (Buffer size above threshold limit for js impl)", () => {
- const bufData = new Uint32Array(256).fill(0x04030201);
- const buf = Buffer.from(bufData.buffer, bufData.byteOffset);
- const otherBufData = new Uint32Array(256).fill(0x03040102);
- const otherBuf = Buffer.from(otherBufData.buffer, otherBufData.byteOffset);
- buf.swap16();
- expect(buf).toEqual(otherBuf);
- });
-
- test("Force use of native code for swap32", () => {
- const bufData = new Uint32Array(256).fill(0x04030201);
- const buf = Buffer.from(bufData.buffer);
- const otherBufData = new Uint32Array(256).fill(0x01020304);
- const otherBuf = Buffer.from(otherBufData.buffer, otherBufData.byteOffset);
- buf.swap32();
- expect(buf).toEqual(otherBuf);
- });
-
- test("Force use of native code for swap64", () => {
- const bufData = new Uint8Array(256 * 8);
- const otherBufData = new Uint8Array(256 * 8);
- for (let i = 0; i < bufData.length; i++) {
- bufData[i] = i % 8;
- otherBufData[otherBufData.length - i - 1] = i % 8;
- }
- const buf = Buffer.from(bufData.buffer, bufData.byteOffset);
- const otherBuf = Buffer.from(otherBufData.buffer, otherBufData.byteOffset);
- buf.swap64();
- expect(buf).toEqual(otherBuf);
- });
-
- test("Test native code with buffers that are not memory-aligned (swap16)", () => {
- const bufData = new Uint8Array(256 * 8);
- const otherBufData = new Uint8Array(256 * 8 - 2);
- for (let i = 0; i < bufData.length; i++) {
- bufData[i] = i % 2;
- }
- for (let i = 1; i < otherBufData.length; i++) {
- otherBufData[otherBufData.length - i] = (i + 1) % 2;
- }
- const buf = Buffer.from(bufData.buffer, bufData.byteOffset);
- // 0|1 0|1 0|1...
- const otherBuf = Buffer.from(otherBufData.buffer, otherBufData.byteOffset);
- // 0|0 1|0 1|0...
-
- buf.slice(1, buf.length - 1).swap16();
- expect(buf.slice(0, otherBuf.length)).toEqual(otherBuf);
- });
-
- test("Test native code with buffers that are not memory-aligned (swap32)", () => {
- const bufData = new Uint8Array(256 * 8);
- const otherBufData = new Uint8Array(256 * 8 - 4);
- for (let i = 0; i < bufData.length; i++) {
- bufData[i] = i % 4;
- }
- for (let i = 1; i < otherBufData.length; i++) {
- otherBufData[otherBufData.length - i] = (i + 1) % 4;
- }
- const buf = Buffer.from(bufData.buffer, bufData.byteOffset);
- // 0|1 2 3 0|1 2 3...
- const otherBuf = Buffer.from(otherBufData.buffer, otherBufData.byteOffset);
- // 0|0 3 2 1|0 3 2...
-
- buf.slice(1, buf.length - 3).swap32();
- expect(buf.slice(0, otherBuf.length)).toEqual(otherBuf);
- });
-
- test("Test native code with buffers that are not memory-aligned (swap64)", () => {
- const bufData = new Uint8Array(256 * 8);
- const otherBufData = new Uint8Array(256 * 8 - 8);
- for (let i = 0; i < bufData.length; i++) {
- bufData[i] = i % 8;
- }
- for (let i = 1; i < otherBufData.length; i++) {
- otherBufData[otherBufData.length - i] = (i + 1) % 8;
- }
- const buf = Buffer.from(bufData.buffer, bufData.byteOffset);
- // 0|1 2 3 4 5 6 7 0|1 2 3 4...
- const otherBuf = Buffer.from(otherBufData.buffer, otherBufData.byteOffset);
- // 0|0 7 6 5 4 3 2 1|0 7 6 5...
-
- buf.slice(1, buf.length - 7).swap64();
- expect(buf.slice(0, otherBuf.length)).toEqual(otherBuf);
- });
-});
-
-//<#END_FILE: test-buffer-swap.js
diff --git a/test/js/node/test/parallel/buffer-tostring-range.test.js b/test/js/node/test/parallel/buffer-tostring-range.test.js
deleted file mode 100644
index a1e72ba714..0000000000
--- a/test/js/node/test/parallel/buffer-tostring-range.test.js
+++ /dev/null
@@ -1,115 +0,0 @@
-//#FILE: test-buffer-tostring-range.js
-//#SHA1: 2bc09c70e84191e47ae345cc3178f28458b10ec2
-//-----------------
-"use strict";
-
-const rangeBuffer = Buffer.from("abc");
-
-test("Buffer.toString range behavior", () => {
- // If start >= buffer's length, empty string will be returned
- expect(rangeBuffer.toString("ascii", 3)).toBe("");
- expect(rangeBuffer.toString("ascii", +Infinity)).toBe("");
- expect(rangeBuffer.toString("ascii", 3.14, 3)).toBe("");
- expect(rangeBuffer.toString("ascii", "Infinity", 3)).toBe("");
-
- // If end <= 0, empty string will be returned
- expect(rangeBuffer.toString("ascii", 1, 0)).toBe("");
- expect(rangeBuffer.toString("ascii", 1, -1.2)).toBe("");
- expect(rangeBuffer.toString("ascii", 1, -100)).toBe("");
- expect(rangeBuffer.toString("ascii", 1, -Infinity)).toBe("");
-
- // If start < 0, start will be taken as zero
- expect(rangeBuffer.toString("ascii", -1, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", -1.99, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", -Infinity, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", "-1", 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", "-1.99", 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", "-Infinity", 3)).toBe("abc");
-
- // If start is an invalid integer, start will be taken as zero
- expect(rangeBuffer.toString("ascii", "node.js", 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", {}, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", [], 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", NaN, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", null, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", undefined, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", false, 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", "", 3)).toBe("abc");
-
- // But, if start is an integer when coerced, then it will be coerced and used.
- expect(rangeBuffer.toString("ascii", "-1", 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", "1", 3)).toBe("bc");
- expect(rangeBuffer.toString("ascii", "-Infinity", 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", "3", 3)).toBe("");
- expect(rangeBuffer.toString("ascii", Number(3), 3)).toBe("");
- expect(rangeBuffer.toString("ascii", "3.14", 3)).toBe("");
- expect(rangeBuffer.toString("ascii", "1.99", 3)).toBe("bc");
- expect(rangeBuffer.toString("ascii", "-1.99", 3)).toBe("abc");
- expect(rangeBuffer.toString("ascii", 1.99, 3)).toBe("bc");
- expect(rangeBuffer.toString("ascii", true, 3)).toBe("bc");
-
- // If end > buffer's length, end will be taken as buffer's length
- expect(rangeBuffer.toString("ascii", 0, 5)).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, 6.99)).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, Infinity)).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, "5")).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, "6.99")).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, "Infinity")).toBe("abc");
-
- // If end is an invalid integer, end will be taken as buffer's length
- expect(rangeBuffer.toString("ascii", 0, "node.js")).toBe("");
- expect(rangeBuffer.toString("ascii", 0, {})).toBe("");
- expect(rangeBuffer.toString("ascii", 0, NaN)).toBe("");
- expect(rangeBuffer.toString("ascii", 0, undefined)).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0)).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, null)).toBe("");
- expect(rangeBuffer.toString("ascii", 0, [])).toBe("");
- expect(rangeBuffer.toString("ascii", 0, false)).toBe("");
- expect(rangeBuffer.toString("ascii", 0, "")).toBe("");
-
- // But, if end is an integer when coerced, then it will be coerced and used.
- expect(rangeBuffer.toString("ascii", 0, "-1")).toBe("");
- expect(rangeBuffer.toString("ascii", 0, "1")).toBe("a");
- expect(rangeBuffer.toString("ascii", 0, "-Infinity")).toBe("");
- expect(rangeBuffer.toString("ascii", 0, "3")).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, Number(3))).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, "3.14")).toBe("abc");
- expect(rangeBuffer.toString("ascii", 0, "1.99")).toBe("a");
- expect(rangeBuffer.toString("ascii", 0, "-1.99")).toBe("");
- expect(rangeBuffer.toString("ascii", 0, 1.99)).toBe("a");
- expect(rangeBuffer.toString("ascii", 0, true)).toBe("a");
-});
-
-test("toString() with an object as an encoding", () => {
- expect(
- rangeBuffer.toString({
- toString: function () {
- return "ascii";
- },
- }),
- ).toBe("abc");
-});
-
-test("toString() with 0 and null as the encoding", () => {
- expect(() => {
- rangeBuffer.toString(0, 1, 2);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_UNKNOWN_ENCODING",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-
- expect(() => {
- rangeBuffer.toString(null, 1, 2);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_UNKNOWN_ENCODING",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-buffer-tostring-range.js
diff --git a/test/js/node/test/parallel/buffer-tostring-rangeerror.test.js b/test/js/node/test/parallel/buffer-tostring-rangeerror.test.js
deleted file mode 100644
index 0e88759c45..0000000000
--- a/test/js/node/test/parallel/buffer-tostring-rangeerror.test.js
+++ /dev/null
@@ -1,30 +0,0 @@
-//#FILE: test-buffer-tostring-rangeerror.js
-//#SHA1: c5bd04a7b4f3b7ecfb3898262dd73da29a9ad162
-//-----------------
-"use strict";
-
-// This test ensures that Node.js throws an Error when trying to convert a
-// large buffer into a string.
-// Regression test for https://github.com/nodejs/node/issues/649.
-
-const {
- SlowBuffer,
- constants: { MAX_STRING_LENGTH },
-} = require("buffer");
-
-const len = MAX_STRING_LENGTH + 1;
-const errorMatcher = expect.objectContaining({
- code: "ERR_STRING_TOO_LONG",
- name: "Error",
- message: `Cannot create a string longer than 2147483647 characters`,
-});
-
-test("Buffer toString with large buffer throws RangeError", () => {
- expect(() => Buffer(len).toString("utf8")).toThrow(errorMatcher);
- expect(() => SlowBuffer(len).toString("utf8")).toThrow(errorMatcher);
- expect(() => Buffer.alloc(len).toString("utf8")).toThrow(errorMatcher);
- expect(() => Buffer.allocUnsafe(len).toString("utf8")).toThrow(errorMatcher);
- expect(() => Buffer.allocUnsafeSlow(len).toString("utf8")).toThrow(errorMatcher);
-});
-
-//<#END_FILE: test-buffer-tostring-rangeerror.js
diff --git a/test/js/node/test/parallel/buffer-tostring.test.js b/test/js/node/test/parallel/buffer-tostring.test.js
deleted file mode 100644
index eb48074506..0000000000
--- a/test/js/node/test/parallel/buffer-tostring.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-buffer-tostring.js
-//#SHA1: 0a6490b6dd4c343c01828d1c4ff81b745b6b1552
-//-----------------
-"use strict";
-
-// utf8, ucs2, ascii, latin1, utf16le
-const encodings = ["utf8", "utf-8", "ucs2", "ucs-2", "ascii", "latin1", "binary", "utf16le", "utf-16le"];
-
-test("Buffer.from().toString() with various encodings", () => {
- encodings
- .reduce((es, e) => es.concat(e, e.toUpperCase()), [])
- .forEach(encoding => {
- expect(Buffer.from("foo", encoding).toString(encoding)).toBe("foo");
- });
-});
-
-test("Buffer.from().toString() with base64 encoding", () => {
- ["base64", "BASE64"].forEach(encoding => {
- expect(Buffer.from("Zm9v", encoding).toString(encoding)).toBe("Zm9v");
- });
-});
-
-test("Buffer.from().toString() with hex encoding", () => {
- ["hex", "HEX"].forEach(encoding => {
- expect(Buffer.from("666f6f", encoding).toString(encoding)).toBe("666f6f");
- });
-});
-
-test("Buffer.from().toString() with invalid encodings", () => {
- for (let i = 1; i < 10; i++) {
- const encoding = String(i).repeat(i);
- expect(Buffer.isEncoding(encoding)).toBe(false);
- expect(() => Buffer.from("foo").toString(encoding)).toThrow(
- expect.objectContaining({
- code: "ERR_UNKNOWN_ENCODING",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- }
-});
-
-//<#END_FILE: test-buffer-tostring.js
diff --git a/test/js/node/test/parallel/buffer-write.test.js b/test/js/node/test/parallel/buffer-write.test.js
deleted file mode 100644
index ceb7123d5f..0000000000
--- a/test/js/node/test/parallel/buffer-write.test.js
+++ /dev/null
@@ -1,119 +0,0 @@
-//#FILE: test-buffer-write.js
-//#SHA1: 9577e31a533888b164b0abf4ebececbe04e381cb
-//-----------------
-"use strict";
-
-[-1, 10].forEach(offset => {
- test(`Buffer.alloc(9).write('foo', ${offset}) throws RangeError`, () => {
- expect(() => Buffer.alloc(9).write("foo", offset)).toThrow(
- expect.objectContaining({
- code: "ERR_OUT_OF_RANGE",
- name: "RangeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-const resultMap = new Map([
- ["utf8", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
- ["ucs2", Buffer.from([102, 0, 111, 0, 111, 0, 0, 0, 0])],
- ["ascii", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
- ["latin1", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
- ["binary", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
- ["utf16le", Buffer.from([102, 0, 111, 0, 111, 0, 0, 0, 0])],
- ["base64", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
- ["base64url", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
- ["hex", Buffer.from([102, 111, 111, 0, 0, 0, 0, 0, 0])],
-]);
-
-// utf8, ucs2, ascii, latin1, utf16le
-const encodings = ["utf8", "utf-8", "ucs2", "ucs-2", "ascii", "latin1", "binary", "utf16le", "utf-16le"];
-
-encodings
- .reduce((es, e) => es.concat(e, e.toUpperCase()), [])
- .forEach(encoding => {
- test(`Buffer.write with encoding ${encoding}`, () => {
- const buf = Buffer.alloc(9);
- const len = Buffer.byteLength("foo", encoding);
- expect(buf.write("foo", 0, len, encoding)).toBe(len);
-
- if (encoding.includes("-")) encoding = encoding.replace("-", "");
-
- expect(buf).toEqual(resultMap.get(encoding.toLowerCase()));
- });
- });
-
-// base64
-["base64", "BASE64", "base64url", "BASE64URL"].forEach(encoding => {
- test(`Buffer.write with encoding ${encoding}`, () => {
- const buf = Buffer.alloc(9);
- const len = Buffer.byteLength("Zm9v", encoding);
-
- expect(buf.write("Zm9v", 0, len, encoding)).toBe(len);
- expect(buf).toEqual(resultMap.get(encoding.toLowerCase()));
- });
-});
-
-// hex
-["hex", "HEX"].forEach(encoding => {
- test(`Buffer.write with encoding ${encoding}`, () => {
- const buf = Buffer.alloc(9);
- const len = Buffer.byteLength("666f6f", encoding);
-
- expect(buf.write("666f6f", 0, len, encoding)).toBe(len);
- expect(buf).toEqual(resultMap.get(encoding.toLowerCase()));
- });
-});
-
-// Invalid encodings
-for (let i = 1; i < 10; i++) {
- const encoding = String(i).repeat(i);
-
- test(`Invalid encoding ${encoding}`, () => {
- expect(Buffer.isEncoding(encoding)).toBe(false);
- expect(() => Buffer.alloc(9).write("foo", encoding)).toThrow(
- expect.objectContaining({
- code: "ERR_UNKNOWN_ENCODING",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-}
-
-// UCS-2 overflow CVE-2018-12115
-for (let i = 1; i < 4; i++) {
- test(`UCS-2 overflow test ${i}`, () => {
- // Allocate two Buffers sequentially off the pool. Run more than once in case
- // we hit the end of the pool and don't get sequential allocations
- const x = Buffer.allocUnsafe(4).fill(0);
- const y = Buffer.allocUnsafe(4).fill(1);
- // Should not write anything, pos 3 doesn't have enough room for a 16-bit char
- expect(x.write("ыыыыыы", 3, "ucs2")).toBe(0);
- // CVE-2018-12115 experienced via buffer overrun to next block in the pool
- expect(Buffer.compare(y, Buffer.alloc(4, 1))).toBe(0);
- });
-}
-
-test("Should not write any data when there is no space for 16-bit chars", () => {
- const z = Buffer.alloc(4, 0);
- expect(z.write("\u0001", 3, "ucs2")).toBe(0);
- expect(Buffer.compare(z, Buffer.alloc(4, 0))).toBe(0);
- // Make sure longer strings are written up to the buffer end.
- expect(z.write("abcd", 2)).toBe(2);
- expect([...z]).toEqual([0, 0, 0x61, 0x62]);
-});
-
-test("Large overrun should not corrupt the process", () => {
- expect(Buffer.alloc(4).write("ыыыыыы".repeat(100), 3, "utf16le")).toBe(0);
-});
-
-test(".write() does not affect the byte after the written-to slice of the Buffer", () => {
- // Refs: https://github.com/nodejs/node/issues/26422
- const buf = Buffer.alloc(8);
- expect(buf.write("ыы", 1, "utf16le")).toBe(4);
- expect([...buf]).toEqual([0, 0x4b, 0x04, 0x4b, 0x04, 0, 0, 0]);
-});
-
-//<#END_FILE: test-buffer-write.js
diff --git a/test/js/node/test/parallel/buffer-zero-fill-reset.test.js b/test/js/node/test/parallel/buffer-zero-fill-reset.test.js
deleted file mode 100644
index d4055fb35a..0000000000
--- a/test/js/node/test/parallel/buffer-zero-fill-reset.test.js
+++ /dev/null
@@ -1,20 +0,0 @@
-//#FILE: test-buffer-zero-fill-reset.js
-//#SHA1: 2278dd06a2e113e875c1f0f46580c0fcc4fc5254
-//-----------------
-"use strict";
-
-test("Uint8Array is zero-filled after Buffer.alloc(0)", () => {
- function testUint8Array(ui) {
- const length = ui.length;
- for (let i = 0; i < length; i++) if (ui[i] !== 0) return false;
- return true;
- }
-
- for (let i = 0; i < 100; i++) {
- Buffer.alloc(0);
- const ui = new Uint8Array(65);
- expect(testUint8Array(ui)).toBe(true);
- }
-});
-
-//<#END_FILE: test-buffer-zero-fill-reset.js
diff --git a/test/js/node/test/parallel/buffer-zero-fill.test.js b/test/js/node/test/parallel/buffer-zero-fill.test.js
deleted file mode 100644
index 003b4ffe08..0000000000
--- a/test/js/node/test/parallel/buffer-zero-fill.test.js
+++ /dev/null
@@ -1,20 +0,0 @@
-//#FILE: test-buffer-zero-fill.js
-//#SHA1: b710e0c9405c90f7526cf0efabd4c61ede37b1f7
-//-----------------
-"use strict";
-
-// Tests deprecated Buffer API on purpose
-test("Buffer zero-fill", () => {
- const buf1 = Buffer(100);
- const buf2 = new Buffer(100);
-
- for (let n = 0; n < buf1.length; n++) {
- expect(buf1[n]).toBe(0);
- }
-
- for (let n = 0; n < buf2.length; n++) {
- expect(buf2[n]).toBe(0);
- }
-});
-
-//<#END_FILE: test-buffer-zero-fill.js
diff --git a/test/js/node/test/parallel/child-process-exec-encoding.test.js b/test/js/node/test/parallel/child-process-exec-encoding.test.js
deleted file mode 100644
index 46ae2d5276..0000000000
--- a/test/js/node/test/parallel/child-process-exec-encoding.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-child-process-exec-encoding.js
-//#SHA1: 3ad6878126678aa6ad2c38a43264e5684dae6a72
-//-----------------
-"use strict";
-
-const stdoutData = "foo";
-const stderrData = "bar";
-
-if (process.argv[2] === "child") {
- // The following console calls are part of the test.
- console.log(stdoutData);
- console.error(stderrData);
-} else {
- const cp = require("child_process");
- const expectedStdout = `${stdoutData}\n`;
- const expectedStderr = `${stderrData}\n`;
-
- function run(options) {
- const cmd = `"${process.execPath}" "${__filename}" child`;
-
- return new Promise((resolve, reject) => {
- cp.exec(cmd, options, (error, stdout, stderr) => {
- if (error) {
- reject(error);
- } else {
- resolve({ stdout, stderr });
- }
- });
- });
- }
-
- test("Test default encoding, which should be utf8", async () => {
- const { stdout, stderr } = await run({});
- expect(typeof stdout).toBe("string");
- expect(typeof stderr).toBe("string");
- expect(stdout).toBe(expectedStdout);
- expect(stderr).toBe(expectedStderr);
- });
-
- test("Test explicit utf8 encoding", async () => {
- const { stdout, stderr } = await run({ encoding: "utf8" });
- expect(typeof stdout).toBe("string");
- expect(typeof stderr).toBe("string");
- expect(stdout).toBe(expectedStdout);
- expect(stderr).toBe(expectedStderr);
- });
-
- test("Test cases that result in buffer encodings", async () => {
- const encodings = [undefined, null, "buffer", "invalid"];
-
- for (const encoding of encodings) {
- const { stdout, stderr } = await run({ encoding });
- expect(stdout).toBeInstanceOf(Buffer);
- expect(stderr).toBeInstanceOf(Buffer);
- expect(stdout.toString()).toBe(expectedStdout);
- expect(stderr.toString()).toBe(expectedStderr);
- }
- });
-}
-
-//<#END_FILE: test-child-process-exec-encoding.js
diff --git a/test/js/node/test/parallel/child-process-exec-env.test.js b/test/js/node/test/parallel/child-process-exec-env.test.js
deleted file mode 100644
index 1649fad830..0000000000
--- a/test/js/node/test/parallel/child-process-exec-env.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//#FILE: test-child-process-exec-env.js
-//#SHA1: cba9b5f7a9d1ab7cd674bde00c1c4184470e4899
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const { isWindows } = require("../common");
-const { exec } = require("child_process");
-const util = require("util");
-
-const execPromise = util.promisify(exec);
-
-test("exec with custom environment", async () => {
- let command, options;
-
- if (!isWindows) {
- command = "/usr/bin/env";
- options = { env: { HELLO: "WORLD" } };
- } else {
- command = "set";
- options = { env: { ...process.env, HELLO: "WORLD" } };
- }
-
- const { stdout, stderr } = await execPromise(command, options);
-
- expect(stdout).not.toBe("");
- expect(stdout).toContain("HELLO=WORLD");
- expect(stderr).toBe("");
-});
-
-//<#END_FILE: test-child-process-exec-env.js
diff --git a/test/js/node/test/parallel/child-process-exec-kill-throws.test.js b/test/js/node/test/parallel/child-process-exec-kill-throws.test.js
deleted file mode 100644
index b0b8482f24..0000000000
--- a/test/js/node/test/parallel/child-process-exec-kill-throws.test.js
+++ /dev/null
@@ -1,46 +0,0 @@
-//#FILE: test-child-process-exec-kill-throws.js
-//#SHA1: 968879ddf3244351dea40c681343ea8defc02a0b
-//-----------------
-"use strict";
-
-const cp = require("child_process");
-
-if (process.argv[2] === "child") {
- // Since maxBuffer is 0, this should trigger an error.
- console.log("foo");
-} else {
- const originalKill = cp.ChildProcess.prototype.kill;
-
- beforeEach(() => {
- // Monkey patch ChildProcess#kill() to kill the process and then throw.
- cp.ChildProcess.prototype.kill = function () {
- originalKill.apply(this, arguments);
- throw new Error("mock error");
- };
- });
-
- afterEach(() => {
- // Restore original kill method
- cp.ChildProcess.prototype.kill = originalKill;
- });
-
- test("ChildProcess#kill() throws error", done => {
- const cmd = `"${process.execPath}" "${__filename}" child`;
- const options = { maxBuffer: 0, killSignal: "SIGKILL" };
-
- const child = cp.exec(cmd, options, (err, stdout, stderr) => {
- // Verify that if ChildProcess#kill() throws, the error is reported.
- expect(err).toEqual(
- expect.objectContaining({
- message: "mock error",
- }),
- );
- expect(stdout).toBe("");
- expect(stderr).toBe("");
- expect(child.killed).toBe(true);
- done();
- });
- });
-}
-
-//<#END_FILE: test-child-process-exec-kill-throws.js
diff --git a/test/js/node/test/parallel/child-process-exec-std-encoding.test.js b/test/js/node/test/parallel/child-process-exec-std-encoding.test.js
deleted file mode 100644
index 010bc7097e..0000000000
--- a/test/js/node/test/parallel/child-process-exec-std-encoding.test.js
+++ /dev/null
@@ -1,31 +0,0 @@
-//#FILE: test-child-process-exec-std-encoding.js
-//#SHA1: fa74583780f5256e46fd7a5ad02aed4b20bb0b76
-//-----------------
-"use strict";
-
-const cp = require("child_process");
-
-const stdoutData = "foo";
-const stderrData = "bar";
-const expectedStdout = `${stdoutData}\n`;
-const expectedStderr = `${stderrData}\n`;
-
-if (process.argv[2] === "child") {
- // The following console calls are part of the test.
- console.log(stdoutData);
- console.error(stderrData);
-} else {
- test("child process exec with stdout and stderr encoding", done => {
- const cmd = `"${process.execPath}" "${__filename}" child`;
- const child = cp.exec(cmd, (error, stdout, stderr) => {
- expect(error).toBeNull();
- expect(stdout).toBe(expectedStdout);
- expect(stderr).toBe(expectedStderr);
- done();
- });
- child.stdout.setEncoding("utf-8");
- child.stderr.setEncoding("utf-8");
- });
-}
-
-//<#END_FILE: test-child-process-exec-std-encoding.js
diff --git a/test/js/node/test/parallel/child-process-exec-stdout-stderr-data-string.test.js b/test/js/node/test/parallel/child-process-exec-stdout-stderr-data-string.test.js
deleted file mode 100644
index 42a1a555ab..0000000000
--- a/test/js/node/test/parallel/child-process-exec-stdout-stderr-data-string.test.js
+++ /dev/null
@@ -1,34 +0,0 @@
-//#FILE: test-child-process-exec-stdout-stderr-data-string.js
-//#SHA1: 342c40f3dbb506150172c2471ae228fd8632b900
-//-----------------
-"use strict";
-// Refs: https://github.com/nodejs/node/issues/7342
-const { exec } = require("child_process");
-
-const command = process.platform === "win32" ? "dir" : "ls";
-
-test("exec stdout data is called at least once", done => {
- const child = exec(command);
- const onData = jest.fn();
- child.stdout.on("data", onData);
-
- child.on("close", () => {
- expect(onData).toHaveBeenCalled();
- done();
- });
-});
-
-test("exec stderr data is called at least once and receives string", done => {
- const child = exec("fhqwhgads");
- const onData = jest.fn(data => {
- expect(typeof data).toBe("string");
- });
- child.stderr.on("data", onData);
-
- child.on("close", () => {
- expect(onData).toHaveBeenCalled();
- done();
- });
-});
-
-//<#END_FILE: test-child-process-exec-stdout-stderr-data-string.js
diff --git a/test/js/node/test/parallel/child-process-exec-timeout-kill.test.js b/test/js/node/test/parallel/child-process-exec-timeout-kill.test.js
deleted file mode 100644
index e3bc2b8e9b..0000000000
--- a/test/js/node/test/parallel/child-process-exec-timeout-kill.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-child-process-exec-timeout-kill.js
-//#SHA1: 01bc25d258b4d8905a2387e9a08b9ceb8c38c141
-//-----------------
-"use strict";
-
-// Test exec() with both a timeout and a killSignal.
-
-const cp = require("child_process");
-const path = require("path");
-
-const { kExpiringChildRunTime, kExpiringParentTimer } = require("../common/child_process");
-
-const logAfterTime = time => {
- setTimeout(() => {
- console.log(`Logged after ${time}ms`);
- }, time);
-};
-
-if (process.argv[2] === "child") {
- logAfterTime(kExpiringChildRunTime);
- process.exit(0);
-}
-
-const cmd = `"${process.execPath}" "${__filename}" child`;
-
-test("exec with timeout and killSignal", done => {
- // Test with a different kill signal.
- cp.exec(
- cmd,
- {
- timeout: kExpiringParentTimer,
- killSignal: "SIGKILL",
- },
- (err, stdout, stderr) => {
- console.log("[stdout]", stdout.trim());
- console.log("[stderr]", stderr.trim());
- expect(stdout.trim()).toBe("");
- expect(stderr.trim()).toBe("");
-
- expect(err?.killed).toBe(true);
- expect(err?.code).toBeNull();
- expect(err?.signal).toBe("SIGKILL");
- expect(err?.cmd).toBe(cmd);
- done();
- },
- );
-});
-
-//<#END_FILE: test-child-process-exec-timeout-kill.js
diff --git a/test/js/node/test/parallel/child-process-execfile-promisified-abortcontroller.test.js b/test/js/node/test/parallel/child-process-execfile-promisified-abortcontroller.test.js
deleted file mode 100644
index acebc661e9..0000000000
--- a/test/js/node/test/parallel/child-process-execfile-promisified-abortcontroller.test.js
+++ /dev/null
@@ -1,57 +0,0 @@
-//#FILE: test-child-process-execFile-promisified-abortController.js
-//#SHA1: 133445acf9aaafea4be11eb7965f222c5827f2f3
-//-----------------
-"use strict";
-
-const { promisify } = require("util");
-const execFile = require("child_process").execFile;
-const fixtures = require("../common/fixtures");
-
-const echoFixture = fixtures.path("echo.js");
-const promisified = promisify(execFile);
-const invalidArgTypeError = {
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
-};
-
-test("Verify that the signal option works properly", async () => {
- const ac = new AbortController();
- const signal = ac.signal;
- const promise = promisified(process.execPath, [echoFixture, 0], { signal });
-
- ac.abort();
-
- await expect(promise).rejects.toThrow(
- expect.objectContaining({
- name: "AbortError",
- message: expect.any(String),
- }),
- );
-});
-
-test("Verify that the signal option works properly when already aborted", async () => {
- const signal = AbortSignal.abort();
-
- await expect(promisified(process.execPath, [echoFixture, 0], { signal })).rejects.toThrow(
- expect.objectContaining({
- name: "AbortError",
- message: expect.any(String),
- }),
- );
-});
-
-test("Verify that if something different than Abortcontroller.signal is passed, ERR_INVALID_ARG_TYPE is thrown", () => {
- const signal = {};
- expect(() => {
- promisified(process.execPath, [echoFixture, 0], { signal });
- }).toThrow(expect.objectContaining(invalidArgTypeError));
-});
-
-test("Verify that if a string is passed as signal, ERR_INVALID_ARG_TYPE is thrown", () => {
- const signal = "world!";
- expect(() => {
- promisified(process.execPath, [echoFixture, 0], { signal });
- }).toThrow(expect.objectContaining(invalidArgTypeError));
-});
-
-//<#END_FILE: test-child-process-execFile-promisified-abortController.js
diff --git a/test/js/node/test/parallel/child-process-flush-stdio.test.js b/test/js/node/test/parallel/child-process-flush-stdio.test.js
deleted file mode 100644
index 53e4419b66..0000000000
--- a/test/js/node/test/parallel/child-process-flush-stdio.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-child-process-flush-stdio.js
-//#SHA1: 42d6ab8508587f13b81d2ec70d28fd88efe8fe05
-//-----------------
-"use strict";
-
-const cp = require("child_process");
-
-// Windows' `echo` command is a built-in shell command and not an external
-// executable like on *nix
-const opts = { shell: process.platform === "win32" };
-
-test("spawn echo without arguments", done => {
- const p = cp.spawn("echo", [], opts);
-
- p.on("close", (code, signal) => {
- expect(code).toBe(0);
- expect(signal).toBeNull();
- done();
- });
-
- p.stdout.read();
-});
-
-test("spawn echo with argument", done => {
- const buffer = [];
- const p = cp.spawn("echo", ["123"], opts);
-
- p.on("close", (code, signal) => {
- expect(code).toBe(0);
- expect(signal).toBeNull();
- expect(Buffer.concat(buffer).toString().trim()).toBe("123");
- done();
- });
-
- p.stdout.on("readable", () => {
- let buf;
- while ((buf = p.stdout.read()) !== null) buffer.push(buf);
- });
-});
-
-//<#END_FILE: test-child-process-flush-stdio.js
diff --git a/test/js/node/test/parallel/child-process-fork-abort-signal.test.js b/test/js/node/test/parallel/child-process-fork-abort-signal.test.js
deleted file mode 100644
index f3c1dcfe65..0000000000
--- a/test/js/node/test/parallel/child-process-fork-abort-signal.test.js
+++ /dev/null
@@ -1,115 +0,0 @@
-//#FILE: test-child-process-fork-abort-signal.js
-//#SHA1: 4805d5dd4e3cb22ffd5a21fd9d92b6ccd6bc73cf
-//-----------------
-"use strict";
-
-const fixtures = require("../common/fixtures");
-const { fork } = require("child_process");
-
-test("aborting a forked child_process after calling fork", done => {
- const ac = new AbortController();
- const { signal } = ac;
- const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), {
- signal,
- });
- cp.on("exit", (code, killSignal) => {
- expect(code).toBeNull();
- expect(killSignal).toBe("SIGTERM");
- done();
- });
- cp.on("error", err => {
- expect(err.name).toBe("AbortError");
- done();
- });
- process.nextTick(() => ac.abort());
-});
-
-test("aborting with custom error", done => {
- const ac = new AbortController();
- const { signal } = ac;
- const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), {
- signal,
- });
- cp.on("exit", (code, killSignal) => {
- expect(code).toBeNull();
- expect(killSignal).toBe("SIGTERM");
- done();
- });
- cp.on("error", err => {
- expect(err.name).toBe("AbortError");
- expect(err.cause.name).toBe("Error");
- expect(err.cause.message).toBe("boom");
- done();
- });
- process.nextTick(() => ac.abort(new Error("boom")));
-});
-
-test("passing an already aborted signal to a forked child_process", done => {
- const signal = AbortSignal.abort();
- const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), {
- signal,
- });
- cp.on("exit", (code, killSignal) => {
- expect(code).toBeNull();
- expect(killSignal).toBe("SIGTERM");
- done();
- });
- cp.on("error", err => {
- expect(err.name).toBe("AbortError");
- done();
- });
-});
-
-test("passing an aborted signal with custom error to a forked child_process", done => {
- const signal = AbortSignal.abort(new Error("boom"));
- const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), {
- signal,
- });
- cp.on("exit", (code, killSignal) => {
- expect(code).toBeNull();
- expect(killSignal).toBe("SIGTERM");
- done();
- });
- cp.on("error", err => {
- expect(err.name).toBe("AbortError");
- expect(err.cause.name).toBe("Error");
- expect(err.cause.message).toBe("boom");
- done();
- });
-});
-
-test("passing a different kill signal", done => {
- const signal = AbortSignal.abort();
- const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), {
- signal,
- killSignal: "SIGKILL",
- });
- cp.on("exit", (code, killSignal) => {
- expect(code).toBeNull();
- expect(killSignal).toBe("SIGKILL");
- done();
- });
- cp.on("error", err => {
- expect(err.name).toBe("AbortError");
- done();
- });
-});
-
-test("aborting a cp before close but after exit", done => {
- const ac = new AbortController();
- const { signal } = ac;
- const cp = fork(fixtures.path("child-process-stay-alive-forever.js"), {
- signal,
- });
- cp.on("exit", () => {
- ac.abort();
- done();
- });
- cp.on("error", () => {
- done(new Error("Should not have errored"));
- });
-
- setTimeout(() => cp.kill(), 1);
-});
-
-//<#END_FILE: test-child-process-fork-abort-signal.js
diff --git a/test/js/node/test/parallel/child-process-fork-args.test.js b/test/js/node/test/parallel/child-process-fork-args.test.js
deleted file mode 100644
index f2efa98aa5..0000000000
--- a/test/js/node/test/parallel/child-process-fork-args.test.js
+++ /dev/null
@@ -1,88 +0,0 @@
-//#FILE: test-child-process-fork-args.js
-//#SHA1: 172297ab2ed7887ced1b830b8c36d2d6a508deed
-//-----------------
-"use strict";
-const fixtures = require("../common/fixtures");
-const { fork } = require("child_process");
-
-// This test check the arguments of `fork` method
-// Refs: https://github.com/nodejs/node/issues/20749
-const expectedEnv = { foo: "bar" };
-
-// Ensure that first argument `modulePath` must be provided
-// and be of type string
-test("fork modulePath argument must be a string", () => {
- const invalidModulePath = [0, true, undefined, null, [], {}, () => {}, Symbol("t")];
- invalidModulePath.forEach(modulePath => {
- expect(() => fork(modulePath)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringMatching(/^The "modulePath" argument must be of type string/),
- }),
- );
- });
-});
-
-test("fork with valid modulePath", done => {
- const cp = fork(fixtures.path("child-process-echo-options.js"));
- cp.on("exit", code => {
- expect(code).toBe(0);
- done();
- });
-});
-
-// Ensure that the second argument of `fork`
-// and `fork` should parse options
-// correctly if args is undefined or null
-test("fork second argument validation", () => {
- const invalidSecondArgs = [0, true, () => {}, Symbol("t")];
- invalidSecondArgs.forEach(arg => {
- expect(() => {
- fork(fixtures.path("child-process-echo-options.js"), arg);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
- });
-});
-
-test("fork with valid second argument", async () => {
- const argsLists = [undefined, null, []];
-
- for (const args of argsLists) {
- const cp = fork(fixtures.path("child-process-echo-options.js"), args, {
- env: { ...process.env, ...expectedEnv },
- });
-
- await new Promise(resolve => {
- cp.on("message", ({ env }) => {
- expect(env.foo).toBe(expectedEnv.foo);
- });
-
- cp.on("exit", code => {
- expect(code).toBe(0);
- resolve();
- });
- });
- }
-});
-
-// Ensure that the third argument should be type of object if provided
-test("fork third argument must be an object if provided", () => {
- const invalidThirdArgs = [0, true, () => {}, Symbol("t")];
- invalidThirdArgs.forEach(arg => {
- expect(() => {
- fork(fixtures.path("child-process-echo-options.js"), [], arg);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
- });
-});
-
-//<#END_FILE: test-child-process-fork-args.js
diff --git a/test/js/node/test/parallel/child-process-fork-close.test.js b/test/js/node/test/parallel/child-process-fork-close.test.js
deleted file mode 100644
index d7dd94759a..0000000000
--- a/test/js/node/test/parallel/child-process-fork-close.test.js
+++ /dev/null
@@ -1,68 +0,0 @@
-//#FILE: test-child-process-fork-close.js
-//#SHA1: d196e4b4f06991be7c2a48169cb89b815c0f172b
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const { fork } = require("child_process");
-const path = require("path");
-
-test("child process fork close events", async () => {
- const cp = fork(path.resolve(__dirname, "../fixtures/child-process-message-and-exit.js"));
-
- let gotMessage = false;
- let gotExit = false;
- let gotClose = false;
-
- const messagePromise = new Promise(resolve => {
- cp.on("message", message => {
- expect(gotMessage).toBe(false);
- expect(gotClose).toBe(false);
- expect(message).toBe("hello");
- gotMessage = true;
- resolve();
- });
- });
-
- const exitPromise = new Promise(resolve => {
- cp.on("exit", () => {
- expect(gotExit).toBe(false);
- expect(gotClose).toBe(false);
- gotExit = true;
- resolve();
- });
- });
-
- const closePromise = new Promise(resolve => {
- cp.on("close", () => {
- expect(gotMessage).toBe(true);
- expect(gotExit).toBe(true);
- expect(gotClose).toBe(false);
- gotClose = true;
- resolve();
- });
- });
-
- await Promise.all([messagePromise, exitPromise, closePromise]);
-});
-
-//<#END_FILE: test-child-process-fork-close.js
diff --git a/test/js/node/test/parallel/child-process-fork-detached.test.js b/test/js/node/test/parallel/child-process-fork-detached.test.js
deleted file mode 100644
index 18c3f6a0cb..0000000000
--- a/test/js/node/test/parallel/child-process-fork-detached.test.js
+++ /dev/null
@@ -1,31 +0,0 @@
-//#FILE: test-child-process-fork-detached.js
-//#SHA1: 289d7a5f7c5d58ae50a06e7427730c57d78fe39c
-//-----------------
-"use strict";
-
-const { fork } = require("child_process");
-const path = require("path");
-
-const fixturesPath = path.resolve(__dirname, "..", "fixtures");
-
-test("fork detached child process", done => {
- const nonPersistentNode = fork(path.join(fixturesPath, "parent-process-nonpersistent-fork.js"), [], { silent: true });
-
- let childId = -1;
-
- nonPersistentNode.stdout.on("data", data => {
- childId = parseInt(data, 10);
- nonPersistentNode.kill();
- });
-
- nonPersistentNode.on("exit", () => {
- expect(childId).not.toBe(-1);
-
- // Killing the child process should not throw an error
- expect(() => process.kill(childId)).not.toThrow();
-
- done();
- });
-});
-
-//<#END_FILE: test-child-process-fork-detached.js
diff --git a/test/js/node/test/parallel/child-process-fork-ref2.test.js b/test/js/node/test/parallel/child-process-fork-ref2.test.js
deleted file mode 100644
index ecea4bfd3a..0000000000
--- a/test/js/node/test/parallel/child-process-fork-ref2.test.js
+++ /dev/null
@@ -1,69 +0,0 @@
-//#FILE: test-child-process-fork-ref2.js
-//#SHA1: 6d8a2bec4198f9d9f71ce9f2cc880cfcd1c9d883
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const { fork } = require("child_process");
-const { debuglog } = require("util");
-const debug = debuglog("test");
-
-const platformTimeout = ms => ms;
-
-if (process.argv[2] === "child") {
- test("child process", () => {
- debug("child -> call disconnect");
- process.disconnect();
-
- return new Promise(resolve => {
- setTimeout(() => {
- debug("child -> will this keep it alive?");
- const mockFn = jest.fn();
- process.on("message", mockFn);
- expect(mockFn).not.toHaveBeenCalled();
- resolve();
- }, platformTimeout(400));
- });
- });
-} else {
- test("parent process", () => {
- return new Promise(resolve => {
- const child = fork(__filename, ["child"]);
-
- const disconnectSpy = jest.fn(() => {
- debug("parent -> disconnect");
- });
- child.on("disconnect", disconnectSpy);
-
- const exitSpy = jest.fn(() => {
- debug("parent -> exit");
- expect(disconnectSpy).toHaveBeenCalledTimes(1);
- resolve();
- });
- child.once("exit", exitSpy);
-
- expect(exitSpy).toHaveBeenCalledTimes(0);
- });
- });
-}
-
-//<#END_FILE: test-child-process-fork-ref2.js
diff --git a/test/js/node/test/parallel/child-process-fork3.test.js b/test/js/node/test/parallel/child-process-fork3.test.js
deleted file mode 100644
index ab5558264a..0000000000
--- a/test/js/node/test/parallel/child-process-fork3.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-child-process-fork3.js
-//#SHA1: afa7c58bf22c64585426b2b3ec4358a415f4ff47
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const child_process = require("child_process");
-const path = require("path");
-
-test("child_process.fork should not hang", () => {
- const emptyScriptPath = path.join(__dirname, "fixtures", "empty.js");
- expect(() => {
- child_process.fork(emptyScriptPath);
- }).not.toThrow();
-});
-
-//<#END_FILE: test-child-process-fork3.js
diff --git a/test/js/node/test/parallel/child-process-kill.test.js b/test/js/node/test/parallel/child-process-kill.test.js
deleted file mode 100644
index 5a9ece5e38..0000000000
--- a/test/js/node/test/parallel/child-process-kill.test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-//#FILE: test-child-process-kill.js
-//#SHA1: 308c453d51a13e0e2c640969456c0092ab00967d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const { spawn } = require("child_process");
-const isWindows = process.platform === "win32";
-
-test("child process kill behavior", async () => {
- const cat = spawn(isWindows ? "cmd" : "cat");
-
- const stdoutEndPromise = new Promise(resolve => {
- cat.stdout.on("end", resolve);
- });
-
- const stderrDataPromise = new Promise((resolve, reject) => {
- cat.stderr.on("data", () => reject(new Error("stderr should not receive data")));
- cat.stderr.on("end", resolve);
- });
-
- const exitPromise = new Promise(resolve => {
- cat.on("exit", (code, signal) => {
- expect(code).toBeNull();
- expect(signal).toBe("SIGTERM");
- expect(cat.signalCode).toBe("SIGTERM");
- resolve();
- });
- });
-
- expect(cat.signalCode).toBeNull();
- expect(cat.killed).toBe(false);
- cat.kill();
- expect(cat.killed).toBe(true);
-
- await Promise.all([stdoutEndPromise, stderrDataPromise, exitPromise]);
-});
-
-//<#END_FILE: test-child-process-kill.js
diff --git a/test/js/node/test/parallel/child-process-send-type-error.test.js b/test/js/node/test/parallel/child-process-send-type-error.test.js
deleted file mode 100644
index cc4908b7da..0000000000
--- a/test/js/node/test/parallel/child-process-send-type-error.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-child-process-send-type-error.js
-//#SHA1: 85b82f9c15ca3d5368e22ccd1e7f44672ce2fb0c
-//-----------------
-"use strict";
-
-const cp = require("child_process");
-
-function fail(proc, args) {
- expect(() => {
- proc.send.apply(proc, args);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-}
-
-let target = process;
-
-if (process.argv[2] !== "child") {
- test("child process send type error", () => {
- target = cp.fork(__filename, ["child"]);
- target.on("exit", (code, signal) => {
- expect(code).toBe(0);
- expect(signal).toBeNull();
- });
-
- fail(target, ["msg", null, null]);
- fail(target, ["msg", null, ""]);
- fail(target, ["msg", null, "foo"]);
- fail(target, ["msg", null, 0]);
- fail(target, ["msg", null, NaN]);
- fail(target, ["msg", null, 1]);
- fail(target, ["msg", null, null, jest.fn()]);
- });
-} else {
- test("process send type error", () => {
- fail(target, ["msg", null, null]);
- fail(target, ["msg", null, ""]);
- fail(target, ["msg", null, "foo"]);
- fail(target, ["msg", null, 0]);
- fail(target, ["msg", null, NaN]);
- fail(target, ["msg", null, 1]);
- fail(target, ["msg", null, null, jest.fn()]);
- });
-}
-
-//<#END_FILE: test-child-process-send-type-error.js
diff --git a/test/js/node/test/parallel/child-process-set-blocking.test.js b/test/js/node/test/parallel/child-process-set-blocking.test.js
deleted file mode 100644
index a8288fc114..0000000000
--- a/test/js/node/test/parallel/child-process-set-blocking.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-child-process-set-blocking.js
-//#SHA1: 2855d3d616c7af61fc6b84705cd05515f02bcb47
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const { spawn } = require("child_process");
-const os = require("os");
-
-const SIZE = 100000;
-const python = process.env.PYTHON || (os.platform() === "win32" ? "python" : "python3");
-
-test("child process set blocking", done => {
- const cp = spawn(python, ["-c", `print(${SIZE} * "C")`], {
- stdio: "inherit",
- });
-
- cp.on("exit", code => {
- expect(code).toBe(0);
- done();
- });
-});
-
-//<#END_FILE: test-child-process-set-blocking.js
diff --git a/test/js/node/test/parallel/child-process-spawnsync-env.test.js b/test/js/node/test/parallel/child-process-spawnsync-env.test.js
deleted file mode 100644
index e6368f7e38..0000000000
--- a/test/js/node/test/parallel/child-process-spawnsync-env.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-child-process-spawnsync-env.js
-//#SHA1: 21ad31214e1261fb3c2636bd98d36946e5be67de
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const cp = require("child_process");
-
-if (process.argv[2] === "child") {
- console.log(process.env.foo);
-} else {
- test("spawnSync with custom environment", () => {
- const expected = "bar";
- const child = cp.spawnSync(process.execPath, [__filename, "child"], {
- env: Object.assign({}, process.env, { foo: expected }),
- });
-
- expect(child.stdout.toString().trim()).toBe(expected);
- });
-}
-
-//<#END_FILE: test-child-process-spawnsync-env.js
diff --git a/test/js/node/test/parallel/child-process-stdio-big-write-end.test.js b/test/js/node/test/parallel/child-process-stdio-big-write-end.test.js
deleted file mode 100644
index ff1ea0cc16..0000000000
--- a/test/js/node/test/parallel/child-process-stdio-big-write-end.test.js
+++ /dev/null
@@ -1,92 +0,0 @@
-//#FILE: test-child-process-stdio-big-write-end.js
-//#SHA1: 728a12ebb5484fcc628e82386c3b521ab95e0456
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const { spawn } = require("child_process");
-const assert = require("assert");
-const debug = require("util").debuglog("test");
-
-let bufsize = 0;
-
-function runParent() {
- return new Promise(resolve => {
- const child = spawn(process.execPath, [__filename, "child"]);
- let sent = 0;
-
- let n = "";
- child.stdout.setEncoding("ascii");
- child.stdout.on("data", c => {
- n += c;
- });
- child.stdout.on("end", () => {
- expect(+n).toBe(sent);
- debug("ok");
- resolve();
- });
-
- // Write until the buffer fills up.
- let buf;
- do {
- bufsize += 1024;
- buf = Buffer.alloc(bufsize, ".");
- sent += bufsize;
- } while (child.stdin.write(buf));
-
- // Then write a bunch more times.
- for (let i = 0; i < 100; i++) {
- const buf = Buffer.alloc(bufsize, ".");
- sent += bufsize;
- child.stdin.write(buf);
- }
-
- // Now end, before it's all flushed.
- child.stdin.end();
-
- // now we wait...
- });
-}
-
-function runChild() {
- return new Promise(resolve => {
- let received = 0;
- process.stdin.on("data", c => {
- received += c.length;
- });
- process.stdin.on("end", () => {
- // This console.log is part of the test.
- console.log(received);
- resolve();
- });
- });
-}
-
-if (process.argv[2] === "child") {
- runChild();
-} else {
- test("child process stdio big write end", async () => {
- await runParent();
- });
-}
-
-//<#END_FILE: test-child-process-stdio-big-write-end.js
diff --git a/test/js/node/test/parallel/child-process-stdio-overlapped.test.js b/test/js/node/test/parallel/child-process-stdio-overlapped.test.js
deleted file mode 100644
index e37232fce3..0000000000
--- a/test/js/node/test/parallel/child-process-stdio-overlapped.test.js
+++ /dev/null
@@ -1,91 +0,0 @@
-//#FILE: test-child-process-stdio-overlapped.js
-//#SHA1: 20ead82f2ea74983af7bead33605fe8f33fccf6d
-//-----------------
-// Test for "overlapped" stdio option. This test uses the "overlapped-checker"
-// helper program which basically a specialized echo program.
-//
-// The test has two goals:
-//
-// - Verify that overlapped I/O works on windows. The test program will deadlock
-// if stdin doesn't have the FILE_FLAG_OVERLAPPED flag set on startup (see
-// test/overlapped-checker/main_win.c for more details).
-// - Verify that "overlapped" stdio option works transparently as a pipe (on
-// unix/windows)
-//
-// This is how the test works:
-//
-// - This script assumes only numeric strings are written to the test program
-// stdout.
-// - The test program will be spawned with "overlapped" set on stdin and "pipe"
-// set on stdout/stderr and at startup writes a number to its stdout
-// - When this script receives some data, it will parse the number, add 50 and
-// write to the test program's stdin.
-// - The test program will then echo the number back to us which will repeat the
-// cycle until the number reaches 200, at which point we send the "exit"
-// string, which causes the test program to exit.
-// - Extra assertion: Every time the test program writes a string to its stdout,
-// it will write the number of bytes written to stderr.
-// - If overlapped I/O is not setup correctly, this test is going to hang.
-"use strict";
-const path = require("path");
-const child_process = require("child_process");
-const fs = require("fs");
-
-const exeExtension = process.platform === "win32" ? ".exe" : "";
-const exe = "overlapped-checker" + exeExtension;
-const exePath = path.join(path.dirname(process.execPath), exe);
-
-test("overlapped stdio option", async () => {
- if (!fs.existsSync(exePath)) {
- console.log(exe + " binary is not available");
- return;
- }
-
- const child = child_process.spawn(exePath, [], {
- stdio: ["overlapped", "pipe", "pipe"],
- });
-
- child.stdin.setEncoding("utf8");
- child.stdout.setEncoding("utf8");
- child.stderr.setEncoding("utf8");
-
- function writeNext(n) {
- child.stdin.write((n + 50).toString());
- }
-
- child.stdout.on("data", s => {
- const n = Number(s);
- if (n >= 200) {
- child.stdin.write("exit");
- return;
- }
- writeNext(n);
- });
-
- let stderr = "";
- child.stderr.on("data", s => {
- stderr += s;
- });
-
- await new Promise(resolve => {
- child.stderr.on("end", resolve);
- });
-
- // This is the sequence of numbers sent to us:
- // - 0 (1 byte written)
- // - 50 (2 bytes written)
- // - 100 (3 bytes written)
- // - 150 (3 bytes written)
- // - 200 (3 bytes written)
- expect(stderr).toBe("12333");
-
- const exitPromise = new Promise(resolve => {
- child.on("exit", resolve);
- });
-
- const status = await exitPromise;
- // The test program will return the number of writes as status code.
- expect(status).toBe(0);
-});
-
-//<#END_FILE: test-child-process-stdio-overlapped.js
diff --git a/test/js/node/test/parallel/cli-eval-event.test.js b/test/js/node/test/parallel/cli-eval-event.test.js
deleted file mode 100644
index 152c3da4dc..0000000000
--- a/test/js/node/test/parallel/cli-eval-event.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-//#FILE: test-cli-eval-event.js
-//#SHA1: d64fa25056a9ecf2e87e46560d477b42d3e32909
-//-----------------
-"use strict";
-
-const { spawn } = require("child_process");
-
-test("CLI eval event", () => {
- return new Promise(resolve => {
- const child = spawn(process.execPath, [
- "-e",
- `
- const server = require('net').createServer().listen(0);
- server.once('listening', server.close);
- `,
- ]);
-
- child.once("exit", (exitCode, signalCode) => {
- expect(exitCode).toBe(0);
- expect(signalCode).toBeNull();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-cli-eval-event.js
diff --git a/test/js/node/test/parallel/client-request-destroy.test.js b/test/js/node/test/parallel/client-request-destroy.test.js
deleted file mode 100644
index 165fbbdd33..0000000000
--- a/test/js/node/test/parallel/client-request-destroy.test.js
+++ /dev/null
@@ -1,19 +0,0 @@
-//#FILE: test-client-request-destroy.js
-//#SHA1: 343919bc022f2956e9aab5c9a215cbadca2364f1
-//-----------------
-"use strict";
-
-// Test that http.ClientRequest.prototype.destroy() returns `this`.
-
-const http = require("http");
-
-test("http.ClientRequest.prototype.destroy() returns `this`", () => {
- const clientRequest = new http.ClientRequest({ createConnection: () => {} });
-
- expect(clientRequest.destroyed).toBe(false);
- expect(clientRequest.destroy()).toBe(clientRequest);
- expect(clientRequest.destroyed).toBe(true);
- expect(clientRequest.destroy()).toBe(clientRequest);
-});
-
-//<#END_FILE: test-client-request-destroy.js
diff --git a/test/js/node/test/parallel/cluster-bind-privileged-port.test.js b/test/js/node/test/parallel/cluster-bind-privileged-port.test.js
deleted file mode 100644
index c83b370b56..0000000000
--- a/test/js/node/test/parallel/cluster-bind-privileged-port.test.js
+++ /dev/null
@@ -1,79 +0,0 @@
-//#FILE: test-cluster-bind-privileged-port.js
-//#SHA1: f3a12e75717db9c1a1edd4f51fb2985787a50706
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const cluster = require("cluster");
-const net = require("net");
-const { readFileSync } = require("fs");
-
-const isLinux = process.platform === "linux";
-const isOSX = process.platform === "darwin";
-const isIBMi = process.platform === "os400";
-const isWindows = process.platform === "win32";
-
-const skipTest = () => {
- test.skip("Skipping test", () => {});
- process.exit(0);
-};
-
-if (isLinux) {
- try {
- const unprivilegedPortStart = parseInt(readFileSync("/proc/sys/net/ipv4/ip_unprivileged_port_start"));
- if (unprivilegedPortStart <= 42) {
- skipTest();
- }
- } catch {
- // Do nothing, feature doesn't exist, minimum is 1024 so 42 is usable.
- // Continue...
- }
-}
-
-// Skip on OS X Mojave. https://github.com/nodejs/node/issues/21679
-if (isOSX) skipTest();
-
-if (isIBMi) skipTest();
-
-if (isWindows) skipTest();
-
-if (process.getuid() === 0) skipTest();
-
-if (cluster.isPrimary) {
- test("primary cluster process", () => {
- const worker = cluster.fork();
- worker.on("exit", exitCode => {
- expect(exitCode).toBe(0);
- });
- });
-} else {
- test("worker cluster process", () => {
- const s = net.createServer(jest.fn());
- s.listen(42, jest.fn());
- s.on("error", err => {
- expect(err.code).toBe("EACCES");
- process.disconnect();
- });
- });
-}
-
-//<#END_FILE: test-cluster-bind-privileged-port.js
diff --git a/test/js/node/test/parallel/cluster-call-and-destroy.test.js b/test/js/node/test/parallel/cluster-call-and-destroy.test.js
deleted file mode 100644
index 1e2914833f..0000000000
--- a/test/js/node/test/parallel/cluster-call-and-destroy.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-//#FILE: test-cluster-call-and-destroy.js
-//#SHA1: 840777cd738f6257dd874035b1c0291ebe16e326
-//-----------------
-"use strict";
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- test("worker disconnection and destruction", () => {
- const worker = cluster.fork();
-
- return new Promise(resolve => {
- worker.on("disconnect", () => {
- expect(worker.isConnected()).toBe(false);
- worker.destroy();
- resolve();
- });
- });
- });
-} else {
- test("worker connection in child process", () => {
- expect(cluster.worker.isConnected()).toBe(true);
- cluster.worker.disconnect();
- });
-}
-
-//<#END_FILE: test-cluster-call-and-destroy.js
diff --git a/test/js/node/test/parallel/cluster-dgram-reuse.test.js b/test/js/node/test/parallel/cluster-dgram-reuse.test.js
deleted file mode 100644
index 143db050b6..0000000000
--- a/test/js/node/test/parallel/cluster-dgram-reuse.test.js
+++ /dev/null
@@ -1,46 +0,0 @@
-//#FILE: test-cluster-dgram-reuse.js
-//#SHA1: b7bfc0764ebc95fa5ef85ce1d860aebd3f7df539
-//-----------------
-"use strict";
-
-const cluster = require("cluster");
-const dgram = require("dgram");
-
-if (process.platform === "win32") {
- test.skip("dgram clustering is currently not supported on windows.");
-} else {
- if (cluster.isPrimary) {
- test("Primary process", () => {
- const worker = cluster.fork();
- worker.on("exit", code => {
- expect(code).toBe(0);
- });
- });
- } else {
- test("Worker process", async () => {
- let waiting = 2;
- function close() {
- if (--waiting === 0) cluster.worker.disconnect();
- }
-
- const options = { type: "udp4", reuseAddr: true };
- const socket1 = dgram.createSocket(options);
- const socket2 = dgram.createSocket(options);
-
- await new Promise(resolve => {
- socket1.bind(0, () => {
- socket2.bind(socket1.address().port, () => {
- // Work around health check issue
- process.nextTick(() => {
- socket1.close(close);
- socket2.close(close);
- resolve();
- });
- });
- });
- });
- });
- }
-}
-
-//<#END_FILE: test-cluster-dgram-reuse.js
diff --git a/test/js/node/test/parallel/cluster-disconnect-idle-worker.test.js b/test/js/node/test/parallel/cluster-disconnect-idle-worker.test.js
deleted file mode 100644
index 217060fd12..0000000000
--- a/test/js/node/test/parallel/cluster-disconnect-idle-worker.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-cluster-disconnect-idle-worker.js
-//#SHA1: f559db612db77271be32bab2d7cb9a4e38f28670
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const cluster = require("cluster");
-const fork = cluster.fork;
-
-if (cluster.isPrimary) {
- test("cluster disconnect idle worker", async () => {
- fork(); // It is intentionally called `fork` instead of
- fork(); // `cluster.fork` to test that `this` is not used
-
- const disconnectCallback = jest.fn(() => {
- expect(Object.keys(cluster.workers)).toEqual([]);
- });
-
- await new Promise(resolve => {
- cluster.disconnect(() => {
- disconnectCallback();
- resolve();
- });
- });
-
- expect(disconnectCallback).toHaveBeenCalledTimes(1);
- });
-}
-
-//<#END_FILE: test-cluster-disconnect-idle-worker.js
diff --git a/test/js/node/test/parallel/cluster-disconnect-with-no-workers.test.js b/test/js/node/test/parallel/cluster-disconnect-with-no-workers.test.js
deleted file mode 100644
index 01c67b2877..0000000000
--- a/test/js/node/test/parallel/cluster-disconnect-with-no-workers.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-cluster-disconnect-with-no-workers.js
-//#SHA1: 06b4a0a662491bd9593c303307535a635d69d53e
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const cluster = require("cluster");
-
-let disconnected = false;
-
-test("cluster.disconnect with no workers", async () => {
- const disconnectPromise = new Promise(resolve => {
- cluster.disconnect(() => {
- disconnected = true;
- resolve();
- });
- });
-
- // Assert that callback is not sometimes synchronous
- expect(disconnected).toBe(false);
-
- await disconnectPromise;
-
- // Assert that the callback was called
- expect(disconnected).toBe(true);
-});
-
-//<#END_FILE: test-cluster-disconnect-with-no-workers.js
diff --git a/test/js/node/test/parallel/cluster-eaddrinuse.test.js b/test/js/node/test/parallel/cluster-eaddrinuse.test.js
deleted file mode 100644
index c72c6d6af5..0000000000
--- a/test/js/node/test/parallel/cluster-eaddrinuse.test.js
+++ /dev/null
@@ -1,94 +0,0 @@
-//#FILE: test-cluster-eaddrinuse.js
-//#SHA1: a17cbbd83e23565c1cb547999357c14f03be6efa
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// Check that having a worker bind to a port that's already taken doesn't
-// leave the primary process in a confused state. Releasing the port and
-// trying again should Just Work[TM].
-
-const { fork } = require("child_process");
-const net = require("net");
-
-const id = String(process.argv[2]);
-const port = String(process.argv[3]);
-
-if (id === "undefined") {
- test("primary process", async () => {
- const server = net.createServer(() => {
- throw new Error("Server should not receive connections");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const worker = fork(__filename, ["worker", server.address().port]);
- worker.on("message", msg => {
- if (msg !== "stop-listening") return;
- server.close(() => {
- worker.send("stopped-listening");
- });
- });
- resolve();
- });
- });
- });
-} else if (id === "worker") {
- test("worker process", async () => {
- let server = net.createServer(() => {
- throw new Error("Server should not receive connections");
- });
-
- await expect(
- new Promise((resolve, reject) => {
- server.listen(port, () => reject(new Error("Server should not listen")));
- server.on("error", resolve);
- }),
- ).resolves.toMatchObject({
- code: "EADDRINUSE",
- message: expect.any(String),
- });
-
- process.send("stop-listening");
-
- await new Promise(resolve => {
- process.once("message", msg => {
- if (msg !== "stopped-listening") return;
- server = net.createServer(() => {
- throw new Error("Server should not receive connections");
- });
- server.listen(port, () => {
- server.close();
- resolve();
- });
- });
- });
- });
-} else {
- test("invalid argument", () => {
- expect(() => {
- throw new Error("Bad argument");
- }).toThrow("Bad argument");
- });
-}
-
-//<#END_FILE: test-cluster-eaddrinuse.js
diff --git a/test/js/node/test/parallel/cluster-listen-pipe-readable-writable.test.js b/test/js/node/test/parallel/cluster-listen-pipe-readable-writable.test.js
deleted file mode 100644
index ea008eda16..0000000000
--- a/test/js/node/test/parallel/cluster-listen-pipe-readable-writable.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-//#FILE: test-cluster-listen-pipe-readable-writable.js
-//#SHA1: ec8b0021cb41214529af900b088dce4d31db708d
-//-----------------
-"use strict";
-
-const cluster = require("cluster");
-const net = require("net");
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const PIPE = path.join(os.tmpdir(), "test.sock");
-
-if (process.platform === "win32") {
- test.skip("skip on Windows", () => {});
-} else {
- if (cluster.isPrimary) {
- test("cluster worker can listen on pipe with readable and writable permissions", () => {
- const worker = cluster.fork();
- worker.on("exit", code => {
- expect(code).toBe(0);
- });
- });
- } else {
- test("server listens on pipe with correct permissions", done => {
- const server = net.createServer().listen(
- {
- path: PIPE,
- readableAll: true,
- writableAll: true,
- },
- () => {
- const stat = fs.statSync(PIPE);
- expect(stat.mode & 0o777).toBe(0o777);
- server.close();
- process.disconnect();
- done();
- },
- );
- });
- }
-}
-
-//<#END_FILE: test-cluster-listen-pipe-readable-writable.js
diff --git a/test/js/node/test/parallel/cluster-send-handle-twice.test.js b/test/js/node/test/parallel/cluster-send-handle-twice.test.js
deleted file mode 100644
index 06cb47d583..0000000000
--- a/test/js/node/test/parallel/cluster-send-handle-twice.test.js
+++ /dev/null
@@ -1,75 +0,0 @@
-//#FILE: test-cluster-send-handle-twice.js
-//#SHA1: d667e299035da70aa7831cb6964ba4e974c6bdc8
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// Testing to send an handle twice to the primary process.
-
-const cluster = require("cluster");
-const net = require("net");
-
-const workers = {
- toStart: 1,
-};
-
-if (cluster.isPrimary) {
- test("primary process", () => {
- for (let i = 0; i < workers.toStart; ++i) {
- const worker = cluster.fork();
- worker.on("exit", (code, signal) => {
- expect(code).toBe(0);
- expect(signal).toBeNull();
- });
- }
- });
-} else {
- test("worker process", async () => {
- const server = net.createServer(socket => {
- process.send("send-handle-1", socket);
- process.send("send-handle-2", socket);
- });
-
- await new Promise((resolve, reject) => {
- server.listen(0, () => {
- const client = net.connect({
- host: "localhost",
- port: server.address().port,
- });
- client.on("close", () => {
- cluster.worker.disconnect();
- resolve();
- });
- client.on("connect", () => {
- client.end();
- });
- });
-
- server.on("error", e => {
- console.error(e);
- reject(new Error("server.listen failed"));
- });
- });
- });
-}
-
-//<#END_FILE: test-cluster-send-handle-twice.js
diff --git a/test/js/node/test/parallel/cluster-setup-primary-cumulative.test.js b/test/js/node/test/parallel/cluster-setup-primary-cumulative.test.js
deleted file mode 100644
index 178c7f77ab..0000000000
--- a/test/js/node/test/parallel/cluster-setup-primary-cumulative.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-cluster-setup-primary-cumulative.js
-//#SHA1: 8a64228ac6d42c930b2426bbc53009f5d8b96a17
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const assert = require("assert");
-const cluster = require("cluster");
-
-test("cluster setup primary cumulative", () => {
- expect(cluster.isPrimary).toBe(true);
-
- // cluster.settings should not be initialized until needed
- expect(cluster.settings).toEqual({});
-
- cluster.setupPrimary();
- expect(cluster.settings).toEqual({
- args: process.argv.slice(2),
- exec: process.argv[1],
- execArgv: process.execArgv,
- silent: false,
- });
-
- cluster.setupPrimary({ exec: "overridden" });
- expect(cluster.settings.exec).toBe("overridden");
-
- cluster.setupPrimary({ args: ["foo", "bar"] });
- expect(cluster.settings.exec).toBe("overridden");
- expect(cluster.settings.args).toEqual(["foo", "bar"]);
-
- cluster.setupPrimary({ execArgv: ["baz", "bang"] });
- expect(cluster.settings.exec).toBe("overridden");
- expect(cluster.settings.args).toEqual(["foo", "bar"]);
- expect(cluster.settings.execArgv).toEqual(["baz", "bang"]);
-
- cluster.setupPrimary();
- expect(cluster.settings).toEqual({
- args: ["foo", "bar"],
- exec: "overridden",
- execArgv: ["baz", "bang"],
- silent: false,
- });
-});
-
-//<#END_FILE: test-cluster-setup-primary-cumulative.js
diff --git a/test/js/node/test/parallel/cluster-setup-primary-emit.test.js b/test/js/node/test/parallel/cluster-setup-primary-emit.test.js
deleted file mode 100644
index dc036034bd..0000000000
--- a/test/js/node/test/parallel/cluster-setup-primary-emit.test.js
+++ /dev/null
@@ -1,67 +0,0 @@
-//#FILE: test-cluster-setup-primary-emit.js
-//#SHA1: 965f86ef2ea557510e956759d3f540edfa7b03de
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const cluster = require("cluster");
-
-expect(cluster.isPrimary).toBe(true);
-
-function emitAndCatch(next) {
- return new Promise(resolve => {
- cluster.once("setup", settings => {
- expect(settings.exec).toBe("new-exec");
- setImmediate(() => {
- next();
- resolve();
- });
- });
- cluster.setupPrimary({ exec: "new-exec" });
- });
-}
-
-function emitAndCatch2(next) {
- return new Promise(resolve => {
- cluster.once("setup", settings => {
- expect(settings).toHaveProperty("exec");
- setImmediate(() => {
- next();
- resolve();
- });
- });
- cluster.setupPrimary();
- });
-}
-
-test("cluster setup primary emit", async () => {
- const nextSpy1 = jest.fn();
- const nextSpy2 = jest.fn();
-
- await emitAndCatch(nextSpy1);
- expect(nextSpy1).toHaveBeenCalledTimes(1);
-
- await emitAndCatch2(nextSpy2);
- expect(nextSpy2).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-cluster-setup-primary-emit.js
diff --git a/test/js/node/test/parallel/cluster-setup-primary-multiple.test.js b/test/js/node/test/parallel/cluster-setup-primary-multiple.test.js
deleted file mode 100644
index 05a3ca9cf5..0000000000
--- a/test/js/node/test/parallel/cluster-setup-primary-multiple.test.js
+++ /dev/null
@@ -1,78 +0,0 @@
-//#FILE: test-cluster-setup-primary-multiple.js
-//#SHA1: a0b16cb2b01b0265f98508f2a6a9974396b6b03a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const cluster = require("cluster");
-const debug = require("util").debuglog("test");
-
-test("cluster setup primary multiple times", async () => {
- expect(cluster.isPrimary).toBe(true);
-
- // The cluster.settings object is cloned even though the current implementation
- // makes that unnecessary. This is to make the test less fragile if the
- // implementation ever changes such that cluster.settings is mutated instead of
- // replaced.
- const cheapClone = obj => JSON.parse(JSON.stringify(obj));
-
- const configs = [];
-
- // Capture changes
- cluster.on("setup", () => {
- debug(`"setup" emitted ${JSON.stringify(cluster.settings)}`);
- configs.push(cheapClone(cluster.settings));
- });
-
- const execs = ["node-next", "node-next-2", "node-next-3"];
-
- // Make changes to cluster settings
- for (let i = 0; i < execs.length; i++) {
- await new Promise(resolve => {
- setTimeout(() => {
- cluster.setupPrimary({ exec: execs[i] });
- resolve();
- }, i * 100);
- });
- }
-
- // Cluster emits 'setup' asynchronously, so we must stay alive long
- // enough for that to happen
- await new Promise(resolve => {
- setTimeout(
- () => {
- debug("cluster setup complete");
- resolve();
- },
- (execs.length + 1) * 100,
- );
- });
-
- // Tests that "setup" is emitted for every call to setupPrimary
- expect(configs.length).toBe(execs.length);
-
- expect(configs[0].exec).toBe(execs[0]);
- expect(configs[1].exec).toBe(execs[1]);
- expect(configs[2].exec).toBe(execs[2]);
-});
-
-//<#END_FILE: test-cluster-setup-primary-multiple.js
diff --git a/test/js/node/test/parallel/cluster-worker-constructor.test.js b/test/js/node/test/parallel/cluster-worker-constructor.test.js
deleted file mode 100644
index 470481560e..0000000000
--- a/test/js/node/test/parallel/cluster-worker-constructor.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-cluster-worker-constructor.js
-//#SHA1: ef3237d09cf6339e487f14c40d4c047c6871ead2
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// test-cluster-worker-constructor.js
-// validates correct behavior of the cluster.Worker constructor
-
-const cluster = require("cluster");
-
-describe("cluster.Worker constructor", () => {
- test("creates a worker with default values", () => {
- const worker = new cluster.Worker();
- expect(worker.exitedAfterDisconnect).toBeUndefined();
- expect(worker.state).toBe("none");
- expect(worker.id).toBe(0);
- expect(worker.process).toBeUndefined();
- });
-
- test("creates a worker with custom values", () => {
- const worker = new cluster.Worker({
- id: 3,
- state: "online",
- process: process,
- });
- expect(worker.exitedAfterDisconnect).toBeUndefined();
- expect(worker.state).toBe("online");
- expect(worker.id).toBe(3);
- expect(worker.process).toBe(process);
- });
-
- test("creates a worker using call method", () => {
- const worker = cluster.Worker.call({}, { id: 5 });
- expect(worker).toBeInstanceOf(cluster.Worker);
- expect(worker.id).toBe(5);
- });
-});
-
-//<#END_FILE: test-cluster-worker-constructor.js
diff --git a/test/js/node/test/parallel/cluster-worker-destroy.test.js b/test/js/node/test/parallel/cluster-worker-destroy.test.js
deleted file mode 100644
index 607cbbb866..0000000000
--- a/test/js/node/test/parallel/cluster-worker-destroy.test.js
+++ /dev/null
@@ -1,73 +0,0 @@
-//#FILE: test-cluster-worker-destroy.js
-//#SHA1: 277a85b7c8fdda347d1f753601ac4b843a9a1c8d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-// The goal of this test is to cover the Workers' implementation of
-// Worker.prototype.destroy. Worker.prototype.destroy is called within
-// the worker's context: once when the worker is still connected to the
-// primary, and another time when it's not connected to it, so that we cover
-// both code paths.
-
-const assert = require("assert");
-const cluster = require("cluster");
-
-let worker1, worker2;
-
-if (cluster.isPrimary) {
- test("primary process", () => {
- worker1 = cluster.fork();
- worker2 = cluster.fork();
-
- [worker1, worker2].forEach(worker => {
- const disconnectSpy = jest.fn();
- const exitSpy = jest.fn();
-
- worker.on("disconnect", disconnectSpy);
- worker.on("exit", exitSpy);
-
- worker.on("exit", () => {
- expect(disconnectSpy).toHaveBeenCalledTimes(1);
- expect(exitSpy).toHaveBeenCalledTimes(1);
- });
- });
- });
-} else if (cluster.worker.id === 1) {
- test("worker 1: call destroy when worker is disconnected", () => {
- // Call destroy when worker is disconnected
- cluster.worker.process.on("disconnect", () => {
- cluster.worker.destroy();
- });
-
- const w = cluster.worker.disconnect();
- expect(w).toBe(cluster.worker);
- });
-} else {
- test("worker 2: call destroy when worker is not disconnected yet", () => {
- // Call destroy when worker is not disconnected yet
- cluster.worker.destroy();
- });
-}
-
-//<#END_FILE: test-cluster-worker-destroy.js
diff --git a/test/js/node/test/parallel/cluster-worker-handle-close.test.js b/test/js/node/test/parallel/cluster-worker-handle-close.test.js
deleted file mode 100644
index f6f608e0ac..0000000000
--- a/test/js/node/test/parallel/cluster-worker-handle-close.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-cluster-worker-handle-close.js
-//#SHA1: 8aa4bcd8641fe9274b97853b80734ea6f18eafbb
-//-----------------
-"use strict";
-const cluster = require("cluster");
-const net = require("net");
-
-if (cluster.isPrimary) {
- test("Primary process", () => {
- cluster.schedulingPolicy = cluster.SCHED_RR;
- expect(cluster.fork).not.toThrow();
- });
-} else {
- let server;
-
- beforeAll(() => {
- server = net.createServer(jest.fn());
- });
-
- test("Worker process", done => {
- const serverListenSpy = jest.spyOn(server, "listen");
- const netConnectSpy = jest.spyOn(net, "connect");
-
- server.listen(0, () => {
- expect(serverListenSpy).toHaveBeenCalledTimes(1);
- expect(netConnectSpy).toHaveBeenCalledWith(server.address().port);
- done();
- });
- });
-
- test("Internal message handling", done => {
- const handleCloseSpy = jest.fn(callback => callback());
- const handle = { close: handleCloseSpy };
-
- const messageHandler = (message, messageHandle) => {
- if (message.act !== "newconn") {
- return;
- }
-
- server.close();
- messageHandle.close = jest.fn(() => {
- handleCloseSpy.call(messageHandle, () => {
- expect(handleCloseSpy).toHaveBeenCalledTimes(1);
- process.exit();
- });
- });
-
- expect(messageHandle.close).toHaveBeenCalledTimes(1);
- done();
- };
-
- process.prependListener("internalMessage", messageHandler);
-
- // Simulate an internal message
- process.emit("internalMessage", { act: "newconn" }, handle);
- });
-}
-
-//<#END_FILE: test-cluster-worker-handle-close.js
diff --git a/test/js/node/test/parallel/cluster-worker-isconnected.test.js b/test/js/node/test/parallel/cluster-worker-isconnected.test.js
deleted file mode 100644
index 4ca42ebe61..0000000000
--- a/test/js/node/test/parallel/cluster-worker-isconnected.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-cluster-worker-isconnected.js
-//#SHA1: cf1e0243c030fe4cf872716099e517daec3efffc
-//-----------------
-"use strict";
-const cluster = require("cluster");
-
-if (cluster.isPrimary) {
- test("worker isConnected() in primary", () => {
- const worker = cluster.fork();
-
- expect(worker.isConnected()).toBe(true);
-
- worker.on("disconnect", () => {
- expect(worker.isConnected()).toBe(false);
- });
-
- worker.on("message", function (msg) {
- if (msg === "readyToDisconnect") {
- worker.disconnect();
- }
- });
- });
-} else {
- test("worker isConnected() in worker", () => {
- function assertNotConnected() {
- expect(cluster.worker.isConnected()).toBe(false);
- }
-
- expect(cluster.worker.isConnected()).toBe(true);
-
- cluster.worker.on("disconnect", assertNotConnected);
- cluster.worker.process.on("disconnect", assertNotConnected);
-
- process.send("readyToDisconnect");
- });
-}
-
-//<#END_FILE: test-cluster-worker-isconnected.js
diff --git a/test/js/node/test/parallel/common-countdown.test.js b/test/js/node/test/parallel/common-countdown.test.js
deleted file mode 100644
index 24c268588e..0000000000
--- a/test/js/node/test/parallel/common-countdown.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-common-countdown.js
-//#SHA1: ba753878e7b8cbeaede6057bc05a7d3b542949a5
-//-----------------
-"use strict";
-
-const assert = require("assert");
-const Countdown = require("../common/countdown");
-const fixtures = require("../common/fixtures");
-const { execFile } = require("child_process");
-
-test("Countdown functionality", () => {
- let done = "";
- const countdown = new Countdown(2, () => (done = true));
- expect(countdown.remaining).toBe(2);
- countdown.dec();
- expect(countdown.remaining).toBe(1);
- countdown.dec();
- expect(countdown.remaining).toBe(0);
- expect(done).toBe(true);
-});
-
-const failFixtures = [
- [fixtures.path("failcounter.js"), "Mismatched function calls. Expected exactly 1, actual 0."],
-];
-
-test.each(failFixtures)("Fail fixture: %s", async (file, expected) => {
- await new Promise(resolve => {
- execFile(process.argv[0], [file], (ex, stdout, stderr) => {
- expect(ex).toBeTruthy();
- expect(stderr).toBe("");
- const firstLine = stdout.split("\n").shift();
- expect(firstLine).toBe(expected);
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-common-countdown.js
diff --git a/test/js/node/test/parallel/console-assign-undefined.test.js b/test/js/node/test/parallel/console-assign-undefined.test.js
deleted file mode 100644
index cc46f41b42..0000000000
--- a/test/js/node/test/parallel/console-assign-undefined.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-console-assign-undefined.js
-//#SHA1: ccd5cd3087520e692e5123679c1753d168d310f0
-//-----------------
-"use strict";
-
-// Patch global.console before importing modules that may modify the console
-// object.
-
-let originalConsole;
-
-beforeAll(() => {
- originalConsole = global.console;
- global.console = 42;
-});
-
-afterAll(() => {
- // Reset the console
- global.console = originalConsole;
-});
-
-test("console can be assigned a non-object value", () => {
- // Originally the console had a getter. Test twice to verify it had no side
- // effect.
- expect(global.console).toBe(42);
- expect(global.console).toBe(42);
-
- expect(() => console.log("foo")).toThrow(
- expect.objectContaining({
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-
- global.console = 1;
- expect(global.console).toBe(1);
- expect(console).toBe(1);
-});
-
-test("console can be reset and used", () => {
- global.console = originalConsole;
- const consoleSpy = jest.spyOn(console, "log");
- console.log("foo");
- expect(consoleSpy).toHaveBeenCalledWith("foo");
- consoleSpy.mockRestore();
-});
-
-//<#END_FILE: test-console-assign-undefined.js
diff --git a/test/js/node/test/parallel/console-issue-43095.test.js b/test/js/node/test/parallel/console-issue-43095.test.js
deleted file mode 100644
index 815c2d86ad..0000000000
--- a/test/js/node/test/parallel/console-issue-43095.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-//#FILE: test-console-issue-43095.js
-//#SHA1: 1c0c5cce62bcee4d50c6b716dd1430db2784c3f4
-//-----------------
-"use strict";
-
-const { inspect } = require("node:util");
-
-test("console output for revoked proxy", () => {
- const consoleSpy = {
- dir: jest.spyOn(console, "dir").mockImplementation(),
- log: jest.spyOn(console, "log").mockImplementation(),
- };
-
- const r = Proxy.revocable({}, {});
- r.revoke();
-
- console.dir(r);
- console.dir(r.proxy);
- console.log(r.proxy);
- console.log(inspect(r.proxy, { showProxy: true }));
-
- expect(consoleSpy.dir).toHaveBeenCalledTimes(2);
- expect(consoleSpy.log).toHaveBeenCalledTimes(2);
-
- // Check that console.dir was called with the revoked proxy object
- expect(consoleSpy.dir.mock.calls[0][0]).toBe(r);
- expect(consoleSpy.dir.mock.calls[1][0]).toBe(r.proxy);
-
- // Check that console.log was called with the revoked proxy
- expect(consoleSpy.log.mock.calls[0][0]).toBe(r.proxy);
-
- // Check that console.log was called with the inspected revoked proxy
- expect(consoleSpy.log.mock.calls[1][0]).toBe(inspect(r.proxy, { showProxy: true }));
-
- // Clean up
- consoleSpy.dir.mockRestore();
- consoleSpy.log.mockRestore();
-});
-
-//<#END_FILE: test-console-issue-43095.js
diff --git a/test/js/node/test/parallel/console-log-stdio-broken-dest.test.js b/test/js/node/test/parallel/console-log-stdio-broken-dest.test.js
deleted file mode 100644
index b93dfe3824..0000000000
--- a/test/js/node/test/parallel/console-log-stdio-broken-dest.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-console-log-stdio-broken-dest.js
-//#SHA1: c2c2e85eeb28db4ace2c4bb0a86f46f7e7bf2682
-//-----------------
-"use strict";
-
-const { Writable } = require("stream");
-const { Console } = require("console");
-const { EventEmitter } = require("events");
-
-test("Console log with broken destination", done => {
- const stream = new Writable({
- write(chunk, enc, cb) {
- cb();
- },
- writev(chunks, cb) {
- setTimeout(cb, 10, new Error("kaboom"));
- },
- });
- const myConsole = new Console(stream, stream);
-
- const warningListener = jest.fn();
- process.on("warning", warningListener);
-
- stream.cork();
- for (let i = 0; i < EventEmitter.defaultMaxListeners + 1; i++) {
- myConsole.log("a message");
- }
- stream.uncork();
-
- // We need to wait for the next tick to ensure the error has time to propagate
- process.nextTick(() => {
- expect(warningListener).not.toHaveBeenCalled();
- process.removeListener("warning", warningListener);
- done();
- });
-});
-
-//<#END_FILE: test-console-log-stdio-broken-dest.js
diff --git a/test/js/node/test/parallel/console-log-throw-primitive.test.js b/test/js/node/test/parallel/console-log-throw-primitive.test.js
deleted file mode 100644
index e318eaaf4d..0000000000
--- a/test/js/node/test/parallel/console-log-throw-primitive.test.js
+++ /dev/null
@@ -1,22 +0,0 @@
-//#FILE: test-console-log-throw-primitive.js
-//#SHA1: a1889badf1058f6fadc8984a5075f3d048e2948c
-//-----------------
-"use strict";
-
-const { Writable } = require("stream");
-const { Console } = require("console");
-
-test("Console.log should not throw when stream throws null", () => {
- const stream = new Writable({
- write() {
- throw null; // eslint-disable-line no-throw-literal
- },
- });
-
- const console = new Console({ stdout: stream });
-
- // Should not throw
- expect(() => console.log("test")).not.toThrow();
-});
-
-//<#END_FILE: test-console-log-throw-primitive.js
diff --git a/test/js/node/test/parallel/console-not-call-tostring.test.js b/test/js/node/test/parallel/console-not-call-tostring.test.js
deleted file mode 100644
index f43e7dbde6..0000000000
--- a/test/js/node/test/parallel/console-not-call-tostring.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-console-not-call-toString.js
-//#SHA1: e0bf3a601442b76f12f657e53df54690d2fe21fa
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-test("util.inspect does not call toString", () => {
- function func() {}
- let toStringCalled = false;
- func.toString = function () {
- toStringCalled = true;
- };
-
- require("util").inspect(func);
-
- expect(toStringCalled).toBe(false);
-});
-
-//<#END_FILE: test-console-not-call-toString.js
diff --git a/test/js/node/test/parallel/console-self-assign.test.js b/test/js/node/test/parallel/console-self-assign.test.js
deleted file mode 100644
index e746e9a47a..0000000000
--- a/test/js/node/test/parallel/console-self-assign.test.js
+++ /dev/null
@@ -1,13 +0,0 @@
-//#FILE: test-console-self-assign.js
-//#SHA1: 7ed2fd07a18f0485f2592ada8e97e9c33753e691
-//-----------------
-"use strict";
-
-// Assigning to itself should not throw.
-test("console self-assignment", () => {
- expect(() => {
- global.console = global.console; // eslint-disable-line no-self-assign
- }).not.toThrow();
-});
-
-//<#END_FILE: test-console-self-assign.js
diff --git a/test/js/node/test/parallel/crypto-dh-shared.test.js b/test/js/node/test/parallel/crypto-dh-shared.test.js
deleted file mode 100644
index f811ca4df7..0000000000
--- a/test/js/node/test/parallel/crypto-dh-shared.test.js
+++ /dev/null
@@ -1,21 +0,0 @@
-//#FILE: test-crypto-dh-shared.js
-//#SHA1: 8d5e31de4aa93f435c4c6d05d7b394156a38fb8e
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-test("Diffie-Hellman shared secret computation", () => {
- const alice = crypto.createDiffieHellmanGroup("modp5");
- const bob = crypto.createDiffieHellmanGroup("modp5");
-
- alice.generateKeys();
- bob.generateKeys();
-
- const aSecret = alice.computeSecret(bob.getPublicKey()).toString("hex");
- const bSecret = bob.computeSecret(alice.getPublicKey()).toString("hex");
-
- expect(aSecret).toBe(bSecret);
-});
-
-//<#END_FILE: test-crypto-dh-shared.js
diff --git a/test/js/node/test/parallel/crypto-from-binary.test.js b/test/js/node/test/parallel/crypto-from-binary.test.js
deleted file mode 100644
index 3c015ec6b6..0000000000
--- a/test/js/node/test/parallel/crypto-from-binary.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-//#FILE: test-crypto-from-binary.js
-//#SHA1: 2f3b186e9b549c6910a58dea98e6bdeb7c540afa
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// This is the same as test/simple/test-crypto, but from before the shift
-// to use buffers by default.
-
-const crypto = require("crypto");
-
-const EXTERN_APEX = 0xfbee9;
-
-// Manually controlled string for checking binary output
-let ucs2_control = "a\u0000";
-
-// Grow the strings to proper length
-while (ucs2_control.length <= EXTERN_APEX) {
- ucs2_control = ucs2_control.repeat(2);
-}
-
-// Check resultant buffer and output string
-const b = Buffer.from(ucs2_control + ucs2_control, "ucs2");
-
-describe("Crypto from binary", () => {
- beforeAll(() => {
- if (!crypto) {
- return test.skip("missing crypto");
- }
- });
-
- test("Update from binary data - small slice", () => {
- const datum1 = b.slice(700000);
- const hash1_converted = crypto.createHash("sha1").update(datum1.toString("base64"), "base64").digest("hex");
- const hash1_direct = crypto.createHash("sha1").update(datum1).digest("hex");
- expect(hash1_direct).toBe(hash1_converted);
- });
-
- test("Update from binary data - full buffer", () => {
- const datum2 = b;
- const hash2_converted = crypto.createHash("sha1").update(datum2.toString("base64"), "base64").digest("hex");
- const hash2_direct = crypto.createHash("sha1").update(datum2).digest("hex");
- expect(hash2_direct).toBe(hash2_converted);
- });
-});
-
-//<#END_FILE: test-crypto-from-binary.js
diff --git a/test/js/node/test/parallel/crypto-keygen-async-elliptic-curve-jwk-rsa.test.js b/test/js/node/test/parallel/crypto-keygen-async-elliptic-curve-jwk-rsa.test.js
deleted file mode 100644
index f19582afbd..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-async-elliptic-curve-jwk-rsa.test.js
+++ /dev/null
@@ -1,45 +0,0 @@
-//#FILE: test-crypto-keygen-async-elliptic-curve-jwk-rsa.js
-//#SHA1: 4337f1e36680f21ed3439d7ab546ea855a0a842e
-//-----------------
-"use strict";
-
-const { generateKeyPair } = require("crypto");
-
-// Test async elliptic curve key generation with 'jwk' encoding and RSA.
-test("async elliptic curve key generation with jwk encoding and RSA", async () => {
- const { publicKey, privateKey } = await new Promise((resolve, reject) => {
- generateKeyPair(
- "rsa",
- {
- modulusLength: 1024,
- publicKeyEncoding: {
- format: "jwk",
- },
- privateKeyEncoding: {
- format: "jwk",
- },
- },
- (err, publicKey, privateKey) => {
- if (err) reject(err);
- else resolve({ publicKey, privateKey });
- },
- );
- });
-
- expect(typeof publicKey).toBe("object");
- expect(typeof privateKey).toBe("object");
- expect(publicKey.kty).toBe("RSA");
- expect(publicKey.kty).toBe(privateKey.kty);
- expect(typeof publicKey.n).toBe("string");
- expect(publicKey.n).toBe(privateKey.n);
- expect(typeof publicKey.e).toBe("string");
- expect(publicKey.e).toBe(privateKey.e);
- expect(typeof privateKey.d).toBe("string");
- expect(typeof privateKey.p).toBe("string");
- expect(typeof privateKey.q).toBe("string");
- expect(typeof privateKey.dp).toBe("string");
- expect(typeof privateKey.dq).toBe("string");
- expect(typeof privateKey.qi).toBe("string");
-});
-
-//<#END_FILE: test-crypto-keygen-async-elliptic-curve-jwk-rsa.js
diff --git a/test/js/node/test/parallel/crypto-keygen-async-encrypted-private-key-der.test.js b/test/js/node/test/parallel/crypto-keygen-async-encrypted-private-key-der.test.js
deleted file mode 100644
index 01e5b30494..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-async-encrypted-private-key-der.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-crypto-keygen-async-encrypted-private-key-der.js
-//#SHA1: 30f86c68619f3f24294d5f062eed48b13c116b0c
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-const { assertApproximateSize, testEncryptDecrypt, testSignVerify } = require("../common/crypto");
-
-// Test async RSA key generation with an encrypted private key, but encoded as DER.
-test("RSA key generation with encrypted private key (DER)", async () => {
- const { publicKey: publicKeyDER, privateKey: privateKeyDER } = await new Promise((resolve, reject) => {
- crypto.generateKeyPair(
- "rsa",
- {
- publicExponent: 0x10001,
- modulusLength: 512,
- publicKeyEncoding: {
- type: "pkcs1",
- format: "der",
- },
- privateKeyEncoding: {
- type: "pkcs8",
- format: "der",
- },
- },
- (err, publicKey, privateKey) => {
- if (err) reject(err);
- else resolve({ publicKey, privateKey });
- },
- );
- });
-
- expect(Buffer.isBuffer(publicKeyDER)).toBe(true);
- assertApproximateSize(publicKeyDER, 74);
-
- expect(Buffer.isBuffer(privateKeyDER)).toBe(true);
-
- const publicKey = {
- key: publicKeyDER,
- type: "pkcs1",
- format: "der",
- };
- const privateKey = {
- key: privateKeyDER,
- format: "der",
- type: "pkcs8",
- passphrase: "secret",
- };
-
- await testEncryptDecrypt(publicKey, privateKey);
- await testSignVerify(publicKey, privateKey);
-});
-
-//<#END_FILE: test-crypto-keygen-async-encrypted-private-key-der.js
diff --git a/test/js/node/test/parallel/crypto-keygen-async-explicit-elliptic-curve.test.js b/test/js/node/test/parallel/crypto-keygen-async-explicit-elliptic-curve.test.js
deleted file mode 100644
index 4d6f637147..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-async-explicit-elliptic-curve.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//#FILE: test-crypto-keygen-async-explicit-elliptic-curve.js
-//#SHA1: be1eabf816f52e5f53cb2535d47050b2552d21cd
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-// Skip the test if crypto support is not available
-if (!crypto.generateKeyPair) {
- test.skip("missing crypto support", () => {});
-} else {
- const { generateKeyPair } = crypto;
-
- const { testSignVerify, spkiExp, sec1Exp } = require("../common/crypto");
-
- // Test async explicit elliptic curve key generation, e.g. for ECDSA,
- // with a SEC1 private key with paramEncoding explicit.
- test("async explicit elliptic curve key generation", async () => {
- await new Promise((resolve, reject) => {
- generateKeyPair(
- "ec",
- {
- namedCurve: "prime256v1",
- paramEncoding: "explicit",
- publicKeyEncoding: {
- type: "spki",
- format: "pem",
- },
- privateKeyEncoding: {
- type: "sec1",
- format: "pem",
- },
- },
- (err, publicKey, privateKey) => {
- if (err) reject(err);
- else resolve({ publicKey, privateKey });
- },
- );
- }).then(({ publicKey, privateKey }) => {
- expect(typeof publicKey).toBe("string");
- expect(publicKey).toMatch(spkiExp);
- expect(typeof privateKey).toBe("string");
- expect(privateKey).toMatch(sec1Exp);
-
- return testSignVerify(publicKey, privateKey);
- });
- });
-}
-
-//<#END_FILE: test-crypto-keygen-async-explicit-elliptic-curve.js
diff --git a/test/js/node/test/parallel/crypto-keygen-async-named-elliptic-curve.test.js b/test/js/node/test/parallel/crypto-keygen-async-named-elliptic-curve.test.js
deleted file mode 100644
index 8721a4551f..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-async-named-elliptic-curve.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-//#FILE: test-crypto-keygen-async-named-elliptic-curve.js
-//#SHA1: 77822175b9b2c2206ec4ab8a3e1182e3576b23bd
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-const { testSignVerify } = require("../common/crypto");
-
-if (!crypto.generateKeyPair) {
- test.skip("missing crypto.generateKeyPair");
-}
-
-const spkiExp =
- /^-----BEGIN PUBLIC KEY-----\n(?:[A-Za-z0-9+/=]{64}\n)*[A-Za-z0-9+/=]{1,64}\n-----END PUBLIC KEY-----\n$/;
-const sec1Exp =
- /^-----BEGIN EC PRIVATE KEY-----\n(?:[A-Za-z0-9+/=]{64}\n)*[A-Za-z0-9+/=]{1,64}\n-----END EC PRIVATE KEY-----\n$/;
-
-// Test async named elliptic curve key generation, e.g. for ECDSA,
-// with a SEC1 private key.
-test("async named elliptic curve key generation with SEC1 private key", async () => {
- const { publicKey, privateKey } = await new Promise((resolve, reject) => {
- crypto.generateKeyPair(
- "ec",
- {
- namedCurve: "prime256v1",
- paramEncoding: "named",
- publicKeyEncoding: {
- type: "spki",
- format: "pem",
- },
- privateKeyEncoding: {
- type: "sec1",
- format: "pem",
- },
- },
- (err, publicKey, privateKey) => {
- if (err) reject(err);
- else resolve({ publicKey, privateKey });
- },
- );
- });
-
- expect(typeof publicKey).toBe("string");
- expect(publicKey).toMatch(spkiExp);
- expect(typeof privateKey).toBe("string");
- expect(privateKey).toMatch(sec1Exp);
-
- await testSignVerify(publicKey, privateKey);
-});
-
-//<#END_FILE: test-crypto-keygen-async-named-elliptic-curve.js
diff --git a/test/js/node/test/parallel/crypto-keygen-empty-passphrase-no-error.test.js b/test/js/node/test/parallel/crypto-keygen-empty-passphrase-no-error.test.js
deleted file mode 100644
index ed029ce08d..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-empty-passphrase-no-error.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-crypto-keygen-empty-passphrase-no-error.js
-//#SHA1: a949b38385a5dd05507975cbc44b3beba764bd95
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-// Skip the test if crypto is not available
-if (typeof crypto.generateKeyPair !== "function") {
- test.skip("missing crypto", () => {});
-} else {
- test("generateKeyPair with empty passphrase should not throw ERR_OSSL_CRYPTO_MALLOC_FAILURE", async () => {
- // Passing an empty passphrase string should not throw ERR_OSSL_CRYPTO_MALLOC_FAILURE even on OpenSSL 3.
- // Regression test for https://github.com/nodejs/node/issues/41428.
- await expect(
- new Promise((resolve, reject) => {
- crypto.generateKeyPair(
- "rsa",
- {
- modulusLength: 1024,
- publicKeyEncoding: {
- type: "spki",
- format: "pem",
- },
- privateKeyEncoding: {
- type: "pkcs8",
- format: "pem",
- cipher: "aes-256-cbc",
- passphrase: "",
- },
- },
- (err, publicKey, privateKey) => {
- if (err) reject(err);
- else resolve({ publicKey, privateKey });
- },
- );
- }),
- ).resolves.toEqual(
- expect.objectContaining({
- publicKey: expect.any(String),
- privateKey: expect.any(String),
- }),
- );
- });
-}
-
-//<#END_FILE: test-crypto-keygen-empty-passphrase-no-error.js
diff --git a/test/js/node/test/parallel/crypto-keygen-key-object-without-encoding.test.js b/test/js/node/test/parallel/crypto-keygen-key-object-without-encoding.test.js
deleted file mode 100644
index 53d01c929f..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-key-object-without-encoding.test.js
+++ /dev/null
@@ -1,90 +0,0 @@
-//#FILE: test-crypto-keygen-key-object-without-encoding.js
-//#SHA1: da408ed128f913dc7343ef88743b362c16420ba0
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-// Skip the test if crypto is not available
-if (!crypto.generateKeyPair) {
- test.skip("missing crypto");
-}
-
-const { generateKeyPair } = crypto;
-
-// Helper functions for testing encryption/decryption and signing/verifying
-const testEncryptDecrypt = (publicKey, privateKey) => {
- const plaintext = "Hello, World!";
- const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(plaintext));
- const decrypted = crypto.privateDecrypt(privateKey, encrypted);
- expect(decrypted.toString()).toBe(plaintext);
-};
-
-const testSignVerify = (publicKey, privateKey) => {
- const data = "Hello, World!";
- const sign = crypto.createSign("SHA256");
- sign.update(data);
- const signature = sign.sign(privateKey);
- const verify = crypto.createVerify("SHA256");
- verify.update(data);
- expect(verify.verify(publicKey, signature)).toBe(true);
-};
-
-// Tests key objects are returned when key encodings are not specified.
-describe("generateKeyPair without encoding", () => {
- // If no publicKeyEncoding is specified, a key object should be returned.
- test("returns key object for public key when no encoding specified", done => {
- generateKeyPair(
- "rsa",
- {
- modulusLength: 1024,
- privateKeyEncoding: {
- type: "pkcs1",
- format: "pem",
- },
- },
- (err, publicKey, privateKey) => {
- expect(err).toBe(null);
- expect(typeof publicKey).toBe("object");
- expect(publicKey.type).toBe("public");
- expect(publicKey.asymmetricKeyType).toBe("rsa");
-
- // The private key should still be a string.
- expect(typeof privateKey).toBe("string");
-
- testEncryptDecrypt(publicKey, privateKey);
- testSignVerify(publicKey, privateKey);
- done();
- },
- );
- });
-
- // If no privateKeyEncoding is specified, a key object should be returned.
- test("returns key object for private key when no encoding specified", done => {
- generateKeyPair(
- "rsa",
- {
- modulusLength: 1024,
- publicKeyEncoding: {
- type: "pkcs1",
- format: "pem",
- },
- },
- (err, publicKey, privateKey) => {
- expect(err).toBe(null);
- // The public key should still be a string.
- expect(typeof publicKey).toBe("string");
-
- expect(typeof privateKey).toBe("object");
- expect(privateKey.type).toBe("private");
- expect(privateKey.asymmetricKeyType).toBe("rsa");
-
- testEncryptDecrypt(publicKey, privateKey);
- testSignVerify(publicKey, privateKey);
- done();
- },
- );
- });
-});
-
-//<#END_FILE: test-crypto-keygen-key-object-without-encoding.js
diff --git a/test/js/node/test/parallel/crypto-keygen-key-objects.test.js b/test/js/node/test/parallel/crypto-keygen-key-objects.test.js
deleted file mode 100644
index 29d4bbe5f8..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-key-objects.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-crypto-keygen-key-objects.js
-//#SHA1: 7a2dce611ba70e533ebb73d9f281896bdf75051f
-//-----------------
-"use strict";
-
-if (!process.versions.bun) {
- const common = require("../common");
- if (!common.hasCrypto) common.skip("missing crypto");
-}
-
-const { generateKeyPairSync } = require("crypto");
-
-// Test sync key generation with key objects.
-test("generateKeyPairSync with RSA", () => {
- const { publicKey, privateKey } = generateKeyPairSync("rsa", {
- modulusLength: 512,
- });
-
- expect(typeof publicKey).toBe("object");
- expect(publicKey.type).toBe("public");
- expect(publicKey.asymmetricKeyType).toBe("rsa");
- expect(publicKey.asymmetricKeyDetails).toEqual({
- modulusLength: 512,
- publicExponent: 65537n,
- });
-
- expect(typeof privateKey).toBe("object");
- expect(privateKey.type).toBe("private");
- expect(privateKey.asymmetricKeyType).toBe("rsa");
- expect(privateKey.asymmetricKeyDetails).toEqual({
- modulusLength: 512,
- publicExponent: 65537n,
- });
-});
-
-//<#END_FILE: test-crypto-keygen-key-objects.js
diff --git a/test/js/node/test/parallel/crypto-keygen-missing-oid.test.js b/test/js/node/test/parallel/crypto-keygen-missing-oid.test.js
deleted file mode 100644
index b91248c3a6..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-missing-oid.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-crypto-keygen-missing-oid.js
-//#SHA1: ffcbc53b115cce8795ca1a0e73a533b04789a930
-//-----------------
-"use strict";
-
-const { generateKeyPair, generateKeyPairSync, getCurves } = require("crypto");
-
-// This test creates EC key pairs on curves without associated OIDs.
-// Specifying a key encoding should not crash.
-test("EC key pairs on curves without associated OIDs", () => {
- if (process.versions.openssl >= "1.1.1i") {
- const curves = ["Oakley-EC2N-3", "Oakley-EC2N-4"];
- const availableCurves = getCurves();
-
- for (const namedCurve of curves) {
- if (!availableCurves.includes(namedCurve)) continue;
-
- const expectedErrorCode = process.versions.openssl.startsWith("3.")
- ? "ERR_OSSL_MISSING_OID"
- : "ERR_OSSL_EC_MISSING_OID";
-
- const params = {
- namedCurve,
- publicKeyEncoding: {
- format: "der",
- type: "spki",
- },
- };
-
- expect(() => {
- generateKeyPairSync("ec", params);
- }).toThrow(
- expect.objectContaining({
- code: expectedErrorCode,
- message: expect.any(String),
- }),
- );
-
- return new Promise(resolve => {
- generateKeyPair("ec", params, err => {
- expect(err).toMatchObject({
- code: expectedErrorCode,
- message: expect.any(String),
- });
- resolve();
- });
- });
- }
- } else {
- // Skip test if OpenSSL version is less than 1.1.1i
- test.skip("OpenSSL version is less than 1.1.1i");
- }
-});
-
-//<#END_FILE: test-crypto-keygen-missing-oid.js
diff --git a/test/js/node/test/parallel/crypto-keygen-non-standard-public-exponent.test.js b/test/js/node/test/parallel/crypto-keygen-non-standard-public-exponent.test.js
deleted file mode 100644
index 46fc35ffdb..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-non-standard-public-exponent.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-crypto-keygen-non-standard-public-exponent.js
-//#SHA1: 955e956a08102b75fcf0571213a1dd939d1f51ac
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-if (!crypto.generateKeyPairSync) {
- test.skip("missing crypto.generateKeyPairSync");
-}
-
-// Test sync key generation with key objects with a non-standard
-// publicExponent
-test("generateKeyPairSync with non-standard publicExponent", () => {
- const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
- publicExponent: 3,
- modulusLength: 512,
- });
-
- expect(typeof publicKey).toBe("object");
- expect(publicKey.type).toBe("public");
- expect(publicKey.asymmetricKeyType).toBe("rsa");
- expect(publicKey.asymmetricKeyDetails).toEqual({
- modulusLength: 512,
- publicExponent: 3n,
- });
-
- expect(typeof privateKey).toBe("object");
- expect(privateKey.type).toBe("private");
- expect(privateKey.asymmetricKeyType).toBe("rsa");
- expect(privateKey.asymmetricKeyDetails).toEqual({
- modulusLength: 512,
- publicExponent: 3n,
- });
-});
-
-//<#END_FILE: test-crypto-keygen-non-standard-public-exponent.js
diff --git a/test/js/node/test/parallel/crypto-keygen-promisify.test.js b/test/js/node/test/parallel/crypto-keygen-promisify.test.js
deleted file mode 100644
index 845d68a970..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-promisify.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-//#FILE: test-crypto-keygen-promisify.js
-//#SHA1: 70eb7089a04950a2ce28a3af9949105eefd420fa
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-const util = require("util");
-
-const {
- assertApproximateSize,
- testEncryptDecrypt,
- testSignVerify,
- pkcs1PubExp,
- pkcs1PrivExp,
-} = require("../common/crypto");
-
-// Skip the test if crypto support is not available
-if (!crypto.generateKeyPair) {
- test.skip("missing crypto support", () => {});
-} else {
- // Test the util.promisified API with async RSA key generation.
- test("util.promisified generateKeyPair with RSA", async () => {
- const generateKeyPairPromise = util.promisify(crypto.generateKeyPair);
- const keys = await generateKeyPairPromise("rsa", {
- publicExponent: 0x10001,
- modulusLength: 512,
- publicKeyEncoding: {
- type: "pkcs1",
- format: "pem",
- },
- privateKeyEncoding: {
- type: "pkcs1",
- format: "pem",
- },
- });
-
- const { publicKey, privateKey } = keys;
- expect(typeof publicKey).toBe("string");
- expect(publicKey).toMatch(pkcs1PubExp);
- assertApproximateSize(publicKey, 180);
-
- expect(typeof privateKey).toBe("string");
- expect(privateKey).toMatch(pkcs1PrivExp);
- assertApproximateSize(privateKey, 512);
-
- testEncryptDecrypt(publicKey, privateKey);
- testSignVerify(publicKey, privateKey);
- });
-}
-
-//<#END_FILE: test-crypto-keygen-promisify.js
diff --git a/test/js/node/test/parallel/crypto-keygen-sync.test.js b/test/js/node/test/parallel/crypto-keygen-sync.test.js
deleted file mode 100644
index 26d3a218fb..0000000000
--- a/test/js/node/test/parallel/crypto-keygen-sync.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//#FILE: test-crypto-keygen-sync.js
-//#SHA1: 57749dc903b0d5f9b64a3d61f313be6e5549323f
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-const {
- assertApproximateSize,
- testEncryptDecrypt,
- testSignVerify,
- pkcs1PubExp,
- pkcs8Exp,
-} = require("../common/crypto");
-
-// Skip the test if crypto support is not available
-if (typeof crypto.generateKeyPairSync !== "function") {
- test.skip("missing crypto support", () => {});
-} else {
- // To make the test faster, we will only test sync key generation once and
- // with a relatively small key.
- test("generateKeyPairSync", () => {
- const ret = crypto.generateKeyPairSync("rsa", {
- publicExponent: 3,
- modulusLength: 512,
- publicKeyEncoding: {
- type: "pkcs1",
- format: "pem",
- },
- privateKeyEncoding: {
- type: "pkcs8",
- format: "pem",
- },
- });
-
- expect(Object.keys(ret)).toHaveLength(2);
- const { publicKey, privateKey } = ret;
-
- expect(typeof publicKey).toBe("string");
- expect(publicKey).toMatch(pkcs1PubExp);
- assertApproximateSize(publicKey, 162);
- expect(typeof privateKey).toBe("string");
- expect(privateKey).toMatch(pkcs8Exp);
- assertApproximateSize(privateKey, 512);
-
- testEncryptDecrypt(publicKey, privateKey);
- testSignVerify(publicKey, privateKey);
- });
-}
-
-//<#END_FILE: test-crypto-keygen-sync.js
diff --git a/test/js/node/test/parallel/crypto-lazy-transform-writable.test.js b/test/js/node/test/parallel/crypto-lazy-transform-writable.test.js
deleted file mode 100644
index 6df20ee83f..0000000000
--- a/test/js/node/test/parallel/crypto-lazy-transform-writable.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-crypto-lazy-transform-writable.js
-//#SHA1: 29f694c4ea89a94302b3aa84677b5e41c73077d7
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-const Stream = require("stream");
-
-if (!crypto) it.skip("missing crypto", () => {});
-
-test("crypto lazy transform writable", done => {
- const hasher1 = crypto.createHash("sha256");
- const hasher2 = crypto.createHash("sha256");
-
- // Calculate the expected result.
- hasher1.write(Buffer.from("hello world"));
- hasher1.end();
-
- const expected = hasher1.read().toString("hex");
-
- class OldStream extends Stream {
- constructor() {
- super();
- this.readable = true;
- }
- }
-
- const stream = new OldStream();
-
- stream.pipe(hasher2).on("finish", () => {
- const hash = hasher2.read().toString("hex");
- expect(hash).toBe(expected);
- done();
- });
-
- stream.emit("data", Buffer.from("hello"));
- stream.emit("data", Buffer.from(" world"));
- stream.emit("end");
-});
-
-//<#END_FILE: test-crypto-lazy-transform-writable.js
diff --git a/test/js/node/test/parallel/crypto-padding-aes256.test.js b/test/js/node/test/parallel/crypto-padding-aes256.test.js
deleted file mode 100644
index 079e7a15b6..0000000000
--- a/test/js/node/test/parallel/crypto-padding-aes256.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-crypto-padding-aes256.js
-//#SHA1: 96fb5beb94bedbc768788ba2726dcd0e61733c5a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const crypto = require("crypto");
-
-const iv = Buffer.from("00000000000000000000000000000000", "hex");
-const key = Buffer.from("0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef", "hex");
-
-function encrypt(val, pad) {
- const c = crypto.createCipheriv("aes256", key, iv);
- c.setAutoPadding(pad);
- return c.update(val, "utf8", "latin1") + c.final("latin1");
-}
-
-function decrypt(val, pad) {
- const c = crypto.createDecipheriv("aes256", key, iv);
- c.setAutoPadding(pad);
- return c.update(val, "latin1", "utf8") + c.final("utf8");
-}
-
-test("AES256 encryption and decryption with no padding (multiple of block size)", () => {
- // echo 0123456789abcdef0123456789abcdef \
- // | openssl enc -e -aes256 -nopad -K -iv \
- // | openssl enc -d -aes256 -nopad -K -iv
- const plaintext = "0123456789abcdef0123456789abcdef"; // Multiple of block size
- const encrypted = encrypt(plaintext, false);
- const decrypted = decrypt(encrypted, false);
- expect(decrypted).toBe(plaintext);
-});
-
-test("AES256 encryption and decryption with padding (not a multiple of block size)", () => {
- // echo 0123456789abcdef0123456789abcde \
- // | openssl enc -e -aes256 -K -iv \
- // | openssl enc -d -aes256 -K -iv
- const plaintext = "0123456789abcdef0123456789abcde"; // not a multiple
- const encrypted = encrypt(plaintext, true);
- const decrypted = decrypt(encrypted, true);
- expect(decrypted).toBe(plaintext);
-});
-
-//<#END_FILE: test-crypto-padding-aes256.js
diff --git a/test/js/node/test/parallel/crypto-randomfillsync-regression.test.js b/test/js/node/test/parallel/crypto-randomfillsync-regression.test.js
deleted file mode 100644
index aa57030f2a..0000000000
--- a/test/js/node/test/parallel/crypto-randomfillsync-regression.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-crypto-randomfillsync-regression.js
-//#SHA1: f37bc7cc1eab82ab93665b246c0d44e9fce8d112
-//-----------------
-"use strict";
-
-// Skip the test if crypto is not available
-let randomFillSync;
-try {
- ({ randomFillSync } = require("crypto"));
-} catch {
- test.skip("missing crypto", () => {});
-}
-
-if (randomFillSync) {
- test("randomFillSync regression test", () => {
- const ab = new ArrayBuffer(20);
- const buf = Buffer.from(ab, 10);
-
- const before = buf.toString("hex");
-
- randomFillSync(buf);
-
- const after = buf.toString("hex");
-
- expect(before).not.toBe(after);
- });
-}
-
-//<#END_FILE: test-crypto-randomfillsync-regression.js
diff --git a/test/js/node/test/parallel/crypto-subtle-zero-length.test.js b/test/js/node/test/parallel/crypto-subtle-zero-length.test.js
deleted file mode 100644
index 9113969480..0000000000
--- a/test/js/node/test/parallel/crypto-subtle-zero-length.test.js
+++ /dev/null
@@ -1,42 +0,0 @@
-//#FILE: test-crypto-subtle-zero-length.js
-//#SHA1: aa21bbc5fd9db7bc09dad3ec61cd743d655f5e3b
-//-----------------
-"use strict";
-
-// Skip test if crypto is not available
-if (typeof crypto === "undefined" || !crypto.subtle) {
- test.skip("missing crypto");
-}
-
-test("SubtleCrypto with zero-length input", async () => {
- const { subtle } = globalThis.crypto;
-
- const k = await subtle.importKey("raw", new Uint8Array(32), { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
- expect(k).toBeInstanceOf(CryptoKey);
-
- const e = await subtle.encrypt(
- {
- name: "AES-GCM",
- iv: new Uint8Array(12),
- },
- k,
- new Uint8Array(0),
- );
- expect(e).toBeInstanceOf(ArrayBuffer);
- expect(Buffer.from(e)).toEqual(
- Buffer.from([0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9, 0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b]),
- );
-
- const v = await subtle.decrypt(
- {
- name: "AES-GCM",
- iv: new Uint8Array(12),
- },
- k,
- e,
- );
- expect(v).toBeInstanceOf(ArrayBuffer);
- expect(v.byteLength).toBe(0);
-});
-
-//<#END_FILE: test-crypto-subtle-zero-length.js
diff --git a/test/js/node/test/parallel/crypto-update-encoding.test.js b/test/js/node/test/parallel/crypto-update-encoding.test.js
deleted file mode 100644
index 1c0d269234..0000000000
--- a/test/js/node/test/parallel/crypto-update-encoding.test.js
+++ /dev/null
@@ -1,33 +0,0 @@
-//#FILE: test-crypto-update-encoding.js
-//#SHA1: dfe3c7e71e22a772cf6b2e6a6540be161fda3418
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-const zeros = Buffer.alloc;
-const key = zeros(16);
-const iv = zeros(16);
-
-const cipher = () => crypto.createCipheriv("aes-128-cbc", key, iv);
-const decipher = () => crypto.createDecipheriv("aes-128-cbc", key, iv);
-const hash = () => crypto.createSign("sha256");
-const hmac = () => crypto.createHmac("sha256", key);
-const sign = () => crypto.createSign("sha256");
-const verify = () => crypto.createVerify("sha256");
-
-test("crypto update ignores inputEncoding for Buffer input", () => {
- const functions = [cipher, decipher, hash, hmac, sign, verify];
- const sizes = [15, 16];
-
- functions.forEach(f => {
- sizes.forEach(n => {
- const instance = f();
- expect(() => {
- instance.update(zeros(n), "hex");
- }).not.toThrow();
- });
- });
-});
-
-//<#END_FILE: test-crypto-update-encoding.js
diff --git a/test/js/node/test/parallel/crypto-webcrypto-aes-decrypt-tag-too-small.test.js b/test/js/node/test/parallel/crypto-webcrypto-aes-decrypt-tag-too-small.test.js
deleted file mode 100644
index de241c13af..0000000000
--- a/test/js/node/test/parallel/crypto-webcrypto-aes-decrypt-tag-too-small.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-//#FILE: test-crypto-webcrypto-aes-decrypt-tag-too-small.js
-//#SHA1: e58d2e4e7dcfc3a29a6e9acbe177f32a1d6bf280
-//-----------------
-"use strict";
-
-if (!globalThis.crypto?.subtle) {
- test.skip("missing crypto");
-}
-
-test("AES-GCM decrypt with tag too small", async () => {
- const { subtle } = globalThis.crypto;
-
- const key = await subtle.importKey(
- "raw",
- new Uint8Array(32),
- {
- name: "AES-GCM",
- },
- false,
- ["encrypt", "decrypt"],
- );
-
- await expect(
- subtle.decrypt(
- {
- name: "AES-GCM",
- iv: new Uint8Array(12),
- },
- key,
- new Uint8Array(0),
- ),
- ).rejects.toThrow(
- expect.objectContaining({
- name: "OperationError",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-crypto-webcrypto-aes-decrypt-tag-too-small.js
diff --git a/test/js/node/test/parallel/dgram-abort-closed.test.js b/test/js/node/test/parallel/dgram-abort-closed.test.js
deleted file mode 100644
index eb09ac67eb..0000000000
--- a/test/js/node/test/parallel/dgram-abort-closed.test.js
+++ /dev/null
@@ -1,20 +0,0 @@
-//#FILE: test-dgram-abort-closed.js
-//#SHA1: 8d3ab4d13dda99cdccb6994f165f2ddacf58360c
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("AbortController with closed dgram socket", () => {
- const controller = new AbortController();
- const socket = dgram.createSocket({ type: "udp4", signal: controller.signal });
-
- socket.close();
-
- // This should not throw or cause any issues
- expect(() => {
- controller.abort();
- }).not.toThrow();
-});
-
-//<#END_FILE: test-dgram-abort-closed.js
diff --git a/test/js/node/test/parallel/dgram-bind-default-address.test.js b/test/js/node/test/parallel/dgram-bind-default-address.test.js
deleted file mode 100644
index 542f335c6e..0000000000
--- a/test/js/node/test/parallel/dgram-bind-default-address.test.js
+++ /dev/null
@@ -1,82 +0,0 @@
-//#FILE: test-dgram-bind-default-address.js
-//#SHA1: f29269b15b1205e37cc43e02b76cc5d8eb3b70be
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-// Skip test in FreeBSD jails since 0.0.0.0 will resolve to default interface
-const inFreeBSDJail = process.platform === "freebsd" && process.env.CI === "true";
-if (inFreeBSDJail) {
- test.skip("In a FreeBSD jail");
-}
-
-test("UDP4 socket bind to default address", async () => {
- const socket = dgram.createSocket("udp4");
-
- await new Promise(resolve => {
- socket.bind(0, () => {
- const address = socket.address();
- expect(typeof address.port).toBe("number");
- expect(isFinite(address.port)).toBe(true);
- expect(address.port).toBeGreaterThan(0);
- expect(address.address).toBe("0.0.0.0");
- socket.close();
- resolve();
- });
- });
-});
-
-const hasIPv6 = (() => {
- try {
- const socket = dgram.createSocket("udp6");
- socket.close();
- return true;
- } catch {
- return false;
- }
-})();
-
-if (!hasIPv6) {
- test.skip("udp6 part of test, because no IPv6 support");
-} else {
- test("UDP6 socket bind to default address", async () => {
- const socket = dgram.createSocket("udp6");
-
- await new Promise(resolve => {
- socket.bind(0, () => {
- const address = socket.address();
- expect(typeof address.port).toBe("number");
- expect(isFinite(address.port)).toBe(true);
- expect(address.port).toBeGreaterThan(0);
- let addressValue = address.address;
- if (addressValue === "::ffff:0.0.0.0") addressValue = "::";
- expect(addressValue).toBe("::");
- socket.close();
- resolve();
- });
- });
- });
-}
-
-//<#END_FILE: test-dgram-bind-default-address.js
diff --git a/test/js/node/test/parallel/dgram-bind.test.js b/test/js/node/test/parallel/dgram-bind.test.js
deleted file mode 100644
index 0bf412718a..0000000000
--- a/test/js/node/test/parallel/dgram-bind.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-//#FILE: test-dgram-bind.js
-//#SHA1: 748fcd0fcb3ed5103b9072bba3019e560fb2799b
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("dgram socket bind", async () => {
- const socket = dgram.createSocket("udp4");
-
- await new Promise(resolve => {
- socket.on("listening", () => {
- expect(() => {
- socket.bind();
- }).toThrow(
- expect.objectContaining({
- code: "ERR_SOCKET_ALREADY_BOUND",
- name: "Error",
- message: expect.stringMatching(/^Socket is already bound$/),
- }),
- );
-
- socket.close();
- resolve();
- });
-
- const result = socket.bind(); // Should not throw.
-
- expect(result).toBe(socket); // Should have returned itself.
- });
-});
-
-//<#END_FILE: test-dgram-bind.js
diff --git a/test/js/node/test/parallel/dgram-bytes-length.test.js b/test/js/node/test/parallel/dgram-bytes-length.test.js
deleted file mode 100644
index 1c1bd1e219..0000000000
--- a/test/js/node/test/parallel/dgram-bytes-length.test.js
+++ /dev/null
@@ -1,42 +0,0 @@
-//#FILE: test-dgram-bytes-length.js
-//#SHA1: f899cc14c13e8c913645e204819cf99b867aec5c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("dgram bytes length", async () => {
- const message = Buffer.from("Some bytes");
- const client = dgram.createSocket("udp4");
-
- await new Promise((resolve, reject) => {
- client.send(message, 0, message.length, 41234, "localhost", function (err, bytes) {
- if (err) reject(err);
- expect(bytes).toBe(message.length);
- client.close();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-dgram-bytes-length.js
diff --git a/test/js/node/test/parallel/dgram-close-in-listening.test.js b/test/js/node/test/parallel/dgram-close-in-listening.test.js
deleted file mode 100644
index e669bea76c..0000000000
--- a/test/js/node/test/parallel/dgram-close-in-listening.test.js
+++ /dev/null
@@ -1,28 +0,0 @@
-//#FILE: test-dgram-close-in-listening.js
-//#SHA1: b37e742b092d70824b67c4ad4d3e1bb17a8c5cd5
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram socket closed before sendQueue is drained does not crash", done => {
- const buf = Buffer.alloc(1024, 42);
-
- const socket = dgram.createSocket("udp4");
-
- socket.on("listening", function () {
- socket.close();
- });
-
- // Get a random port for send
- const portGetter = dgram.createSocket("udp4").bind(0, "localhost", () => {
- // Adds a listener to 'listening' to send the data when
- // the socket is available
- socket.send(buf, 0, buf.length, portGetter.address().port, portGetter.address().address);
-
- portGetter.close();
- done(); // Signal test completion
- });
-});
-
-//<#END_FILE: test-dgram-close-in-listening.js
diff --git a/test/js/node/test/parallel/dgram-close.test.js b/test/js/node/test/parallel/dgram-close.test.js
deleted file mode 100644
index fe89cc0f66..0000000000
--- a/test/js/node/test/parallel/dgram-close.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-dgram-close.js
-//#SHA1: c396ba7a9c9ef45206989b36e4b5db0b95503e38
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// Flags: --expose-internals
-"use strict";
-// Ensure that if a dgram socket is closed before the DNS lookup completes, it
-// won't crash.
-
-const dgram = require("dgram");
-
-const buf = Buffer.alloc(1024, 42);
-
-test("dgram socket close before DNS lookup completes", done => {
- let socket = dgram.createSocket("udp4");
-
- // Get a random port for send
- const portGetter = dgram.createSocket("udp4");
-
- portGetter.bind(0, "localhost", () => {
- socket.send(buf, 0, buf.length, portGetter.address().port, portGetter.address().address);
-
- expect(socket.close()).toBe(socket);
-
- socket.on("close", () => {
- socket = null;
-
- // Verify that accessing handle after closure doesn't throw
- setImmediate(() => {
- setImmediate(() => {
- // We can't access internal symbols, so we'll just check if this doesn't throw
- expect(() => {
- console.log("Handle fd is: ", "placeholder");
- }).not.toThrow();
-
- portGetter.close();
- done();
- });
- });
- });
- });
-});
-
-//<#END_FILE: test-dgram-close.js
diff --git a/test/js/node/test/parallel/dgram-cluster-close-in-listening.test.js b/test/js/node/test/parallel/dgram-cluster-close-in-listening.test.js
deleted file mode 100644
index 3a882a49d2..0000000000
--- a/test/js/node/test/parallel/dgram-cluster-close-in-listening.test.js
+++ /dev/null
@@ -1,42 +0,0 @@
-//#FILE: test-dgram-cluster-close-in-listening.js
-//#SHA1: f288642fce76ef0138f8e44cd8eb09ded9dc4640
-//-----------------
-"use strict";
-// Ensure that closing dgram sockets in 'listening' callbacks of cluster workers
-// won't throw errors.
-
-const dgram = require("dgram");
-const cluster = require("cluster");
-
-if (process.platform === "win32") {
- it.skip("dgram clustering is currently not supported on windows.", () => {});
-} else {
- if (cluster.isPrimary) {
- test("Primary cluster forks workers", () => {
- for (let i = 0; i < 3; i += 1) {
- expect(() => cluster.fork()).not.toThrow();
- }
- });
- } else {
- test("Worker handles dgram socket lifecycle", done => {
- const socket = dgram.createSocket("udp4");
-
- socket.on("error", () => {
- done(new Error("Error event should not be called"));
- });
-
- socket.on("listening", () => {
- socket.close();
- });
-
- socket.on("close", () => {
- cluster.worker.disconnect();
- done();
- });
-
- socket.bind(0);
- });
- }
-}
-
-//<#END_FILE: test-dgram-cluster-close-in-listening.js
diff --git a/test/js/node/test/parallel/dgram-connect-send-callback-multi-buffer.test.js b/test/js/node/test/parallel/dgram-connect-send-callback-multi-buffer.test.js
deleted file mode 100644
index 2d014e97c6..0000000000
--- a/test/js/node/test/parallel/dgram-connect-send-callback-multi-buffer.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-dgram-connect-send-callback-multi-buffer.js
-//#SHA1: f30fbed996bbcd2adb268e9e3412a5f83119f8ae
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram connect send callback multi buffer", done => {
- const client = dgram.createSocket("udp4");
-
- const messageSent = jest.fn((err, bytes) => {
- expect(bytes).toBe(buf1.length + buf2.length);
- });
-
- const buf1 = Buffer.alloc(256, "x");
- const buf2 = Buffer.alloc(256, "y");
-
- client.on("listening", () => {
- const port = client.address().port;
- client.connect(port, () => {
- client.send([buf1, buf2], messageSent);
- });
- });
-
- client.on("message", (buf, info) => {
- const expected = Buffer.concat([buf1, buf2]);
- expect(buf.equals(expected)).toBe(true);
- client.close();
- expect(messageSent).toHaveBeenCalledTimes(1);
- done();
- });
-
- client.bind(0);
-});
-
-//<#END_FILE: test-dgram-connect-send-callback-multi-buffer.js
diff --git a/test/js/node/test/parallel/dgram-connect-send-default-host.test.js b/test/js/node/test/parallel/dgram-connect-send-default-host.test.js
deleted file mode 100644
index 6e597bae7c..0000000000
--- a/test/js/node/test/parallel/dgram-connect-send-default-host.test.js
+++ /dev/null
@@ -1,69 +0,0 @@
-//#FILE: test-dgram-connect-send-default-host.js
-//#SHA1: 78d734d664f2bf2f6376846bba7c909d8253c4dc
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-const toSend = [Buffer.alloc(256, "x"), Buffer.alloc(256, "y"), Buffer.alloc(256, "z"), "hello"];
-
-const received = [];
-
-test("dgram connect and send with default host", async () => {
- const client = dgram.createSocket("udp4");
- const server = dgram.createSocket("udp4");
-
- const serverListening = new Promise(resolve => {
- server.on("listening", resolve);
- });
-
- server.on("message", (buf, info) => {
- received.push(buf.toString());
-
- if (received.length === toSend.length * 2) {
- // The replies may arrive out of order -> sort them before checking.
- received.sort();
-
- const expected = toSend.concat(toSend).map(String).sort();
- expect(received).toEqual(expected);
- client.close();
- server.close();
- }
- });
-
- server.bind(0);
-
- await serverListening;
-
- const port = server.address().port;
- await new Promise((resolve, reject) => {
- client.connect(port, err => {
- if (err) reject(err);
- else resolve();
- });
- });
-
- client.send(toSend[0], 0, toSend[0].length);
- client.send(toSend[1]);
- client.send([toSend[2]]);
- client.send(toSend[3], 0, toSend[3].length);
-
- client.send(new Uint8Array(toSend[0]), 0, toSend[0].length);
- client.send(new Uint8Array(toSend[1]));
- client.send([new Uint8Array(toSend[2])]);
- client.send(new Uint8Array(Buffer.from(toSend[3])), 0, toSend[3].length);
-
- // Wait for all messages to be received
- await new Promise(resolve => {
- const checkInterval = setInterval(() => {
- if (received.length === toSend.length * 2) {
- clearInterval(checkInterval);
- resolve();
- }
- }, 100);
- });
-
- expect(received.length).toBe(toSend.length * 2);
-});
-
-//<#END_FILE: test-dgram-connect-send-default-host.js
diff --git a/test/js/node/test/parallel/dgram-connect-send-empty-array.test.js b/test/js/node/test/parallel/dgram-connect-send-empty-array.test.js
deleted file mode 100644
index 32b665f932..0000000000
--- a/test/js/node/test/parallel/dgram-connect-send-empty-array.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-dgram-connect-send-empty-array.js
-//#SHA1: 81de5b211c0e3be3158d2c06178577f39e62f0d1
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram.connect() and send empty array", () => {
- const client = dgram.createSocket("udp4");
-
- expect.assertions(1);
-
- return new Promise(resolve => {
- client.on("message", (buf, info) => {
- const expected = Buffer.alloc(0);
- expect(buf).toEqual(expected);
- client.close();
- resolve();
- });
-
- client.on("listening", () => {
- client.connect(client.address().port, "127.0.0.1", () => client.send([]));
- });
-
- client.bind(0);
- });
-});
-
-//<#END_FILE: test-dgram-connect-send-empty-array.js
diff --git a/test/js/node/test/parallel/dgram-connect-send-empty-buffer.test.js b/test/js/node/test/parallel/dgram-connect-send-empty-buffer.test.js
deleted file mode 100644
index 7c4209dbf1..0000000000
--- a/test/js/node/test/parallel/dgram-connect-send-empty-buffer.test.js
+++ /dev/null
@@ -1,28 +0,0 @@
-//#FILE: test-dgram-connect-send-empty-buffer.js
-//#SHA1: 08e8b667af8e6f97e6df2c95360a3a3aec05d435
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram connect and send empty buffer", done => {
- const client = dgram.createSocket("udp4");
-
- client.bind(0, () => {
- const port = client.address().port;
- client.connect(port, () => {
- const buf = Buffer.alloc(0);
- client.send(buf, 0, 0, err => {
- expect(err).toBeNull();
- });
- });
-
- client.on("message", buffer => {
- expect(buffer.length).toBe(0);
- client.close();
- done();
- });
- });
-});
-
-//<#END_FILE: test-dgram-connect-send-empty-buffer.js
diff --git a/test/js/node/test/parallel/dgram-connect-send-empty-packet.test.js b/test/js/node/test/parallel/dgram-connect-send-empty-packet.test.js
deleted file mode 100644
index d5f56ddb5d..0000000000
--- a/test/js/node/test/parallel/dgram-connect-send-empty-packet.test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-//#FILE: test-dgram-connect-send-empty-packet.js
-//#SHA1: 107d20a1e7a2628097091471ffdad75fc714b1fb
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram connect and send empty packet", done => {
- const client = dgram.createSocket("udp4");
-
- client.bind(0, () => {
- expect.hasAssertions();
- client.connect(client.address().port, () => {
- client.on("message", callback);
- const buf = Buffer.alloc(1);
-
- const interval = setInterval(() => {
- client.send(buf, 0, 0, callback);
- }, 10);
-
- function callback(firstArg) {
- // If client.send() callback, firstArg should be null.
- // If client.on('message') listener, firstArg should be a 0-length buffer.
- if (firstArg instanceof Buffer) {
- expect(firstArg.length).toBe(0);
- clearInterval(interval);
- client.close();
- done();
- }
- }
- });
- });
-});
-
-//<#END_FILE: test-dgram-connect-send-empty-packet.js
diff --git a/test/js/node/test/parallel/dgram-connect-send-multi-string-array.test.js b/test/js/node/test/parallel/dgram-connect-send-multi-string-array.test.js
deleted file mode 100644
index 7ae5672c0f..0000000000
--- a/test/js/node/test/parallel/dgram-connect-send-multi-string-array.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//#FILE: test-dgram-connect-send-multi-string-array.js
-//#SHA1: 611c15bc8089ffcae85adaa91bff5031c776a8ab
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram.createSocket can send multi-string array", done => {
- const socket = dgram.createSocket("udp4");
- const data = ["foo", "bar", "baz"];
-
- socket.on("message", (msg, rinfo) => {
- socket.close();
- expect(msg.toString()).toBe(data.join(""));
- done();
- });
-
- socket.bind(0, () => {
- socket.connect(socket.address().port, () => {
- socket.send(data);
- });
- });
-});
-
-//<#END_FILE: test-dgram-connect-send-multi-string-array.js
diff --git a/test/js/node/test/parallel/dgram-implicit-bind.test.js b/test/js/node/test/parallel/dgram-implicit-bind.test.js
deleted file mode 100644
index d733e2109f..0000000000
--- a/test/js/node/test/parallel/dgram-implicit-bind.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-dgram-implicit-bind.js
-//#SHA1: 3b390facaac3ee5e617c9fdc11acdb9f019fabfa
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("dgram implicit bind", async () => {
- const source = dgram.createSocket("udp4");
- const target = dgram.createSocket("udp4");
- let messages = 0;
-
- const messageHandler = jest.fn(buf => {
- if (buf.toString() === "abc") ++messages;
- if (buf.toString() === "def") ++messages;
- if (messages === 2) {
- source.close();
- target.close();
- }
- });
-
- target.on("message", messageHandler);
-
- await new Promise(resolve => {
- target.on("listening", resolve);
- target.bind(0);
- });
-
- // Second .send() call should not throw a bind error.
- const port = target.address().port;
- source.send(Buffer.from("abc"), 0, 3, port, "127.0.0.1");
- source.send(Buffer.from("def"), 0, 3, port, "127.0.0.1");
-
- // Wait for the messages to be processed
- await new Promise(resolve => setTimeout(resolve, 100));
-
- expect(messageHandler).toHaveBeenCalledTimes(2);
- expect(messages).toBe(2);
-});
-
-//<#END_FILE: test-dgram-implicit-bind.js
diff --git a/test/js/node/test/parallel/dgram-listen-after-bind.test.js b/test/js/node/test/parallel/dgram-listen-after-bind.test.js
deleted file mode 100644
index fd8faa3fe8..0000000000
--- a/test/js/node/test/parallel/dgram-listen-after-bind.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//#FILE: test-dgram-listen-after-bind.js
-//#SHA1: c1a91f2b83b502dd1abc4b46f023df6677fdf465
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("dgram listen after bind", done => {
- const socket = dgram.createSocket("udp4");
-
- socket.bind();
-
- let fired = false;
- const timer = setTimeout(() => {
- socket.close();
- }, 100);
-
- socket.on("listening", () => {
- clearTimeout(timer);
- fired = true;
- socket.close();
- });
-
- socket.on("close", () => {
- expect(fired).toBe(true);
- done();
- });
-});
-
-//<#END_FILE: test-dgram-listen-after-bind.js
diff --git a/test/js/node/test/parallel/dgram-oob-buffer.test.js b/test/js/node/test/parallel/dgram-oob-buffer.test.js
deleted file mode 100644
index 4d1eae8968..0000000000
--- a/test/js/node/test/parallel/dgram-oob-buffer.test.js
+++ /dev/null
@@ -1,63 +0,0 @@
-//#FILE: test-dgram-oob-buffer.js
-//#SHA1: a851da9a2178e92ce8315294d7cebf6eb78eb4bd
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// Some operating systems report errors when an UDP message is sent to an
-// unreachable host. This error can be reported by sendto() and even by
-// recvfrom(). Node should not propagate this error to the user.
-
-const dgram = require("dgram");
-
-test("UDP message sent to unreachable host should not propagate error", async () => {
- const socket = dgram.createSocket("udp4");
- const buf = Buffer.from([1, 2, 3, 4]);
-
- const portGetter = dgram.createSocket("udp4");
-
- await new Promise(resolve => {
- portGetter.bind(0, "localhost", () => {
- const { address, port } = portGetter.address();
-
- portGetter.close(() => {
- const sendCallback = jest.fn();
-
- socket.send(buf, 0, 0, port, address, sendCallback);
- socket.send(buf, 0, 4, port, address, sendCallback);
- socket.send(buf, 1, 3, port, address, sendCallback);
- socket.send(buf, 3, 1, port, address, sendCallback);
- // Since length of zero means nothing, don't error despite OOB.
- socket.send(buf, 4, 0, port, address, sendCallback);
-
- socket.close();
-
- // We expect the sendCallback to not be called
- expect(sendCallback).not.toHaveBeenCalled();
-
- resolve();
- });
- });
- });
-});
-
-//<#END_FILE: test-dgram-oob-buffer.js
diff --git a/test/js/node/test/parallel/dgram-ref.test.js b/test/js/node/test/parallel/dgram-ref.test.js
deleted file mode 100644
index bbb6602414..0000000000
--- a/test/js/node/test/parallel/dgram-ref.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-//#FILE: test-dgram-ref.js
-//#SHA1: b1a50859a1784815d575d8203f7da20fe8d07e50
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("Should not hang when creating UDP sockets", () => {
- // Should not hang, see https://github.com/nodejs/node-v0.x-archive/issues/1282
- expect(() => dgram.createSocket("udp4")).not.toThrow();
- expect(() => dgram.createSocket("udp6")).not.toThrow();
-});
-
-test("Test ref() on a closed socket", done => {
- // Test the case of ref()'ing a socket with no handle.
- const s = dgram.createSocket("udp4");
-
- s.close(() => {
- expect(() => s.ref()).not.toThrow();
- done();
- });
-});
-
-//<#END_FILE: test-dgram-ref.js
diff --git a/test/js/node/test/parallel/dgram-send-callback-buffer-empty-address.test.js b/test/js/node/test/parallel/dgram-send-callback-buffer-empty-address.test.js
deleted file mode 100644
index de86cfc036..0000000000
--- a/test/js/node/test/parallel/dgram-send-callback-buffer-empty-address.test.js
+++ /dev/null
@@ -1,27 +0,0 @@
-//#FILE: test-dgram-send-callback-buffer-empty-address.js
-//#SHA1: 5c76ad150693dcec8921099fa994f61aa783713c
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram send callback with buffer and empty address", done => {
- const client = dgram.createSocket("udp4");
-
- const buf = Buffer.alloc(256, "x");
-
- const onMessage = jest.fn(bytes => {
- expect(bytes).toBe(buf.length);
- client.close();
- done();
- });
-
- client.bind(0, () => {
- client.send(buf, client.address().port, error => {
- expect(error).toBeFalsy();
- onMessage(buf.length);
- });
- });
-});
-
-//<#END_FILE: test-dgram-send-callback-buffer-empty-address.js
diff --git a/test/js/node/test/parallel/dgram-send-callback-multi-buffer-empty-address.test.js b/test/js/node/test/parallel/dgram-send-callback-multi-buffer-empty-address.test.js
deleted file mode 100644
index 429e4cd9eb..0000000000
--- a/test/js/node/test/parallel/dgram-send-callback-multi-buffer-empty-address.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-dgram-send-callback-multi-buffer-empty-address.js
-//#SHA1: 61d00ee31b25f144989e0d3ced884a70f4e7d07a
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-let client;
-
-beforeEach(() => {
- client = dgram.createSocket("udp4");
-});
-
-afterEach(() => {
- client.close();
-});
-
-test("send callback multi buffer empty address", done => {
- const buf1 = Buffer.alloc(256, "x");
- const buf2 = Buffer.alloc(256, "y");
-
- client.on("listening", function () {
- const port = this.address().port;
- client.send([buf1, buf2], port, (err, bytes) => {
- expect(err).toBeNull();
- expect(bytes).toBe(buf1.length + buf2.length);
- });
- });
-
- client.on("message", buf => {
- const expected = Buffer.concat([buf1, buf2]);
- expect(buf.equals(expected)).toBe(true);
- done();
- });
-
- client.bind(0);
-});
-
-//<#END_FILE: test-dgram-send-callback-multi-buffer-empty-address.js
diff --git a/test/js/node/test/parallel/dgram-send-callback-multi-buffer.test.js b/test/js/node/test/parallel/dgram-send-callback-multi-buffer.test.js
deleted file mode 100644
index 36cf0d1eaa..0000000000
--- a/test/js/node/test/parallel/dgram-send-callback-multi-buffer.test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-//#FILE: test-dgram-send-callback-multi-buffer.js
-//#SHA1: 622d513f7897c216601b50a2960a8a36259b2595
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram send callback with multiple buffers", done => {
- const client = dgram.createSocket("udp4");
-
- const messageSent = jest.fn((err, bytes) => {
- expect(err).toBeNull();
- expect(bytes).toBe(buf1.length + buf2.length);
- });
-
- const buf1 = Buffer.alloc(256, "x");
- const buf2 = Buffer.alloc(256, "y");
-
- client.on("listening", () => {
- const port = client.address().port;
- client.send([buf1, buf2], port, "localhost", messageSent);
- });
-
- client.on("message", (buf, info) => {
- const expected = Buffer.concat([buf1, buf2]);
- expect(buf.equals(expected)).toBe(true);
- expect(messageSent).toHaveBeenCalledTimes(1);
- client.close();
- done();
- });
-
- client.bind(0);
-});
-
-//<#END_FILE: test-dgram-send-callback-multi-buffer.js
diff --git a/test/js/node/test/parallel/dgram-send-callback-recursive.test.js b/test/js/node/test/parallel/dgram-send-callback-recursive.test.js
deleted file mode 100644
index e42d990c9f..0000000000
--- a/test/js/node/test/parallel/dgram-send-callback-recursive.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-//#FILE: test-dgram-send-callback-recursive.js
-//#SHA1: fac7c8b29bd2122d4de273c54128b5a6100ad437
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-let received = 0;
-let sent = 0;
-const limit = 10;
-let async = false;
-let port;
-const chunk = "abc";
-
-test("dgram send callback recursive", done => {
- const client = dgram.createSocket("udp4");
-
- function onsend() {
- if (sent++ < limit) {
- client.send(chunk, 0, chunk.length, port, "127.0.0.1", onsend);
- } else {
- expect(async).toBe(true);
- }
- }
-
- client.on("listening", function () {
- port = this.address().port;
-
- process.nextTick(() => {
- async = true;
- });
-
- onsend();
- });
-
- client.on("message", (buf, info) => {
- received++;
- if (received === limit) {
- client.close();
- }
- });
-
- client.on("close", () => {
- expect(received).toBe(limit);
- done();
- });
-
- client.bind(0);
-});
-
-//<#END_FILE: test-dgram-send-callback-recursive.js
diff --git a/test/js/node/test/parallel/dgram-send-cb-quelches-error.test.js b/test/js/node/test/parallel/dgram-send-cb-quelches-error.test.js
deleted file mode 100644
index 96364d73fd..0000000000
--- a/test/js/node/test/parallel/dgram-send-cb-quelches-error.test.js
+++ /dev/null
@@ -1,44 +0,0 @@
-//#FILE: test-dgram-send-cb-quelches-error.js
-//#SHA1: 7525b0a8af0df192c36a848b23332424245d2937
-//-----------------
-"use strict";
-
-const assert = require("assert");
-const dgram = require("dgram");
-const dns = require("dns");
-
-test("dgram send callback quelches error", () => {
- const socket = dgram.createSocket("udp4");
- const buffer = Buffer.from("gary busey");
-
- dns.setServers([]);
-
- const onEvent = jest.fn(() => {
- throw new Error("Error should not be emitted if there is callback");
- });
-
- socket.once("error", onEvent);
-
- // assert that:
- // * callbacks act as "error" listeners if given.
- // * error is never emitter for missing dns entries
- // if a callback that handles error is present
- // * error is emitted if a callback with no argument is passed
- socket.send(buffer, 0, buffer.length, 100, "dne.example.com", callbackOnly);
-
- function callbackOnly(err) {
- expect(err).toBeTruthy();
- socket.removeListener("error", onEvent);
- socket.on("error", onError);
- socket.send(buffer, 0, buffer.length, 100, "dne.invalid");
- }
-
- function onError(err) {
- expect(err).toBeTruthy();
- socket.close();
- }
-
- expect(onEvent).not.toHaveBeenCalled();
-});
-
-//<#END_FILE: test-dgram-send-cb-quelches-error.js
diff --git a/test/js/node/test/parallel/dgram-send-empty-buffer.test.js b/test/js/node/test/parallel/dgram-send-empty-buffer.test.js
deleted file mode 100644
index 3dcd6ffe3b..0000000000
--- a/test/js/node/test/parallel/dgram-send-empty-buffer.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//#FILE: test-dgram-send-empty-buffer.js
-//#SHA1: ac60fc545252e681b648a7038d1bebe46ffbbac0
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("dgram send empty buffer", done => {
- const client = dgram.createSocket("udp4");
-
- client.bind(0, () => {
- const port = client.address().port;
-
- client.on("message", buffer => {
- expect(buffer.length).toBe(0);
- clearInterval(interval);
- client.close();
- done();
- });
-
- const buf = Buffer.alloc(0);
- const interval = setInterval(() => {
- client.send(buf, 0, 0, port, "127.0.0.1", () => {
- // This callback is expected to be called
- });
- }, 10);
- });
-});
-
-//<#END_FILE: test-dgram-send-empty-buffer.js
diff --git a/test/js/node/test/parallel/dgram-send-empty-packet.test.js b/test/js/node/test/parallel/dgram-send-empty-packet.test.js
deleted file mode 100644
index 07802512c7..0000000000
--- a/test/js/node/test/parallel/dgram-send-empty-packet.test.js
+++ /dev/null
@@ -1,34 +0,0 @@
-//#FILE: test-dgram-send-empty-packet.js
-//#SHA1: f39fb8a7245893f0f6f55aeb110d458e2f265013
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("send empty packet", done => {
- const client = dgram.createSocket("udp4");
-
- client.bind(0, () => {
- client.on("message", jest.fn(callback));
-
- const port = client.address().port;
- const buf = Buffer.alloc(1);
-
- const interval = setInterval(() => {
- client.send(buf, 0, 0, port, "127.0.0.1", jest.fn(callback));
- }, 10);
-
- function callback(firstArg) {
- // If client.send() callback, firstArg should be null.
- // If client.on('message') listener, firstArg should be a 0-length buffer.
- if (firstArg instanceof Buffer) {
- expect(firstArg.length).toBe(0);
- clearInterval(interval);
- client.close();
- done();
- }
- }
- });
-});
-
-//<#END_FILE: test-dgram-send-empty-packet.js
diff --git a/test/js/node/test/parallel/dgram-send-multi-buffer-copy.test.js b/test/js/node/test/parallel/dgram-send-multi-buffer-copy.test.js
deleted file mode 100644
index b9baba6443..0000000000
--- a/test/js/node/test/parallel/dgram-send-multi-buffer-copy.test.js
+++ /dev/null
@@ -1,42 +0,0 @@
-//#FILE: test-dgram-send-multi-buffer-copy.js
-//#SHA1: 6adf8291a5dd40cb6a71ad3779f0d26d2150249a
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-let client;
-
-beforeEach(() => {
- client = dgram.createSocket("udp4");
-});
-
-afterEach(() => {
- client.close();
-});
-
-test("dgram send multi buffer copy", done => {
- const onMessage = jest.fn((err, bytes) => {
- expect(bytes).toBe(buf1.length + buf2.length);
- });
-
- const buf1 = Buffer.alloc(256, "x");
- const buf2 = Buffer.alloc(256, "y");
-
- client.on("listening", function () {
- const toSend = [buf1, buf2];
- client.send(toSend, this.address().port, "127.0.0.1", onMessage);
- toSend.splice(0, 2);
- });
-
- client.on("message", (buf, info) => {
- const expected = Buffer.concat([buf1, buf2]);
- expect(buf.equals(expected)).toBe(true);
- expect(onMessage).toHaveBeenCalledTimes(1);
- done();
- });
-
- client.bind(0);
-});
-
-//<#END_FILE: test-dgram-send-multi-buffer-copy.js
diff --git a/test/js/node/test/parallel/dgram-send-multi-string-array.test.js b/test/js/node/test/parallel/dgram-send-multi-string-array.test.js
deleted file mode 100644
index 804ea7c285..0000000000
--- a/test/js/node/test/parallel/dgram-send-multi-string-array.test.js
+++ /dev/null
@@ -1,23 +0,0 @@
-//#FILE: test-dgram-send-multi-string-array.js
-//#SHA1: 8ea2007ac52bfde3742aabe352aab19bf91a4ac2
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-test("dgram send multiple strings as array", done => {
- const socket = dgram.createSocket("udp4");
- const data = ["foo", "bar", "baz"];
-
- socket.on("message", (msg, rinfo) => {
- socket.close();
- expect(msg.toString()).toBe(data.join(""));
- done();
- });
-
- socket.bind(() => {
- socket.send(data, socket.address().port, "localhost");
- });
-});
-
-//<#END_FILE: test-dgram-send-multi-string-array.js
diff --git a/test/js/node/test/parallel/dgram-sendto.test.js b/test/js/node/test/parallel/dgram-sendto.test.js
deleted file mode 100644
index e3b3d88c2a..0000000000
--- a/test/js/node/test/parallel/dgram-sendto.test.js
+++ /dev/null
@@ -1,70 +0,0 @@
-//#FILE: test-dgram-sendto.js
-//#SHA1: 8047210c86bed6536f5ff3132e228a2ee9d0bb11
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-
-describe("dgram.sendto", () => {
- let socket;
-
- beforeEach(() => {
- socket = dgram.createSocket("udp4");
- });
-
- afterEach(() => {
- socket.close();
- });
-
- test("throws when called with no arguments", () => {
- expect(() => socket.sendto()).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-
- test('throws when "length" argument is invalid', () => {
- expect(() => socket.sendto("buffer", 1, "offset", "port", "address", "cb")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-
- test('throws when "offset" argument is invalid', () => {
- expect(() => socket.sendto("buffer", "offset", 1, "port", "address", "cb")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-
- test('throws when "address" argument is invalid', () => {
- expect(() => socket.sendto("buffer", 1, 1, 10, false, "cb")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-
- test('throws when "port" argument is invalid', () => {
- expect(() => socket.sendto("buffer", 1, 1, false, "address", "cb")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-dgram-sendto.js
diff --git a/test/js/node/test/parallel/dgram-udp4.test.js b/test/js/node/test/parallel/dgram-udp4.test.js
deleted file mode 100644
index 27be2e63fc..0000000000
--- a/test/js/node/test/parallel/dgram-udp4.test.js
+++ /dev/null
@@ -1,81 +0,0 @@
-//#FILE: test-dgram-udp4.js
-//#SHA1: 588735591046212fc512f69d9001ccb820c57a71
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-const message_to_send = "A message to send";
-const localhostIPv4 = "127.0.0.1";
-
-test("UDP4 server and client communication", async () => {
- const server = dgram.createSocket("udp4");
-
- const serverMessagePromise = new Promise(resolve => {
- server.on("message", (msg, rinfo) => {
- expect(rinfo.address).toBe(localhostIPv4);
- expect(msg.toString()).toBe(message_to_send);
- server.send(msg, 0, msg.length, rinfo.port, rinfo.address);
- resolve();
- });
- });
-
- const listeningPromise = new Promise(resolve => {
- server.on("listening", resolve);
- });
-
- server.bind(0);
-
- await listeningPromise;
-
- const client = dgram.createSocket("udp4");
- const port = server.address().port;
-
- const clientMessagePromise = new Promise(resolve => {
- client.on("message", (msg, rinfo) => {
- expect(rinfo.address).toBe(localhostIPv4);
- expect(rinfo.port).toBe(port);
- expect(msg.toString()).toBe(message_to_send);
- resolve();
- });
- });
-
- client.send(message_to_send, 0, message_to_send.length, port, "localhost");
-
- await Promise.all([serverMessagePromise, clientMessagePromise]);
-
- const clientClosePromise = new Promise(resolve => {
- client.on("close", resolve);
- });
-
- const serverClosePromise = new Promise(resolve => {
- server.on("close", resolve);
- });
-
- client.close();
- server.close();
-
- await Promise.all([clientClosePromise, serverClosePromise]);
-});
-
-//<#END_FILE: test-dgram-udp4.js
diff --git a/test/js/node/test/parallel/dgram-unref-in-cluster.test.js b/test/js/node/test/parallel/dgram-unref-in-cluster.test.js
deleted file mode 100644
index dcca2428e3..0000000000
--- a/test/js/node/test/parallel/dgram-unref-in-cluster.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-dgram-unref-in-cluster.js
-//#SHA1: eca71c33b1bf5be34a28e6cc82df49c73e775153
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-const cluster = require("cluster");
-
-if (process.platform === "win32") {
- test.skip("dgram clustering is currently not supported on Windows.");
-} else {
- if (cluster.isPrimary) {
- test("dgram unref in cluster", () => {
- cluster.fork();
- });
- } else {
- test("dgram unref in cluster worker", () => {
- const socket = dgram.createSocket("udp4");
- socket.unref();
- socket.bind();
-
- return new Promise(resolve => {
- socket.on("listening", () => {
- const sockets = process.getActiveResourcesInfo().filter(item => {
- return item === "UDPWrap";
- });
- expect(sockets.length).toBe(0);
- process.disconnect();
- resolve();
- });
- });
- });
- }
-}
-
-//<#END_FILE: test-dgram-unref-in-cluster.js
diff --git a/test/js/node/test/parallel/dgram-unref.test.js b/test/js/node/test/parallel/dgram-unref.test.js
deleted file mode 100644
index ff11989d7b..0000000000
--- a/test/js/node/test/parallel/dgram-unref.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-dgram-unref.js
-//#SHA1: 97b218a9107def7e2cc28e595f84f9a05a606850
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const dgram = require("dgram");
-
-test("unref() a socket with a handle", () => {
- const s = dgram.createSocket("udp4");
- s.bind();
- s.unref();
- // No assertion needed, just checking that it doesn't throw
-});
-
-test("unref() a socket with no handle", done => {
- const s = dgram.createSocket("udp4");
- s.close(() => {
- s.unref();
- done();
- });
-});
-
-test("setTimeout should not be called", () => {
- const mockCallback = jest.fn();
- setTimeout(mockCallback, 1000).unref();
- expect(mockCallback).not.toHaveBeenCalled();
-});
-
-//<#END_FILE: test-dgram-unref.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-has-subscribers.test.js b/test/js/node/test/parallel/diagnostics-channel-has-subscribers.test.js
deleted file mode 100644
index 2e2f119c73..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-has-subscribers.test.js
+++ /dev/null
@@ -1,18 +0,0 @@
-//#FILE: test-diagnostics-channel-has-subscribers.js
-//#SHA1: 8040abda8d37916d6f6d5f3966e8c531d1770e1a
-//-----------------
-"use strict";
-
-const { channel, hasSubscribers } = require("diagnostics_channel");
-
-describe("diagnostics_channel", () => {
- test("hasSubscribers returns correct state", () => {
- const dc = channel("test");
- expect(hasSubscribers("test")).toBe(false);
-
- dc.subscribe(() => {});
- expect(hasSubscribers("test")).toBe(true);
- });
-});
-
-//<#END_FILE: test-diagnostics-channel-has-subscribers.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-http-server-start.test.js b/test/js/node/test/parallel/diagnostics-channel-http-server-start.test.js
deleted file mode 100644
index a5446eec21..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-http-server-start.test.js
+++ /dev/null
@@ -1,76 +0,0 @@
-//#FILE: test-diagnostics-channel-http-server-start.js
-//#SHA1: 5540b17246152983b832ddafa0be55502ee83a23
-//-----------------
-"use strict";
-
-const { AsyncLocalStorage } = require("async_hooks");
-const dc = require("diagnostics_channel");
-const http = require("http");
-
-const als = new AsyncLocalStorage();
-let context;
-
-describe("diagnostics_channel http server start", () => {
- let server;
- let request;
- let response;
-
- beforeAll(() => {
- // Bind requests to an AsyncLocalStorage context
- dc.subscribe("http.server.request.start", message => {
- als.enterWith(message);
- context = message;
- });
-
- // When the request ends, verify the context has been maintained
- // and that the messages contain the expected data
- dc.subscribe("http.server.response.finish", message => {
- const data = {
- request,
- response,
- server,
- socket: request.socket,
- };
-
- // Context is maintained
- compare(als.getStore(), context);
-
- compare(context, data);
- compare(message, data);
- });
-
- server = http.createServer((req, res) => {
- request = req;
- response = res;
-
- setTimeout(() => {
- res.end("done");
- }, 1);
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- it("should maintain context and contain expected data", done => {
- server.listen(() => {
- const { port } = server.address();
- http.get(`http://localhost:${port}`, res => {
- res.resume();
- res.on("end", () => {
- done();
- });
- });
- });
- });
-});
-
-function compare(a, b) {
- expect(a.request).toBe(b.request);
- expect(a.response).toBe(b.response);
- expect(a.socket).toBe(b.socket);
- expect(a.server).toBe(b.server);
-}
-
-//<#END_FILE: test-diagnostics-channel-http-server-start.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-object-channel-pub-sub.test.js b/test/js/node/test/parallel/diagnostics-channel-object-channel-pub-sub.test.js
deleted file mode 100644
index ae95ea487b..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-object-channel-pub-sub.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-//#FILE: test-diagnostics-channel-object-channel-pub-sub.js
-//#SHA1: 185a8134da179dfda5f6b2d1a1a2622752431a90
-//-----------------
-"use strict";
-
-const dc = require("diagnostics_channel");
-const { Channel } = dc;
-
-const input = {
- foo: "bar",
-};
-
-test("Channel creation and subscription", () => {
- // Should not have named channel
- expect(dc.hasSubscribers("test")).toBe(false);
-
- // Individual channel objects can be created to avoid future lookups
- const channel = dc.channel("test");
- expect(channel).toBeInstanceOf(Channel);
-
- // No subscribers yet, should not publish
- expect(channel.hasSubscribers).toBe(false);
-
- const subscriber = jest.fn((message, name) => {
- expect(name).toBe(channel.name);
- expect(message).toEqual(input);
- });
-
- // Now there's a subscriber, should publish
- channel.subscribe(subscriber);
- expect(channel.hasSubscribers).toBe(true);
-
- // The ActiveChannel prototype swap should not fail instanceof
- expect(channel).toBeInstanceOf(Channel);
-
- // Should trigger the subscriber once
- channel.publish(input);
- expect(subscriber).toHaveBeenCalledTimes(1);
-
- // Should not publish after subscriber is unsubscribed
- expect(channel.unsubscribe(subscriber)).toBe(true);
- expect(channel.hasSubscribers).toBe(false);
-
- // unsubscribe() should return false when subscriber is not found
- expect(channel.unsubscribe(subscriber)).toBe(false);
-});
-
-test("Invalid subscriber", () => {
- const channel = dc.channel("test");
- expect(() => {
- channel.subscribe(null);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-diagnostics-channel-object-channel-pub-sub.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-pub-sub.test.js b/test/js/node/test/parallel/diagnostics-channel-pub-sub.test.js
deleted file mode 100644
index f20d19d136..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-pub-sub.test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-//#FILE: test-diagnostics-channel-pub-sub.js
-//#SHA1: cc5eee7f44117c2fd8446e8050ac19f5341f85a5
-//-----------------
-"use strict";
-
-const dc = require("diagnostics_channel");
-const { Channel } = dc;
-
-const name = "test";
-const input = {
- foo: "bar",
-};
-
-test("diagnostics_channel pub/sub functionality", () => {
- // Individual channel objects can be created to avoid future lookups
- const channel = dc.channel(name);
- expect(channel).toBeInstanceOf(Channel);
-
- // No subscribers yet, should not publish
- expect(channel.hasSubscribers).toBeFalsy();
-
- const subscriber = jest.fn((message, channelName) => {
- expect(channelName).toBe(channel.name);
- expect(message).toEqual(input);
- });
-
- // Now there's a subscriber, should publish
- dc.subscribe(name, subscriber);
- expect(channel.hasSubscribers).toBeTruthy();
-
- // The ActiveChannel prototype swap should not fail instanceof
- expect(channel).toBeInstanceOf(Channel);
-
- // Should trigger the subscriber once
- channel.publish(input);
- expect(subscriber).toHaveBeenCalledTimes(1);
-
- // Should not publish after subscriber is unsubscribed
- expect(dc.unsubscribe(name, subscriber)).toBeTruthy();
- expect(channel.hasSubscribers).toBeFalsy();
-
- // unsubscribe() should return false when subscriber is not found
- expect(dc.unsubscribe(name, subscriber)).toBeFalsy();
-
- expect(() => {
- dc.subscribe(name, null);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.any(String),
- }),
- );
-
- // Reaching zero subscribers should not delete from the channels map as there
- // will be no more weakref to incRef if another subscribe happens while the
- // channel object itself exists.
- channel.subscribe(subscriber);
- channel.unsubscribe(subscriber);
- channel.subscribe(subscriber);
-});
-
-//<#END_FILE: test-diagnostics-channel-pub-sub.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-symbol-named.test.js b/test/js/node/test/parallel/diagnostics-channel-symbol-named.test.js
deleted file mode 100644
index d2d6065687..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-symbol-named.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-diagnostics-channel-symbol-named.js
-//#SHA1: e0ae87b803333891439e11fa2306eefd23b507e4
-//-----------------
-"use strict";
-
-const dc = require("diagnostics_channel");
-
-const input = {
- foo: "bar",
-};
-
-const symbol = Symbol("test");
-
-// Individual channel objects can be created to avoid future lookups
-const channel = dc.channel(symbol);
-
-test("diagnostics channel with symbol name", () => {
- // Expect two successful publishes later
- const subscriber = jest.fn((message, name) => {
- expect(name).toBe(symbol);
- expect(message).toEqual(input);
- });
-
- channel.subscribe(subscriber);
-
- channel.publish(input);
-
- expect(subscriber).toHaveBeenCalledTimes(1);
-});
-
-test("channel creation with invalid argument", () => {
- expect(() => {
- dc.channel(null);
- }).toThrow(
- expect.objectContaining({
- name: "TypeError",
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-diagnostics-channel-symbol-named.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-sync-unsubscribe.test.js b/test/js/node/test/parallel/diagnostics-channel-sync-unsubscribe.test.js
deleted file mode 100644
index eb5ceea25b..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-sync-unsubscribe.test.js
+++ /dev/null
@@ -1,24 +0,0 @@
-//#FILE: test-diagnostics-channel-sync-unsubscribe.js
-//#SHA1: 85d73bd9ce82a4293daca05617b2aece359745ff
-//-----------------
-"use strict";
-
-const dc = require("node:diagnostics_channel");
-
-const channel_name = "test:channel";
-const published_data = "some message";
-
-test("diagnostics channel sync unsubscribe", () => {
- const onMessageHandler = jest.fn(() => dc.unsubscribe(channel_name, onMessageHandler));
-
- dc.subscribe(channel_name, onMessageHandler);
-
- // This must not throw.
- expect(() => {
- dc.channel(channel_name).publish(published_data);
- }).not.toThrow();
-
- expect(onMessageHandler).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-diagnostics-channel-sync-unsubscribe.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-callback-run-stores.test.js b/test/js/node/test/parallel/diagnostics-channel-tracing-channel-callback-run-stores.test.js
deleted file mode 100644
index 15fcdedaf9..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-callback-run-stores.test.js
+++ /dev/null
@@ -1,45 +0,0 @@
-//#FILE: test-diagnostics-channel-tracing-channel-callback-run-stores.js
-//#SHA1: 8ed3a87eb9d6c1a3a624245ce5f430b7e3730d2d
-//-----------------
-"use strict";
-
-const { AsyncLocalStorage } = require("async_hooks");
-const dc = require("diagnostics_channel");
-
-const channel = dc.tracingChannel("test");
-const store = new AsyncLocalStorage();
-
-const firstContext = { foo: "bar" };
-const secondContext = { baz: "buz" };
-
-test("tracing channel callback run stores", async () => {
- const startBindStoreMock = jest.fn(() => firstContext);
- const asyncStartBindStoreMock = jest.fn(() => secondContext);
-
- channel.start.bindStore(store, startBindStoreMock);
- channel.asyncStart.bindStore(store, asyncStartBindStoreMock);
-
- expect(store.getStore()).toBeUndefined();
-
- await new Promise(resolve => {
- channel.traceCallback(
- cb => {
- expect(store.getStore()).toEqual(firstContext);
- setImmediate(cb);
- },
- 0,
- {},
- null,
- () => {
- expect(store.getStore()).toEqual(secondContext);
- resolve();
- },
- );
- });
-
- expect(store.getStore()).toBeUndefined();
- expect(startBindStoreMock).toHaveBeenCalledTimes(1);
- expect(asyncStartBindStoreMock).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-diagnostics-channel-tracing-channel-callback-run-stores.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-promise-run-stores.test.js b/test/js/node/test/parallel/diagnostics-channel-tracing-channel-promise-run-stores.test.js
deleted file mode 100644
index 6c75c54789..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-promise-run-stores.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-diagnostics-channel-tracing-channel-promise-run-stores.js
-//#SHA1: 4e5abb65d92cb3e649073803971180493c1a30ca
-//-----------------
-"use strict";
-
-const { setTimeout } = require("node:timers/promises");
-const { AsyncLocalStorage } = require("async_hooks");
-const dc = require("diagnostics_channel");
-
-const channel = dc.tracingChannel("test");
-const store = new AsyncLocalStorage();
-
-const firstContext = { foo: "bar" };
-const secondContext = { baz: "buz" };
-
-test("tracingChannel promise run stores", async () => {
- const startBindStoreMock = jest.fn(() => firstContext);
- const asyncStartBindStoreMock = jest.fn(() => secondContext);
-
- channel.start.bindStore(store, startBindStoreMock);
- channel.asyncStart.bindStore(store, asyncStartBindStoreMock);
-
- expect(store.getStore()).toBeUndefined();
-
- await channel.tracePromise(async () => {
- expect(store.getStore()).toEqual(firstContext);
- await setTimeout(1);
- // Should _not_ switch to second context as promises don't have an "after"
- // point at which to do a runStores.
- expect(store.getStore()).toEqual(firstContext);
- });
-
- expect(store.getStore()).toBeUndefined();
-
- expect(startBindStoreMock).toHaveBeenCalledTimes(1);
- expect(asyncStartBindStoreMock).not.toHaveBeenCalled();
-});
-
-//<#END_FILE: test-diagnostics-channel-tracing-channel-promise-run-stores.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-promise.test.js b/test/js/node/test/parallel/diagnostics-channel-tracing-channel-promise.test.js
deleted file mode 100644
index 032a552cb6..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-promise.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-diagnostics-channel-tracing-channel-promise.js
-//#SHA1: 6a692d8400685da6c930b662562adb3e36b2da9a
-//-----------------
-"use strict";
-
-const dc = require("diagnostics_channel");
-
-const channel = dc.tracingChannel("test");
-
-const expectedResult = { foo: "bar" };
-const input = { foo: "bar" };
-const thisArg = { baz: "buz" };
-
-function check(found) {
- expect(found).toEqual(input);
-}
-
-function checkAsync(found) {
- check(found);
- expect(found.error).toBeUndefined();
- expect(found.result).toEqual(expectedResult);
-}
-
-const handlers = {
- start: jest.fn(check),
- end: jest.fn(check),
- asyncStart: jest.fn(checkAsync),
- asyncEnd: jest.fn(checkAsync),
- error: jest.fn(),
-};
-
-test("diagnostics_channel tracing channel promise", async () => {
- channel.subscribe(handlers);
-
- await channel.tracePromise(
- function (value) {
- expect(this).toEqual(thisArg);
- return Promise.resolve(value);
- },
- input,
- thisArg,
- expectedResult,
- );
-
- expect(handlers.start).toHaveBeenCalledTimes(1);
- expect(handlers.end).toHaveBeenCalledTimes(1);
- expect(handlers.asyncStart).toHaveBeenCalledTimes(1);
- expect(handlers.asyncEnd).toHaveBeenCalledTimes(1);
- expect(handlers.error).not.toHaveBeenCalled();
-
- const value = await channel.tracePromise(
- function (value) {
- expect(this).toEqual(thisArg);
- return Promise.resolve(value);
- },
- input,
- thisArg,
- expectedResult,
- );
-
- expect(value).toEqual(expectedResult);
-});
-
-//<#END_FILE: test-diagnostics-channel-tracing-channel-promise.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync-error.test.js b/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync-error.test.js
deleted file mode 100644
index 2906e447cf..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync-error.test.js
+++ /dev/null
@@ -1,52 +0,0 @@
-//#FILE: test-diagnostics-channel-tracing-channel-sync-error.js
-//#SHA1: faf279d48c76f3c97ddf7e258df9ed49154a4cac
-//-----------------
-"use strict";
-
-const dc = require("diagnostics_channel");
-
-const channel = dc.tracingChannel("test");
-
-const expectedError = new Error("test");
-const input = { foo: "bar" };
-const thisArg = { baz: "buz" };
-
-function check(found) {
- expect(found).toEqual(input);
-}
-
-test("traceSync with error", () => {
- const handlers = {
- start: jest.fn(check),
- end: jest.fn(check),
- asyncStart: jest.fn(),
- asyncEnd: jest.fn(),
- error: jest.fn(found => {
- check(found);
- expect(found.error).toBe(expectedError);
- }),
- };
-
- channel.subscribe(handlers);
-
- expect(() => {
- channel.traceSync(
- function (err) {
- expect(this).toEqual(thisArg);
- expect(err).toBe(expectedError);
- throw err;
- },
- input,
- thisArg,
- expectedError,
- );
- }).toThrow(expectedError);
-
- expect(handlers.start).toHaveBeenCalledTimes(1);
- expect(handlers.end).toHaveBeenCalledTimes(1);
- expect(handlers.asyncStart).not.toHaveBeenCalled();
- expect(handlers.asyncEnd).not.toHaveBeenCalled();
- expect(handlers.error).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-diagnostics-channel-tracing-channel-sync-error.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync-run-stores.test.js b/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync-run-stores.test.js
deleted file mode 100644
index ed7212e92d..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync-run-stores.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-diagnostics-channel-tracing-channel-sync-run-stores.js
-//#SHA1: 51ffe2c7cb7160b565bfe6bbca0d29005a6bf876
-//-----------------
-"use strict";
-
-const { AsyncLocalStorage } = require("async_hooks");
-const dc = require("diagnostics_channel");
-
-const channel = dc.tracingChannel("test");
-const store = new AsyncLocalStorage();
-
-const context = { foo: "bar" };
-
-test("diagnostics channel tracing channel sync run stores", () => {
- const startCallback = jest.fn(() => context);
- channel.start.bindStore(store, startCallback);
-
- expect(store.getStore()).toBeUndefined();
-
- const traceCallback = jest.fn(() => {
- expect(store.getStore()).toEqual(context);
- });
-
- channel.traceSync(traceCallback);
-
- expect(store.getStore()).toBeUndefined();
-
- expect(startCallback).toHaveBeenCalledTimes(1);
- expect(traceCallback).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-diagnostics-channel-tracing-channel-sync-run-stores.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync.test.js b/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync.test.js
deleted file mode 100644
index f4a4c3b923..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-tracing-channel-sync.test.js
+++ /dev/null
@@ -1,80 +0,0 @@
-//#FILE: test-diagnostics-channel-tracing-channel-sync.js
-//#SHA1: fad9bfb35032ed67643b026f8e79611d8197a131
-//-----------------
-"use strict";
-
-const dc = require("diagnostics_channel");
-
-const channel = dc.tracingChannel("test");
-
-const expectedResult = { foo: "bar" };
-const input = { foo: "bar" };
-const thisArg = { baz: "buz" };
-const arg = { baz: "buz" };
-
-function check(found) {
- expect(found).toBe(input);
-}
-
-describe("diagnostics_channel tracing channel sync", () => {
- const handlers = {
- start: jest.fn(check),
- end: jest.fn(found => {
- check(found);
- expect(found.result).toBe(expectedResult);
- }),
- asyncStart: jest.fn(),
- asyncEnd: jest.fn(),
- error: jest.fn(),
- };
-
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- test("channel subscription and traceSync", () => {
- expect(channel.start.hasSubscribers).toBe(false);
- channel.subscribe(handlers);
- expect(channel.start.hasSubscribers).toBe(true);
-
- const result1 = channel.traceSync(
- function (arg1) {
- expect(arg1).toBe(arg);
- expect(this).toBe(thisArg);
- return expectedResult;
- },
- input,
- thisArg,
- arg,
- );
-
- expect(result1).toBe(expectedResult);
- expect(handlers.start).toHaveBeenCalledTimes(1);
- expect(handlers.end).toHaveBeenCalledTimes(1);
- expect(handlers.asyncStart).not.toHaveBeenCalled();
- expect(handlers.asyncEnd).not.toHaveBeenCalled();
- expect(handlers.error).not.toHaveBeenCalled();
- });
-
- test("channel unsubscription", () => {
- channel.unsubscribe(handlers);
- expect(channel.start.hasSubscribers).toBe(false);
-
- const result2 = channel.traceSync(
- function (arg1) {
- expect(arg1).toBe(arg);
- expect(this).toBe(thisArg);
- return expectedResult;
- },
- input,
- thisArg,
- arg,
- );
-
- expect(result2).toBe(expectedResult);
- expect(handlers.start).not.toHaveBeenCalled();
- expect(handlers.end).not.toHaveBeenCalled();
- });
-});
-
-//<#END_FILE: test-diagnostics-channel-tracing-channel-sync.js
diff --git a/test/js/node/test/parallel/diagnostics-channel-udp.test.js b/test/js/node/test/parallel/diagnostics-channel-udp.test.js
deleted file mode 100644
index 449df21666..0000000000
--- a/test/js/node/test/parallel/diagnostics-channel-udp.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-//#FILE: test-diagnostics-channel-udp.js
-//#SHA1: 13d46f3f2404ee7cd53a551b90fc1ced191d4a81
-//-----------------
-"use strict";
-
-const dgram = require("dgram");
-const dc = require("diagnostics_channel");
-
-const udpSocketChannel = dc.channel("udp.socket");
-
-const isUDPSocket = socket => socket instanceof dgram.Socket;
-
-test("udp.socket channel emits UDP socket", () => {
- const channelCallback = jest.fn(({ socket }) => {
- expect(isUDPSocket(socket)).toBe(true);
- });
-
- udpSocketChannel.subscribe(channelCallback);
-
- const socket = dgram.createSocket("udp4");
- socket.close();
-
- expect(channelCallback).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-diagnostics-channel-udp.js
diff --git a/test/js/node/test/parallel/dns-resolve-promises.test.js b/test/js/node/test/parallel/dns-resolve-promises.test.js
deleted file mode 100644
index 737ae7e467..0000000000
--- a/test/js/node/test/parallel/dns-resolve-promises.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//#FILE: test-dns-resolve-promises.js
-//#SHA1: ca56d4fe55a765a3e9db340661c96d8b1fd7a7a9
-//-----------------
-"use strict";
-
-const dns = require("dns");
-
-test("DNS resolve promises error handling", async () => {
- // Mock the dns.promises.resolve function to simulate an error
- dns.promises.resolve = jest.fn().mockRejectedValue({
- code: "EPERM",
- syscall: "queryA",
- hostname: "example.org",
- });
-
- await expect(dns.promises.resolve("example.org")).rejects.toMatchObject({
- code: "EPERM",
- syscall: "queryA",
- hostname: "example.org",
- });
-
- expect(dns.promises.resolve).toHaveBeenCalledWith("example.org");
-});
-
-//<#END_FILE: test-dns-resolve-promises.js
diff --git a/test/js/node/test/parallel/domain-crypto.test.js b/test/js/node/test/parallel/domain-crypto.test.js
deleted file mode 100644
index 406da90236..0000000000
--- a/test/js/node/test/parallel/domain-crypto.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-//#FILE: test-domain-crypto.js
-//#SHA1: d7d6352f0f2684220baef0cfa1029278c3f05f8f
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const crypto = require("crypto");
-
-// Pollution of global is intentional as part of test.
-// See https://github.com/nodejs/node/commit/d1eff9ab
-global.domain = require("domain");
-
-describe("domain-crypto", () => {
- beforeAll(() => {
- if (!crypto) {
- test.skip("node compiled without OpenSSL.");
- }
- });
-
- test("crypto.randomBytes should not throw", () => {
- expect(() => crypto.randomBytes(8)).not.toThrow();
- });
-
- test("crypto.randomBytes with callback should succeed", () => {
- return new Promise(resolve => {
- crypto.randomBytes(8, (err, buffer) => {
- expect(err).toBeNull();
- expect(buffer).toBeInstanceOf(Buffer);
- expect(buffer.length).toBe(8);
- resolve();
- });
- });
- });
-
- test("crypto.randomFillSync should not throw", () => {
- const buf = Buffer.alloc(8);
- expect(() => crypto.randomFillSync(buf)).not.toThrow();
- });
-
- test("crypto.pseudoRandomBytes should not throw", () => {
- expect(() => crypto.pseudoRandomBytes(8)).not.toThrow();
- });
-
- test("crypto.pseudoRandomBytes with callback should succeed", () => {
- return new Promise(resolve => {
- crypto.pseudoRandomBytes(8, (err, buffer) => {
- expect(err).toBeNull();
- expect(buffer).toBeInstanceOf(Buffer);
- expect(buffer.length).toBe(8);
- resolve();
- });
- });
- });
-
- test("crypto.pbkdf2 should succeed", () => {
- return new Promise(resolve => {
- crypto.pbkdf2("password", "salt", 8, 8, "sha1", (err, derivedKey) => {
- expect(err).toBeNull();
- expect(derivedKey).toBeInstanceOf(Buffer);
- expect(derivedKey.length).toBe(8);
- resolve();
- });
- });
- });
-});
-
-//<#END_FILE: test-domain-crypto.js
diff --git a/test/js/node/test/parallel/domain-dep0097.test.js b/test/js/node/test/parallel/domain-dep0097.test.js
deleted file mode 100644
index 03a74830e1..0000000000
--- a/test/js/node/test/parallel/domain-dep0097.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-domain-dep0097.js
-//#SHA1: d0eeaeed86d045c8deba99d4ca589d35b368f17d
-//-----------------
-"use strict";
-
-// Skip this test if inspector is disabled
-if (typeof inspector === "undefined") {
- test.skip("Inspector is disabled", () => {});
-} else {
- const domain = require("domain");
- const inspector = require("inspector");
-
- test("DEP0097 warning is emitted", () => {
- const warningHandler = jest.fn(warning => {
- expect(warning.code).toBe("DEP0097");
- expect(warning.message).toMatch(/Triggered by calling emit on process/);
- });
-
- process.on("warning", warningHandler);
-
- domain.create().run(() => {
- inspector.open(0);
- });
-
- expect(warningHandler).toHaveBeenCalledTimes(1);
-
- // Clean up
- process.removeListener("warning", warningHandler);
- });
-}
-
-//<#END_FILE: test-domain-dep0097.js
diff --git a/test/js/node/test/parallel/domain-thrown-error-handler-stack.test.js b/test/js/node/test/parallel/domain-thrown-error-handler-stack.test.js
deleted file mode 100644
index f3c8d0b8b7..0000000000
--- a/test/js/node/test/parallel/domain-thrown-error-handler-stack.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-domain-thrown-error-handler-stack.js
-//#SHA1: fd9aef2a4c852c0d092708bb6e712ad345cd4d2d
-//-----------------
-"use strict";
-
-const domain = require("domain");
-
-// Make sure that when an error is thrown from a nested domain, its error
-// handler runs outside of that domain, but within the context of any parent
-// domain.
-
-test("nested domain error handling", () => {
- const d = domain.create();
- const d2 = domain.create();
-
- d2.on("error", err => {
- expect(domain._stack.length).toBe(1);
- expect(process.domain).toBe(d);
-
- process.nextTick(() => {
- expect(domain._stack.length).toBe(1);
- expect(process.domain).toBe(d);
- });
- });
-
- expect(() => {
- d.run(() => {
- d2.run(() => {
- throw new Error("oops");
- });
- });
- }).toThrow(
- expect.objectContaining({
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-domain-thrown-error-handler-stack.js
diff --git a/test/js/node/test/parallel/domain-vm-promise-isolation.test.js b/test/js/node/test/parallel/domain-vm-promise-isolation.test.js
deleted file mode 100644
index fe9ef2198e..0000000000
--- a/test/js/node/test/parallel/domain-vm-promise-isolation.test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-//#FILE: test-domain-vm-promise-isolation.js
-//#SHA1: 866cac427030e1696a6583c234815beed16bf5c8
-//-----------------
-"use strict";
-
-const domain = require("domain");
-const vm = require("vm");
-
-// A promise created in a VM should not include a domain field but
-// domains should still be able to propagate through them.
-//
-// See; https://github.com/nodejs/node/issues/40999
-
-const context = vm.createContext({});
-
-function run(code) {
- const d = domain.createDomain();
- d.run(() => {
- const p = vm.runInContext(code, context)();
- expect(p.domain).toBeUndefined();
- return p.then(() => {
- expect(process.domain).toBe(d);
- });
- });
-}
-
-test("VM promise isolation and domain propagation", async () => {
- const runPromises = [];
- for (let i = 0; i < 1000; i++) {
- runPromises.push(run("async () => null"));
- }
- await Promise.all(runPromises);
-}, 30000); // Increased timeout for multiple iterations
-
-//<#END_FILE: test-domain-vm-promise-isolation.js
diff --git a/test/js/node/test/parallel/double-tls-client.test.js b/test/js/node/test/parallel/double-tls-client.test.js
deleted file mode 100644
index 0913a2a5b7..0000000000
--- a/test/js/node/test/parallel/double-tls-client.test.js
+++ /dev/null
@@ -1,85 +0,0 @@
-//#FILE: test-double-tls-client.js
-//#SHA1: f0d01e282b2d7efc1e1770700f742345216a8bb3
-//-----------------
-"use strict";
-
-const assert = require("assert");
-const fixtures = require("../common/fixtures");
-const tls = require("tls");
-
-// In reality, this can be a HTTP CONNECT message, signaling the incoming
-// data is TLS encrypted
-const HEAD = "XXXX";
-
-let subserver;
-let server;
-
-beforeAll(() => {
- subserver = tls.createServer({
- key: fixtures.readKey("agent1-key.pem"),
- cert: fixtures.readKey("agent1-cert.pem"),
- });
-
- subserver.on("secureConnection", () => {
- process.exit(0);
- });
-
- server = tls.createServer({
- key: fixtures.readKey("agent1-key.pem"),
- cert: fixtures.readKey("agent1-cert.pem"),
- });
-
- server.on("secureConnection", serverTlsSock => {
- serverTlsSock.on("data", chunk => {
- expect(chunk.toString()).toBe(HEAD);
- subserver.emit("connection", serverTlsSock);
- });
- });
-});
-
-afterAll(() => {
- server.close();
- subserver.close();
-});
-
-test("double TLS client", done => {
- const onSecureConnect = jest.fn();
-
- server.listen(() => {
- const down = tls.connect({
- host: "127.0.0.1",
- port: server.address().port,
- rejectUnauthorized: false,
- });
-
- down.on("secureConnect", () => {
- onSecureConnect();
- down.write(HEAD, err => {
- expect(err).toBeFalsy();
-
- // Sending tls data on a client TLSSocket with an active write led to a crash:
- //
- // node[16862]: ../src/crypto/crypto_tls.cc:963:virtual int node::crypto::TLSWrap::DoWrite(node::WriteWrap*,
- // uv_buf_t*, size_t, uv_stream_t*): Assertion `!current_write_' failed.
- // 1: 0xb090e0 node::Abort() [node]
- // 2: 0xb0915e [node]
- // 3: 0xca8413 node::crypto::TLSWrap::DoWrite(node::WriteWrap*, uv_buf_t*, unsigned long, uv_stream_s*) [node]
- // 4: 0xcaa549 node::StreamBase::Write(uv_buf_t*, unsigned long, uv_stream_s*, v8::Local) [node]
- // 5: 0xca88d7 node::crypto::TLSWrap::EncOut() [node]
- // 6: 0xd3df3e [node]
- // 7: 0xd3f35f v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [node]
- // 8: 0x15d9ef9 [node]
- // Aborted
- tls.connect({
- socket: down,
- rejectUnauthorized: false,
- });
-
- expect(onSecureConnect).toHaveBeenCalledTimes(1);
- done();
- });
- });
- });
-});
-
-//<#END_FILE: test-double-tls-client.js
diff --git a/test/js/node/test/parallel/error-format-list.test.js b/test/js/node/test/parallel/error-format-list.test.js
deleted file mode 100644
index ea5fb2dfc9..0000000000
--- a/test/js/node/test/parallel/error-format-list.test.js
+++ /dev/null
@@ -1,31 +0,0 @@
-//#FILE: test-error-format-list.js
-//#SHA1: ed33f55f6c42ff9671add8288b1d2984393bdfc1
-//-----------------
-"use strict";
-
-if (!Intl) {
- test.skip("missing Intl", () => {});
-} else {
- test("formatList function", () => {
- const and = new Intl.ListFormat("en", { style: "long", type: "conjunction" });
- const or = new Intl.ListFormat("en", { style: "long", type: "disjunction" });
-
- const input = ["apple", "banana", "orange", "pear"];
- for (let i = 0; i < input.length; i++) {
- const slicedInput = input.slice(0, i);
- expect(formatList(slicedInput)).toBe(and.format(slicedInput));
- expect(formatList(slicedInput, "or")).toBe(or.format(slicedInput));
- }
- });
-}
-
-// Helper function to replicate the behavior of internal/errors formatList
-function formatList(list, type = "and") {
- const formatter = new Intl.ListFormat("en", {
- style: "long",
- type: type === "and" ? "conjunction" : "disjunction",
- });
- return formatter.format(list);
-}
-
-//<#END_FILE: test-error-format-list.js
diff --git a/test/js/node/test/parallel/errors-systemerror-stacktracelimit-deleted-and-error-sealed.test.js b/test/js/node/test/parallel/errors-systemerror-stacktracelimit-deleted-and-error-sealed.test.js
deleted file mode 100644
index f2b27f0e1f..0000000000
--- a/test/js/node/test/parallel/errors-systemerror-stacktracelimit-deleted-and-error-sealed.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-errors-systemerror-stackTraceLimit-deleted-and-Error-sealed.js
-//#SHA1: 5d9d37ff8651fd7b7ffd5e9ae1b54e4ebc900355
-//-----------------
-"use strict";
-
-test("SystemError with deleted stackTraceLimit and sealed Error", () => {
- delete Error.stackTraceLimit;
- Object.seal(Error);
-
- const ctx = {
- code: "ETEST",
- message: "code message",
- syscall: "syscall_test",
- path: "/str",
- dest: "/str2",
- };
-
- const errorThrowingFunction = () => {
- const error = new Error("custom message");
- error.code = "ERR_TEST";
- error.name = "SystemError";
- error.info = ctx;
- throw error;
- };
-
- expect(errorThrowingFunction).toThrow(
- expect.objectContaining({
- code: "ERR_TEST",
- name: "SystemError",
- info: ctx,
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-errors-systemerror-stackTraceLimit-deleted-and-Error-sealed.js
diff --git a/test/js/node/test/parallel/eval.test.js b/test/js/node/test/parallel/eval.test.js
deleted file mode 100644
index 97bc6069a4..0000000000
--- a/test/js/node/test/parallel/eval.test.js
+++ /dev/null
@@ -1,11 +0,0 @@
-//#FILE: test-eval.js
-//#SHA1: 3ea606b33a3ee4b40ef918317b32008e0f5d5e49
-//-----------------
-"use strict";
-
-// Verify that eval is allowed by default.
-test("eval is allowed by default", () => {
- expect(eval('"eval"')).toBe("eval");
-});
-
-//<#END_FILE: test-eval.js
diff --git a/test/js/node/test/parallel/event-emitter-add-listeners.test.js b/test/js/node/test/parallel/event-emitter-add-listeners.test.js
deleted file mode 100644
index fec7a8fdd2..0000000000
--- a/test/js/node/test/parallel/event-emitter-add-listeners.test.js
+++ /dev/null
@@ -1,91 +0,0 @@
-//#FILE: test-event-emitter-add-listeners.js
-//#SHA1: 25d8611a8cf3694d26e53bb90f760beeb3bb1946
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const EventEmitter = require("events");
-
-test("EventEmitter addListener functionality", () => {
- const ee = new EventEmitter();
- const events_new_listener_emitted = [];
- const listeners_new_listener_emitted = [];
-
- // Sanity check
- expect(ee.addListener).toBe(ee.on);
-
- ee.on("newListener", function (event, listener) {
- // Don't track newListener listeners.
- if (event === "newListener") return;
-
- events_new_listener_emitted.push(event);
- listeners_new_listener_emitted.push(listener);
- });
-
- const hello = jest.fn((a, b) => {
- expect(a).toBe("a");
- expect(b).toBe("b");
- });
-
- ee.once("newListener", function (name, listener) {
- expect(name).toBe("hello");
- expect(listener).toBe(hello);
- expect(this.listeners("hello")).toEqual([]);
- });
-
- ee.on("hello", hello);
- ee.once("foo", () => {
- throw new Error("This should not be called");
- });
- expect(events_new_listener_emitted).toEqual(["hello", "foo"]);
- expect(listeners_new_listener_emitted).toEqual([hello, expect.any(Function)]);
-
- ee.emit("hello", "a", "b");
- expect(hello).toHaveBeenCalledTimes(1);
-});
-
-test("setMaxListeners with 0 does not throw", () => {
- const f = new EventEmitter();
- expect(() => {
- f.setMaxListeners(0);
- }).not.toThrow();
-});
-
-test("newListener event and listener order", () => {
- const listen1 = () => {};
- const listen2 = () => {};
- const ee = new EventEmitter();
-
- ee.once("newListener", function () {
- expect(ee.listeners("hello")).toEqual([]);
- ee.once("newListener", function () {
- expect(ee.listeners("hello")).toEqual([]);
- });
- ee.on("hello", listen2);
- });
- ee.on("hello", listen1);
- // The order of listeners on an event is not always the order in which the
- // listeners were added.
- expect(ee.listeners("hello")).toEqual([listen2, listen1]);
-});
-
-//<#END_FILE: test-event-emitter-add-listeners.js
diff --git a/test/js/node/test/parallel/event-emitter-check-listener-leaks.test.js b/test/js/node/test/parallel/event-emitter-check-listener-leaks.test.js
deleted file mode 100644
index 49c67758b6..0000000000
--- a/test/js/node/test/parallel/event-emitter-check-listener-leaks.test.js
+++ /dev/null
@@ -1,103 +0,0 @@
-//#FILE: test-event-emitter-check-listener-leaks.js
-//#SHA1: c9d313a0879cc331d8ad1afafe5b9f482597bc7c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const events = require("events");
-
-test("default", () => {
- const e = new events.EventEmitter();
-
- for (let i = 0; i < 10; i++) {
- e.on("default", jest.fn());
- }
- expect(Object.hasOwn(e._events.default, "warned")).toBe(false);
- e.on("default", jest.fn());
- expect(e._events.default.warned).toBe(true);
-
- // symbol
- const symbol = Symbol("symbol");
- e.setMaxListeners(1);
- e.on(symbol, jest.fn());
- expect(Object.hasOwn(e._events[symbol], "warned")).toBe(false);
- e.on(symbol, jest.fn());
- expect(Object.hasOwn(e._events[symbol], "warned")).toBe(true);
-
- // specific
- e.setMaxListeners(5);
- for (let i = 0; i < 5; i++) {
- e.on("specific", jest.fn());
- }
- expect(Object.hasOwn(e._events.specific, "warned")).toBe(false);
- e.on("specific", jest.fn());
- expect(e._events.specific.warned).toBe(true);
-
- // only one
- e.setMaxListeners(1);
- e.on("only one", jest.fn());
- expect(Object.hasOwn(e._events["only one"], "warned")).toBe(false);
- e.on("only one", jest.fn());
- expect(Object.hasOwn(e._events["only one"], "warned")).toBe(true);
-
- // unlimited
- e.setMaxListeners(0);
- for (let i = 0; i < 1000; i++) {
- e.on("unlimited", jest.fn());
- }
- expect(Object.hasOwn(e._events.unlimited, "warned")).toBe(false);
-});
-
-test("process-wide", () => {
- events.EventEmitter.defaultMaxListeners = 42;
- const e = new events.EventEmitter();
-
- for (let i = 0; i < 42; ++i) {
- e.on("fortytwo", jest.fn());
- }
- expect(Object.hasOwn(e._events.fortytwo, "warned")).toBe(false);
- e.on("fortytwo", jest.fn());
- expect(Object.hasOwn(e._events.fortytwo, "warned")).toBe(true);
- delete e._events.fortytwo.warned;
-
- events.EventEmitter.defaultMaxListeners = 44;
- e.on("fortytwo", jest.fn());
- expect(Object.hasOwn(e._events.fortytwo, "warned")).toBe(false);
- e.on("fortytwo", jest.fn());
- expect(Object.hasOwn(e._events.fortytwo, "warned")).toBe(true);
-});
-
-test("_maxListeners precedence over defaultMaxListeners", () => {
- events.EventEmitter.defaultMaxListeners = 42;
- const e = new events.EventEmitter();
- e.setMaxListeners(1);
- e.on("uno", jest.fn());
- expect(Object.hasOwn(e._events.uno, "warned")).toBe(false);
- e.on("uno", jest.fn());
- expect(Object.hasOwn(e._events.uno, "warned")).toBe(true);
-
- // chainable
- expect(e.setMaxListeners(1)).toBe(e);
-});
-
-//<#END_FILE: test-event-emitter-check-listener-leaks.js
diff --git a/test/js/node/test/parallel/event-emitter-emit-context.test.js b/test/js/node/test/parallel/event-emitter-emit-context.test.js
deleted file mode 100644
index b39c26258e..0000000000
--- a/test/js/node/test/parallel/event-emitter-emit-context.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//#FILE: test-event-emitter-emit-context.js
-//#SHA1: 66f963c1a1351deff53d036d86f821c5e932c832
-//-----------------
-"use strict";
-const EventEmitter = require("events");
-
-// Test emit called by other context
-const EE = new EventEmitter();
-
-// Works as expected if the context has no `constructor.name`
-test("emit called with context having no constructor.name", () => {
- const ctx = { __proto__: null };
- expect(() => EE.emit.call(ctx, "error", new Error("foo"))).toThrow(
- expect.objectContaining({
- name: "Error",
- message: expect.any(String),
- }),
- );
-});
-
-test("emit called with empty object context", () => {
- expect(EE.emit.call({}, "foo")).toBe(false);
-});
-
-//<#END_FILE: test-event-emitter-emit-context.js
diff --git a/test/js/node/test/parallel/event-emitter-get-max-listeners.test.js b/test/js/node/test/parallel/event-emitter-get-max-listeners.test.js
deleted file mode 100644
index 612a3f1323..0000000000
--- a/test/js/node/test/parallel/event-emitter-get-max-listeners.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-event-emitter-get-max-listeners.js
-//#SHA1: ff5c2f7b9525ae4137ea8eddd742572bd399c5ce
-//-----------------
-"use strict";
-
-const EventEmitter = require("events");
-
-test("EventEmitter getMaxListeners", () => {
- const emitter = new EventEmitter();
-
- expect(emitter.getMaxListeners()).toBe(EventEmitter.defaultMaxListeners);
-
- emitter.setMaxListeners(0);
- expect(emitter.getMaxListeners()).toBe(0);
-
- emitter.setMaxListeners(3);
- expect(emitter.getMaxListeners()).toBe(3);
-});
-
-// https://github.com/nodejs/node/issues/523 - second call should not throw.
-test("EventEmitter.prototype.on should not throw on second call", () => {
- const recv = {};
- expect(() => {
- EventEmitter.prototype.on.call(recv, "event", () => {});
- EventEmitter.prototype.on.call(recv, "event", () => {});
- }).not.toThrow();
-});
-
-//<#END_FILE: test-event-emitter-get-max-listeners.js
diff --git a/test/js/node/test/parallel/event-emitter-listener-count.test.js b/test/js/node/test/parallel/event-emitter-listener-count.test.js
deleted file mode 100644
index b9772949ad..0000000000
--- a/test/js/node/test/parallel/event-emitter-listener-count.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-event-emitter-listener-count.js
-//#SHA1: 0f4b7f14fe432472b51524b3853db6d8615614f1
-//-----------------
-"use strict";
-
-const EventEmitter = require("events");
-
-describe("EventEmitter.listenerCount and emitter.listenerCount", () => {
- let emitter;
-
- beforeEach(() => {
- emitter = new EventEmitter();
- emitter.on("foo", () => {});
- emitter.on("foo", () => {});
- emitter.on("baz", () => {});
- // Allow any type
- emitter.on(123, () => {});
- });
-
- test("EventEmitter.listenerCount returns correct count", () => {
- expect(EventEmitter.listenerCount(emitter, "foo")).toBe(2);
- });
-
- test("emitter.listenerCount returns correct counts for various events", () => {
- expect(emitter.listenerCount("foo")).toBe(2);
- expect(emitter.listenerCount("bar")).toBe(0);
- expect(emitter.listenerCount("baz")).toBe(1);
- expect(emitter.listenerCount(123)).toBe(1);
- });
-});
-
-//<#END_FILE: test-event-emitter-listener-count.js
diff --git a/test/js/node/test/parallel/event-emitter-modify-in-emit.test.js b/test/js/node/test/parallel/event-emitter-modify-in-emit.test.js
deleted file mode 100644
index 422054923c..0000000000
--- a/test/js/node/test/parallel/event-emitter-modify-in-emit.test.js
+++ /dev/null
@@ -1,89 +0,0 @@
-//#FILE: test-event-emitter-modify-in-emit.js
-//#SHA1: 6d378f9c7700ce7946f7d59bbc32b7cb82efc836
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const events = require("events");
-
-describe("EventEmitter modify in emit", () => {
- let callbacks_called;
- let e;
-
- function callback1() {
- callbacks_called.push("callback1");
- e.on("foo", callback2);
- e.on("foo", callback3);
- e.removeListener("foo", callback1);
- }
-
- function callback2() {
- callbacks_called.push("callback2");
- e.removeListener("foo", callback2);
- }
-
- function callback3() {
- callbacks_called.push("callback3");
- e.removeListener("foo", callback3);
- }
-
- beforeEach(() => {
- callbacks_called = [];
- e = new events.EventEmitter();
- });
-
- test("listeners are modified during emit", () => {
- e.on("foo", callback1);
- expect(e.listeners("foo").length).toBe(1);
-
- e.emit("foo");
- expect(e.listeners("foo").length).toBe(2);
- expect(callbacks_called).toEqual(["callback1"]);
-
- e.emit("foo");
- expect(e.listeners("foo").length).toBe(0);
- expect(callbacks_called).toEqual(["callback1", "callback2", "callback3"]);
-
- e.emit("foo");
- expect(e.listeners("foo").length).toBe(0);
- expect(callbacks_called).toEqual(["callback1", "callback2", "callback3"]);
- });
-
- test("removeAllListeners removes all listeners", () => {
- e.on("foo", callback1);
- e.on("foo", callback2);
- expect(e.listeners("foo").length).toBe(2);
- e.removeAllListeners("foo");
- expect(e.listeners("foo").length).toBe(0);
- });
-
- test("removing callbacks during emit allows emits to propagate to all listeners", () => {
- e.on("foo", callback2);
- e.on("foo", callback3);
- expect(e.listeners("foo").length).toBe(2);
- e.emit("foo");
- expect(callbacks_called).toEqual(["callback2", "callback3"]);
- expect(e.listeners("foo").length).toBe(0);
- });
-});
-
-//<#END_FILE: test-event-emitter-modify-in-emit.js
diff --git a/test/js/node/test/parallel/event-emitter-num-args.test.js b/test/js/node/test/parallel/event-emitter-num-args.test.js
deleted file mode 100644
index e295eb022c..0000000000
--- a/test/js/node/test/parallel/event-emitter-num-args.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-event-emitter-num-args.js
-//#SHA1: b17b5bfd071180f4c53c8c408dc14ec860fd4225
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const events = require("events");
-
-describe("EventEmitter number of arguments", () => {
- let e;
- let num_args_emitted;
-
- beforeEach(() => {
- e = new events.EventEmitter();
- num_args_emitted = [];
-
- e.on("numArgs", function () {
- const numArgs = arguments.length;
- num_args_emitted.push(numArgs);
- });
-
- e.on("foo", function () {
- num_args_emitted.push(arguments.length);
- });
-
- e.on("foo", function () {
- num_args_emitted.push(arguments.length);
- });
- });
-
- it("should emit correct number of arguments", () => {
- e.emit("numArgs");
- e.emit("numArgs", null);
- e.emit("numArgs", null, null);
- e.emit("numArgs", null, null, null);
- e.emit("numArgs", null, null, null, null);
- e.emit("numArgs", null, null, null, null, null);
-
- e.emit("foo", null, null, null, null);
-
- expect(num_args_emitted).toEqual([0, 1, 2, 3, 4, 5, 4, 4]);
- });
-});
-
-//<#END_FILE: test-event-emitter-num-args.js
diff --git a/test/js/node/test/parallel/event-emitter-prepend.test.js b/test/js/node/test/parallel/event-emitter-prepend.test.js
deleted file mode 100644
index f8f7d47b8c..0000000000
--- a/test/js/node/test/parallel/event-emitter-prepend.test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-//#FILE: test-event-emitter-prepend.js
-//#SHA1: 9a753f44fc304ff6584a31c20e95037e622579d7
-//-----------------
-"use strict";
-
-const EventEmitter = require("events");
-const stream = require("stream");
-
-describe("EventEmitter prepend", () => {
- test("prepend listeners in correct order", () => {
- const myEE = new EventEmitter();
- let m = 0;
-
- // This one comes last.
- myEE.on("foo", () => {
- expect(m).toBe(2);
- });
-
- // This one comes second.
- myEE.prependListener("foo", () => {
- expect(m).toBe(1);
- m++;
- });
-
- // This one comes first.
- myEE.prependOnceListener("foo", () => {
- expect(m).toBe(0);
- m++;
- });
-
- myEE.emit("foo");
- expect.assertions(3);
- });
-
- test("fallback if prependListener is undefined", () => {
- // Test fallback if prependListener is undefined.
- delete EventEmitter.prototype.prependListener;
-
- function Writable() {
- this.writable = true;
- stream.Stream.call(this);
- }
- Object.setPrototypeOf(Writable.prototype, stream.Stream.prototype);
- Object.setPrototypeOf(Writable, stream.Stream);
-
- function Readable() {
- this.readable = true;
- stream.Stream.call(this);
- }
- Object.setPrototypeOf(Readable.prototype, stream.Stream.prototype);
- Object.setPrototypeOf(Readable, stream.Stream);
-
- const w = new Writable();
- const r = new Readable();
- r.pipe(w);
-
- // If we reach this point without throwing, the test passes
- expect(true).toBe(true);
- });
-});
-
-//<#END_FILE: test-event-emitter-prepend.js
diff --git a/test/js/node/test/parallel/event-emitter-set-max-listeners-side-effects.test.js b/test/js/node/test/parallel/event-emitter-set-max-listeners-side-effects.test.js
deleted file mode 100644
index 101ccfa80b..0000000000
--- a/test/js/node/test/parallel/event-emitter-set-max-listeners-side-effects.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-event-emitter-set-max-listeners-side-effects.js
-//#SHA1: 319371e261c5cc46348475cdd789eb9ee56839d8
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const events = require("events");
-
-test("EventEmitter setMaxListeners should not have side effects", () => {
- const e = new events.EventEmitter();
-
- expect(e._events).not.toBeInstanceOf(Object);
- expect(Object.keys(e._events)).toEqual([]);
- e.setMaxListeners(5);
- expect(Object.keys(e._events)).toEqual([]);
-});
-
-//<#END_FILE: test-event-emitter-set-max-listeners-side-effects.js
diff --git a/test/js/node/test/parallel/event-emitter-special-event-names.test.js b/test/js/node/test/parallel/event-emitter-special-event-names.test.js
deleted file mode 100644
index 60d8071a33..0000000000
--- a/test/js/node/test/parallel/event-emitter-special-event-names.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-//#FILE: test-event-emitter-special-event-names.js
-//#SHA1: 3ae93e3a9f5cd01560264a5c297a2fae25c5c18f
-//-----------------
-"use strict";
-
-const EventEmitter = require("events");
-
-describe("EventEmitter with special event names", () => {
- let ee;
-
- beforeEach(() => {
- ee = new EventEmitter();
- });
-
- test("initial eventNames() is empty", () => {
- expect(ee.eventNames()).toEqual([]);
- });
-
- test("_events does not have hasOwnProperty or toString", () => {
- expect(ee._events.hasOwnProperty).toBeUndefined();
- expect(ee._events.toString).toBeUndefined();
- });
-
- test("can add and list special event names", () => {
- const handler = jest.fn();
-
- ee.on("__proto__", handler);
- ee.on("__defineGetter__", handler);
- ee.on("toString", handler);
-
- expect(ee.eventNames()).toEqual(["__proto__", "__defineGetter__", "toString"]);
-
- expect(ee.listeners("__proto__")).toEqual([handler]);
- expect(ee.listeners("__defineGetter__")).toEqual([handler]);
- expect(ee.listeners("toString")).toEqual([handler]);
- });
-
- test("can emit __proto__ event", () => {
- const handler = jest.fn();
- ee.on("__proto__", handler);
- ee.emit("__proto__", 1);
- expect(handler).toHaveBeenCalledWith(1);
- });
-
- test("process can emit __proto__ event", () => {
- const handler = jest.fn();
- process.on("__proto__", handler);
- process.emit("__proto__", 1);
- expect(handler).toHaveBeenCalledWith(1);
- });
-});
-
-//<#END_FILE: test-event-emitter-special-event-names.js
diff --git a/test/js/node/test/parallel/event-emitter-subclass.test.js b/test/js/node/test/parallel/event-emitter-subclass.test.js
deleted file mode 100644
index a48d9e8fdd..0000000000
--- a/test/js/node/test/parallel/event-emitter-subclass.test.js
+++ /dev/null
@@ -1,81 +0,0 @@
-//#FILE: test-event-emitter-subclass.js
-//#SHA1: e7f7e379fcf89318168b9e5d9f38c4af371ada8e
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const EventEmitter = require("events").EventEmitter;
-
-Object.setPrototypeOf(MyEE.prototype, EventEmitter.prototype);
-Object.setPrototypeOf(MyEE, EventEmitter);
-
-function MyEE(cb) {
- this.once(1, cb);
- this.emit(1);
- this.removeAllListeners();
- EventEmitter.call(this);
-}
-
-test("MyEE callback is called", () => {
- const callback = jest.fn();
- const myee = new MyEE(callback);
- expect(callback).toHaveBeenCalledTimes(1);
-});
-
-Object.setPrototypeOf(ErrorEE.prototype, EventEmitter.prototype);
-Object.setPrototypeOf(ErrorEE, EventEmitter);
-function ErrorEE() {
- this.emit("error", new Error("blerg"));
-}
-
-test("ErrorEE throws error", () => {
- expect(() => {
- new ErrorEE();
- }).toThrow(
- expect.objectContaining({
- message: expect.any(String),
- }),
- );
-});
-
-test("MyEE _events is empty after removeAllListeners", () => {
- const myee = new MyEE(() => {});
- expect(myee._events).not.toBeInstanceOf(Object);
- expect(Object.keys(myee._events)).toEqual([]);
-});
-
-function MyEE2() {
- EventEmitter.call(this);
-}
-
-MyEE2.prototype = new EventEmitter();
-
-test("MyEE2 instances do not share listeners", () => {
- const ee1 = new MyEE2();
- const ee2 = new MyEE2();
-
- ee1.on("x", () => {});
-
- expect(ee2.listenerCount("x")).toBe(0);
-});
-
-//<#END_FILE: test-event-emitter-subclass.js
diff --git a/test/js/node/test/parallel/event-emitter-symbols.test.js b/test/js/node/test/parallel/event-emitter-symbols.test.js
deleted file mode 100644
index bfb0e2b774..0000000000
--- a/test/js/node/test/parallel/event-emitter-symbols.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-event-emitter-symbols.js
-//#SHA1: c3fa4a8db31f2a88317d3c60fb52aa2921eaa20d
-//-----------------
-"use strict";
-
-const EventEmitter = require("events");
-
-test("EventEmitter with Symbol events", () => {
- const ee = new EventEmitter();
- const foo = Symbol("foo");
- const listener = jest.fn();
-
- ee.on(foo, listener);
- expect(ee.listeners(foo)).toEqual([listener]);
-
- ee.emit(foo);
- expect(listener).toHaveBeenCalledTimes(1);
-
- ee.removeAllListeners();
- expect(ee.listeners(foo)).toEqual([]);
-
- ee.on(foo, listener);
- expect(ee.listeners(foo)).toEqual([listener]);
-
- ee.removeListener(foo, listener);
- expect(ee.listeners(foo)).toEqual([]);
-});
-
-//<#END_FILE: test-event-emitter-symbols.js
diff --git a/test/js/node/test/parallel/event-target.test.js b/test/js/node/test/parallel/event-target.test.js
deleted file mode 100644
index 0b5fc40712..0000000000
--- a/test/js/node/test/parallel/event-target.test.js
+++ /dev/null
@@ -1,25 +0,0 @@
-//#FILE: test-event-target.js
-//#SHA1: 3e70912640aa5270e13723e1895636bfd238420a
-//-----------------
-"use strict";
-
-const eventPhases = {
- NONE: 0,
- CAPTURING_PHASE: 1,
- AT_TARGET: 2,
- BUBBLING_PHASE: 3,
-};
-
-describe("Event phases", () => {
- test.each(Object.entries(eventPhases))("Event.%s should be %d", (prop, value) => {
- // Check if the value of the property matches the expected value
- expect(Event[prop]).toBe(value);
-
- const desc = Object.getOwnPropertyDescriptor(Event, prop);
- expect(desc.writable).toBe(false);
- expect(desc.configurable).toBe(false);
- expect(desc.enumerable).toBe(true);
- });
-});
-
-//<#END_FILE: test-event-target.js
diff --git a/test/js/node/test/parallel/events-list.test.js b/test/js/node/test/parallel/events-list.test.js
deleted file mode 100644
index bde2b1a0e6..0000000000
--- a/test/js/node/test/parallel/events-list.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-events-list.js
-//#SHA1: 946973d6c9e19c6410b4486cbef3e2ed032715fc
-//-----------------
-"use strict";
-
-const EventEmitter = require("events");
-
-test("EventEmitter.eventNames()", () => {
- const EE = new EventEmitter();
- const m = () => {};
-
- EE.on("foo", () => {});
- expect(EE.eventNames()).toEqual(["foo"]);
-
- EE.on("bar", m);
- expect(EE.eventNames()).toEqual(["foo", "bar"]);
-
- EE.removeListener("bar", m);
- expect(EE.eventNames()).toEqual(["foo"]);
-
- const s = Symbol("s");
- EE.on(s, m);
- expect(EE.eventNames()).toEqual(["foo", s]);
-
- EE.removeListener(s, m);
- expect(EE.eventNames()).toEqual(["foo"]);
-});
-
-//<#END_FILE: test-events-list.js
diff --git a/test/js/node/test/parallel/events-on-async-iterator.test.js b/test/js/node/test/parallel/events-on-async-iterator.test.js
deleted file mode 100644
index eb67f58c5b..0000000000
--- a/test/js/node/test/parallel/events-on-async-iterator.test.js
+++ /dev/null
@@ -1,417 +0,0 @@
-import { test, expect } from "bun:test";
-const common = require("../common");
-const assert = require("assert");
-const { on, EventEmitter, listenerCount } = require("events");
-
-test("basic", async () => {
- const ee = new EventEmitter();
- process.nextTick(() => {
- ee.emit("foo", "bar");
- // 'bar' is a spurious event, we are testing
- // that it does not show up in the iterable
- ee.emit("bar", 24);
- ee.emit("foo", 42);
- });
-
- const iterable = on(ee, "foo");
-
- const expected = [["bar"], [42]];
-
- for await (const event of iterable) {
- const current = expected.shift();
-
- expect(current).toStrictEqual(event);
-
- if (expected.length === 0) {
- break;
- }
- }
- expect(ee.listenerCount("foo")).toBe(0);
- expect(ee.listenerCount("error")).toBe(0);
-});
-
-test("invalidArgType", async () => {
- assert.throws(
- () => on({}, "foo"),
- common.expectsError({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- const ee = new EventEmitter();
-
- [1, "hi", null, false, () => {}, Symbol(), 1n].map(options => {
- return assert.throws(
- () => on(ee, "foo", options),
- common.expectsError({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
- });
-});
-
-test("error", async () => {
- const ee = new EventEmitter();
- const _err = new Error("kaboom");
- process.nextTick(() => {
- ee.emit("error", _err);
- });
-
- const iterable = on(ee, "foo");
- let looped = false;
- let thrown = false;
-
- try {
- // eslint-disable-next-line no-unused-vars
- for await (const event of iterable) {
- looped = true;
- }
- } catch (err) {
- thrown = true;
- expect(err).toStrictEqual(_err);
- }
- expect(thrown).toBe(true);
- expect(looped).toBe(false);
-});
-
-test("errorDelayed", async () => {
- const ee = new EventEmitter();
- const _err = new Error("kaboom");
- process.nextTick(() => {
- ee.emit("foo", 42);
- ee.emit("error", _err);
- });
-
- const iterable = on(ee, "foo");
- const expected = [[42]];
- let thrown = false;
-
- try {
- for await (const event of iterable) {
- const current = expected.shift();
- assert.deepStrictEqual(current, event);
- }
- } catch (err) {
- thrown = true;
- expect(err).toStrictEqual(_err);
- }
- expect(thrown).toBe(true);
- expect(ee.listenerCount("foo")).toBe(0);
- expect(ee.listenerCount("error")).toBe(0);
-});
-
-test("throwInLoop", async () => {
- const ee = new EventEmitter();
- const _err = new Error("kaboom");
-
- process.nextTick(() => {
- ee.emit("foo", 42);
- });
-
- try {
- for await (const event of on(ee, "foo")) {
- assert.deepStrictEqual(event, [42]);
- throw _err;
- }
- } catch (err) {
- expect(err).toStrictEqual(_err);
- }
-
- expect(ee.listenerCount("foo")).toBe(0);
- expect(ee.listenerCount("error")).toBe(0);
-});
-
-test("next", async () => {
- const ee = new EventEmitter();
- const iterable = on(ee, "foo");
-
- process.nextTick(function () {
- ee.emit("foo", "bar");
- ee.emit("foo", 42);
- iterable.return();
- });
-
- const results = await Promise.all([iterable.next(), iterable.next(), iterable.next()]);
-
- expect(results).toStrictEqual([
- {
- value: ["bar"],
- done: false,
- },
- {
- value: [42],
- done: false,
- },
- {
- value: undefined,
- done: true,
- },
- ]);
-
- expect(await iterable.next()).toStrictEqual({
- value: undefined,
- done: true,
- });
-});
-
-test("nextError", async () => {
- const ee = new EventEmitter();
- const iterable = on(ee, "foo");
- const _err = new Error("kaboom");
- process.nextTick(function () {
- ee.emit("error", _err);
- });
- const results = await Promise.allSettled([iterable.next(), iterable.next(), iterable.next()]);
- assert.deepStrictEqual(results, [
- {
- status: "rejected",
- reason: _err,
- },
- {
- status: "fulfilled",
- value: {
- value: undefined,
- done: true,
- },
- },
- {
- status: "fulfilled",
- value: {
- value: undefined,
- done: true,
- },
- },
- ]);
- expect(ee.listeners("error").length).toBe(0);
-});
-
-test("iterableThrow", async () => {
- const ee = new EventEmitter();
- const iterable = on(ee, "foo");
-
- process.nextTick(() => {
- ee.emit("foo", "bar");
- ee.emit("foo", 42); // lost in the queue
- iterable.throw(_err);
- });
-
- const _err = new Error("kaboom");
- let thrown = false;
-
- assert.throws(
- () => {
- // No argument
- iterable.throw();
- },
- {
- message: 'The "EventEmitter.AsyncIterator" argument must be' + " of type Error. Received: undefined",
- name: "TypeError",
- },
- );
-
- const expected = [["bar"], [42]];
-
- try {
- for await (const event of iterable) {
- assert.deepStrictEqual(event, expected.shift());
- }
- } catch (err) {
- thrown = true;
- assert.strictEqual(err, _err);
- }
- assert.strictEqual(thrown, true);
- assert.strictEqual(expected.length, 0);
- assert.strictEqual(ee.listenerCount("foo"), 0);
- assert.strictEqual(ee.listenerCount("error"), 0);
-});
-
-test("eventTarget", async () => {
- const et = new EventTarget();
- const tick = () => et.dispatchEvent(new Event("tick"));
- const interval = setInterval(tick, 0);
- let count = 0;
- for await (const [event] of on(et, "tick")) {
- count++;
- assert.strictEqual(event.type, "tick");
- if (count >= 5) {
- break;
- }
- }
- assert.strictEqual(count, 5);
- clearInterval(interval);
-});
-
-test("errorListenerCount", async () => {
- const et = new EventEmitter();
- on(et, "foo");
- assert.strictEqual(et.listenerCount("error"), 1);
-});
-
-test.skip("nodeEventTarget", async () => {
- const et = new NodeEventTarget();
- const tick = () => et.dispatchEvent(new Event("tick"));
- const interval = setInterval(tick, 0);
- let count = 0;
- for await (const [event] of on(et, "tick")) {
- count++;
- assert.strictEqual(event.type, "tick");
- if (count >= 5) {
- break;
- }
- }
- assert.strictEqual(count, 5);
- clearInterval(interval);
-});
-
-test("abortableOnBefore", async () => {
- const ee = new EventEmitter();
- const abortedSignal = AbortSignal.abort();
- [1, {}, null, false, "hi"].forEach(signal => {
- assert.throws(() => on(ee, "foo", { signal }), {
- code: "ERR_INVALID_ARG_TYPE",
- });
- });
- assert.throws(() => on(ee, "foo", { signal: abortedSignal }), {
- name: "AbortError",
- });
-});
-
-test("eventTargetAbortableOnBefore", async () => {
- const et = new EventTarget();
- const abortedSignal = AbortSignal.abort();
- [1, {}, null, false, "hi"].forEach(signal => {
- assert.throws(() => on(et, "foo", { signal }), {
- code: "ERR_INVALID_ARG_TYPE",
- });
- });
- assert.throws(() => on(et, "foo", { signal: abortedSignal }), {
- name: "AbortError",
- });
-});
-
-test("abortableOnAfter", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
-
- const i = setInterval(() => ee.emit("foo", "foo"), 10);
-
- async function foo() {
- for await (const f of on(ee, "foo", { signal: ac.signal })) {
- assert.strictEqual(f, "foo");
- }
- }
-
- foo()
- .catch(
- common.mustCall(error => {
- assert.strictEqual(error.name, "AbortError");
- }),
- )
- .finally(() => {
- clearInterval(i);
- });
-
- process.nextTick(() => ac.abort());
-});
-
-test("eventTargetAbortableOnAfter", async () => {
- const et = new EventTarget();
- const ac = new AbortController();
-
- const i = setInterval(() => et.dispatchEvent(new Event("foo")), 10);
-
- async function foo() {
- for await (const f of on(et, "foo", { signal: ac.signal })) {
- assert(f);
- }
- }
-
- foo()
- .catch(
- common.mustCall(error => {
- assert.strictEqual(error.name, "AbortError");
- }),
- )
- .finally(() => {
- clearInterval(i);
- });
-
- process.nextTick(() => ac.abort());
-});
-
-test("eventTargetAbortableOnAfter2", async () => {
- const et = new EventTarget();
- const ac = new AbortController();
-
- const i = setInterval(() => et.dispatchEvent(new Event("foo")), 10);
-
- async function foo() {
- for await (const f of on(et, "foo", { signal: ac.signal })) {
- assert(f);
- // Cancel after a single event has been triggered.
- ac.abort();
- }
- }
-
- foo()
- .catch(
- common.mustCall(error => {
- assert.strictEqual(error.name, "AbortError");
- }),
- )
- .finally(() => {
- clearInterval(i);
- });
-});
-
-test("abortableOnAfterDone", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
-
- const i = setInterval(() => ee.emit("foo", "foo"), 1);
- let count = 0;
-
- async function foo() {
- for await (const f of on(ee, "foo", { signal: ac.signal })) {
- assert.strictEqual(f[0], "foo");
- if (++count === 5) break;
- }
- ac.abort(); // No error will occur
- }
-
- foo().finally(() => {
- clearInterval(i);
- });
-});
-
-test("abortListenerRemovedAfterComplete", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
-
- const i = setInterval(() => ee.emit("foo", "foo"), 1);
- try {
- // Below: either the kEvents map is empty or the 'abort' listener list is empty
-
- // Return case
- const endedIterator = on(ee, "foo", { signal: ac.signal });
- expect(listenerCount(ac.signal, "abort")).toBeGreaterThan(0);
- endedIterator.return();
- expect(listenerCount(ac.signal, "abort")).toBe(0);
-
- // Throw case
- const throwIterator = on(ee, "foo", { signal: ac.signal });
- expect(listenerCount(ac.signal, "abort")).toBeGreaterThan(0);
- throwIterator.throw(new Error());
- expect(listenerCount(ac.signal, "abort")).toBe(0);
-
- // Abort case
- on(ee, "foo", { signal: ac.signal });
- expect(listenerCount(ac.signal, "abort")).toBeGreaterThan(0);
- ac.abort(new Error());
- expect(listenerCount(ac.signal, "abort")).toBe(0);
- } finally {
- clearInterval(i);
- }
-});
diff --git a/test/js/node/test/parallel/events-once.test.js b/test/js/node/test/parallel/events-once.test.js
deleted file mode 100644
index 3e0c4c9ecb..0000000000
--- a/test/js/node/test/parallel/events-once.test.js
+++ /dev/null
@@ -1,254 +0,0 @@
-import { test, expect } from "bun:test";
-const { once, EventEmitter, listenerCount } = require("events");
-const { deepStrictEqual, fail, rejects, strictEqual } = require("assert");
-// const { kEvents } = require("internal/event_target");
-
-test("onceAnEvent", async () => {
- const ee = new EventEmitter();
-
- process.nextTick(() => {
- ee.emit("myevent", 42);
- });
-
- const [value] = await once(ee, "myevent");
- strictEqual(value, 42);
- strictEqual(ee.listenerCount("error"), 0);
- strictEqual(ee.listenerCount("myevent"), 0);
-});
-
-test("onceAnEventWithInvalidOptions", async () => {
- const ee = new EventEmitter();
-
- await Promise.all(
- [1, "hi", null, false, () => {}, Symbol(), 1n].map(options => {
- expect.toThrowWithCode(() => once(ee, "myevent", options), "ERR_INVALID_ARG_TYPE");
- }),
- );
-});
-
-test("onceAnEventWithTwoArgs", async () => {
- const ee = new EventEmitter();
-
- process.nextTick(() => {
- ee.emit("myevent", 42, 24);
- });
-
- const value = await once(ee, "myevent");
- deepStrictEqual(value, [42, 24]);
-});
-
-test("catchesErrors", async () => {
- const ee = new EventEmitter();
-
- const expected = new Error("kaboom");
- let err;
- process.nextTick(() => {
- ee.emit("error", expected);
- });
-
- try {
- await once(ee, "myevent");
- } catch (_e) {
- err = _e;
- }
- strictEqual(err, expected);
- strictEqual(ee.listenerCount("error"), 0);
- strictEqual(ee.listenerCount("myevent"), 0);
-});
-
-test("catchesErrorsWithAbortSignal", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
- const signal = ac.signal;
-
- const expected = new Error("boom");
- let err;
- process.nextTick(() => {
- ee.emit("error", expected);
- });
-
- try {
- const promise = once(ee, "myevent", { signal });
- strictEqual(ee.listenerCount("error"), 1);
- strictEqual(listenerCount(signal, "abort"), 1);
-
- await promise;
- } catch (e) {
- err = e;
- }
- strictEqual(err, expected);
- strictEqual(ee.listenerCount("error"), 0);
- strictEqual(ee.listenerCount("myevent"), 0);
- strictEqual(listenerCount(signal, "abort"), 0);
-});
-
-test("stopListeningAfterCatchingError", async () => {
- const ee = new EventEmitter();
-
- const expected = new Error("kaboom");
- let err;
- process.nextTick(() => {
- ee.emit("error", expected);
- ee.emit("myevent", 42, 24);
- });
-
- try {
- await once(ee, "myevent");
- } catch (_e) {
- err = _e;
- }
- process.removeAllListeners("multipleResolves");
- strictEqual(err, expected);
- strictEqual(ee.listenerCount("error"), 0);
- strictEqual(ee.listenerCount("myevent"), 0);
-});
-
-test("onceError", async () => {
- const ee = new EventEmitter();
-
- const expected = new Error("kaboom");
- process.nextTick(() => {
- ee.emit("error", expected);
- });
-
- const promise = once(ee, "error");
- strictEqual(ee.listenerCount("error"), 1);
- const [err] = await promise;
- strictEqual(err, expected);
- strictEqual(ee.listenerCount("error"), 0);
- strictEqual(ee.listenerCount("myevent"), 0);
-});
-
-test("onceWithEventTarget", async () => {
- const et = new EventTarget();
- const event = new Event("myevent");
- process.nextTick(() => {
- et.dispatchEvent(event);
- });
- const [value] = await once(et, "myevent");
- strictEqual(value, event);
-});
-
-test("onceWithEventTargetError", async () => {
- const et = new EventTarget();
- const error = new Event("error");
- process.nextTick(() => {
- et.dispatchEvent(error);
- });
-
- const [err] = await once(et, "error");
- strictEqual(err, error);
-});
-
-test("onceWithInvalidEventEmmiter", async () => {
- const ac = new AbortController();
- expect.toThrowWithCode(() => once(ac, "myevent"), "ERR_INVALID_ARG_TYPE");
-});
-
-test("prioritizesEventEmitter", async () => {
- const ee = new EventEmitter();
- ee.addEventListener = fail;
- ee.removeAllListeners = fail;
- process.nextTick(() => ee.emit("foo"));
- await once(ee, "foo");
-});
-
-test("abortSignalBefore", async () => {
- const ee = new EventEmitter();
- ee.on("error", () => expect(false).toEqual(true));
- const abortedSignal = AbortSignal.abort();
-
- await Promise.all(
- [1, {}, "hi", null, false].map(signal => {
- expect.toThrowWithCode(() => once(ee, "foo", { signal }), "ERR_INVALID_ARG_TYPE");
- }),
- );
-
- expect(() => once(ee, "foo", { signal: abortedSignal })).toThrow();
-});
-
-test("abortSignalAfter", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
- ee.on("error", () => expect(false).toEqual(true));
- const r = rejects(once(ee, "foo", { signal: ac.signal }), {
- name: "AbortError",
- });
- process.nextTick(() => ac.abort());
- return r;
-});
-
-test("abortSignalAfterEvent", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
- process.nextTick(() => {
- ee.emit("foo");
- ac.abort();
- });
- const promise = once(ee, "foo", { signal: ac.signal });
- strictEqual(listenerCount(ac.signal, "abort"), 1);
- await promise;
- strictEqual(listenerCount(ac.signal, "abort"), 0);
-});
-
-test("abortSignalRemoveListener", async () => {
- const ee = new EventEmitter();
- const ac = new AbortController();
-
- try {
- process.nextTick(() => ac.abort());
- await once(ee, "test", { signal: ac.signal });
- } catch {
- strictEqual(ee.listeners("test").length, 0);
- strictEqual(ee.listeners("error").length, 0);
- }
-});
-
-test.skip("eventTargetAbortSignalBefore", async () => {
- const et = new EventTarget();
- const abortedSignal = AbortSignal.abort();
-
- await Promise.all(
- [1, {}, "hi", null, false].map(signal => {
- return rejects(once(et, "foo", { signal }), {
- code: "ERR_INVALID_ARG_TYPE",
- });
- }),
- );
-
- return rejects(once(et, "foo", { signal: abortedSignal }), {
- name: "AbortError",
- });
-});
-
-test.skip("eventTargetAbortSignalBeforeEvenWhenSignalPropagationStopped", async () => {
- const et = new EventTarget();
- const ac = new AbortController();
- const { signal } = ac;
- signal.addEventListener("abort", e => e.stopImmediatePropagation(), { once: true });
-
- process.nextTick(() => ac.abort());
- return rejects(once(et, "foo", { signal }), {
- name: "AbortError",
- });
-});
-
-test("eventTargetAbortSignalAfter", async () => {
- const et = new EventTarget();
- const ac = new AbortController();
- const r = rejects(once(et, "foo", { signal: ac.signal }), {
- name: "AbortError",
- });
- process.nextTick(() => ac.abort());
- return r;
-});
-
-test("eventTargetAbortSignalAfterEvent", async () => {
- const et = new EventTarget();
- const ac = new AbortController();
- process.nextTick(() => {
- et.dispatchEvent(new Event("foo"));
- ac.abort();
- });
- await once(et, "foo", { signal: ac.signal });
-});
diff --git a/test/js/node/test/parallel/eventsource-disabled.test.js b/test/js/node/test/parallel/eventsource-disabled.test.js
deleted file mode 100644
index 0b7c76c1e2..0000000000
--- a/test/js/node/test/parallel/eventsource-disabled.test.js
+++ /dev/null
@@ -1,10 +0,0 @@
-//#FILE: test-eventsource-disabled.js
-//#SHA1: ebb7581b56a8dd86c5385eba1befa9ef984a8065
-//-----------------
-"use strict";
-
-test("EventSource is undefined", () => {
- expect(typeof EventSource).toBe("undefined");
-});
-
-//<#END_FILE: test-eventsource-disabled.js
diff --git a/test/js/node/test/parallel/eventtarget-once-twice.test.js b/test/js/node/test/parallel/eventtarget-once-twice.test.js
deleted file mode 100644
index 74f19e01b0..0000000000
--- a/test/js/node/test/parallel/eventtarget-once-twice.test.js
+++ /dev/null
@@ -1,24 +0,0 @@
-//#FILE: test-eventtarget-once-twice.js
-//#SHA1: dd2fea0f3c839d77c64423ed3c2cbdd319365141
-//-----------------
-"use strict";
-
-const { once } = require("events");
-
-test("once can be called twice on EventTarget", async () => {
- const et = new EventTarget();
-
- const promise = (async () => {
- await once(et, "foo");
- await once(et, "foo");
- })();
-
- et.dispatchEvent(new Event("foo"));
- setImmediate(() => {
- et.dispatchEvent(new Event("foo"));
- });
-
- await expect(promise).resolves.toBeUndefined();
-});
-
-//<#END_FILE: test-eventtarget-once-twice.js
diff --git a/test/js/node/test/parallel/fetch-mock.test.js b/test/js/node/test/parallel/fetch-mock.test.js
deleted file mode 100644
index 84bce7c9a7..0000000000
--- a/test/js/node/test/parallel/fetch-mock.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-//#FILE: test-fetch-mock.js
-//#SHA1: 92268be36b00e63e18a837088b9718344c3bff4f
-//-----------------
-"use strict";
-
-test("should correctly stub globalThis.fetch", async () => {
- const customFetch = async url => {
- return {
- text: async () => "foo",
- };
- };
-
- const originalFetch = globalThis.fetch;
- globalThis.fetch = jest.fn(customFetch);
-
- const response = await globalThis.fetch("some-url");
- const text = await response.text();
-
- expect(text).toBe("foo");
- expect(globalThis.fetch).toHaveBeenCalledWith("some-url");
-
- // Restore the original fetch
- globalThis.fetch = originalFetch;
-});
-
-//<#END_FILE: test-fetch-mock.js
diff --git a/test/js/node/test/parallel/file-read-noexist.test.js b/test/js/node/test/parallel/file-read-noexist.test.js
deleted file mode 100644
index 199afac796..0000000000
--- a/test/js/node/test/parallel/file-read-noexist.test.js
+++ /dev/null
@@ -1,45 +0,0 @@
-//#FILE: test-file-read-noexist.js
-//#SHA1: c4cbb5dc6abca53c1dd513a4ece2741c1fc2235a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const path = require("path");
-
-const filename = path.join(__dirname, "fixtures", "does_not_exist.txt");
-
-test("fs.readFile with non-existent file", async () => {
- await expect(
- new Promise((resolve, reject) => {
- fs.readFile(filename, "latin1", (err, content) => {
- if (err) reject(err);
- else resolve(content);
- });
- }),
- ).rejects.toMatchObject({
- code: "ENOENT",
- message: expect.any(String),
- });
-});
-
-//<#END_FILE: test-file-read-noexist.js
diff --git a/test/js/node/test/parallel/finalization-registry-shutdown.test.js b/test/js/node/test/parallel/finalization-registry-shutdown.test.js
deleted file mode 100644
index 9dfd3c99c2..0000000000
--- a/test/js/node/test/parallel/finalization-registry-shutdown.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-//#FILE: test-finalization-registry-shutdown.js
-//#SHA1: c5da440f8ea977c501bb5920f55ce69b1da6e28d
-//-----------------
-// Flags: --expose-gc
-"use strict";
-
-// This test verifies that when a V8 FinalizationRegistryCleanupTask is queue
-// at the last moment when JavaScript can be executed, the callback of a
-// FinalizationRegistry will not be invoked and the process should exit
-// normally.
-
-test("FinalizationRegistry callback should not be called during shutdown", () => {
- const mockCallback = jest.fn();
- const reg = new FinalizationRegistry(mockCallback);
-
- function register() {
- // Create a temporary object in a new function scope to allow it to be GC-ed.
- reg.register({});
- }
-
- const exitHandler = () => {
- // This is the final chance to execute JavaScript.
- register();
- // Queue a FinalizationRegistryCleanupTask by a testing gc request.
- global.gc();
- };
-
- process.on("exit", exitHandler);
-
- // Simulate the exit process
- exitHandler();
-
- // Verify that the callback was not called
- expect(mockCallback).not.toHaveBeenCalled();
-
- // Clean up
- process.removeListener("exit", exitHandler);
-});
-
-//<#END_FILE: test-finalization-registry-shutdown.js
diff --git a/test/js/node/test/parallel/fs-chown-type-check.test.js b/test/js/node/test/parallel/fs-chown-type-check.test.js
deleted file mode 100644
index 4a899dd46e..0000000000
--- a/test/js/node/test/parallel/fs-chown-type-check.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-//#FILE: test-fs-chown-type-check.js
-//#SHA1: 6ecbd3ae2da32793768e64e9252d749ddf36c85a
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-describe("fs.chown and fs.chownSync type checks", () => {
- test("invalid path argument", () => {
- [false, 1, {}, [], null, undefined].forEach(invalidPath => {
- expect(() => fs.chown(invalidPath, 1, 1, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.chownSync(invalidPath, 1, 1)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
- });
- });
-
- test("invalid uid or gid arguments", () => {
- [false, "test", {}, [], null, undefined].forEach(invalidId => {
- expect(() => fs.chown("not_a_file_that_exists", invalidId, 1, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.chown("not_a_file_that_exists", 1, invalidId, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.chownSync("not_a_file_that_exists", invalidId, 1)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.chownSync("not_a_file_that_exists", 1, invalidId)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
- });
- });
-});
-
-//<#END_FILE: test-fs-chown-type-check.js
diff --git a/test/js/node/test/parallel/fs-constants.test.js b/test/js/node/test/parallel/fs-constants.test.js
deleted file mode 100644
index 0d1332c1bb..0000000000
--- a/test/js/node/test/parallel/fs-constants.test.js
+++ /dev/null
@@ -1,13 +0,0 @@
-//#FILE: test-fs-constants.js
-//#SHA1: 6113ac0dd5e6b3d59252a25e6ddae61b589ca362
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-test("fs constants for Windows chmod() are defined", () => {
- expect(fs.constants.S_IRUSR).toBeDefined();
- expect(fs.constants.S_IWUSR).toBeDefined();
-});
-
-//<#END_FILE: test-fs-constants.js
diff --git a/test/js/node/test/parallel/fs-copyfile-respect-permissions.test.js b/test/js/node/test/parallel/fs-copyfile-respect-permissions.test.js
deleted file mode 100644
index 39d72c9cd6..0000000000
--- a/test/js/node/test/parallel/fs-copyfile-respect-permissions.test.js
+++ /dev/null
@@ -1,76 +0,0 @@
-//#FILE: test-fs-copyfile-respect-permissions.js
-//#SHA1: 5a5d15dd2a31fab3f8cffa86fcaedc7dab528c9f
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const isWindows = process.platform === 'win32';
-const isIBMi = process.platform === 'os400';
-
-if (!isWindows && process.getuid() === 0) {
- it.skip('should not run as root', () => {});
-} else if (isIBMi) {
- it.skip('IBMi has a different access permission mechanism', () => {});
-} else {
- const tmpdir = path.join(os.tmpdir(), 'test-fs-copyfile-respect-permissions');
-
- beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- });
-
- afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- });
-
- let n = 0;
-
- function beforeEach() {
- n++;
- const source = path.join(tmpdir, `source${n}`);
- const dest = path.join(tmpdir, `dest${n}`);
- fs.writeFileSync(source, 'source');
- fs.writeFileSync(dest, 'dest');
- fs.chmodSync(dest, '444');
-
- const check = (err) => {
- const expected = ['EACCES', 'EPERM'];
- expect(expected).toContain(err.code);
- expect(fs.readFileSync(dest, 'utf8')).toBe('dest');
- return true;
- };
-
- return { source, dest, check };
- }
-
- test('synchronous API', () => {
- const { source, dest, check } = beforeEach();
- expect(() => { fs.copyFileSync(source, dest); }).toThrow(expect.objectContaining({
- message: expect.any(String),
- code: expect.stringMatching(/^(EACCES|EPERM)$/)
- }));
- });
-
- test('promises API', async () => {
- const { source, dest, check } = beforeEach();
- await expect(fs.promises.copyFile(source, dest)).rejects.toThrow(expect.objectContaining({
- message: expect.any(String),
- code: expect.stringMatching(/^(EACCES|EPERM)$/)
- }));
- });
-
- test('callback API', (done) => {
- const { source, dest, check } = beforeEach();
- fs.copyFile(source, dest, (err) => {
- expect(check(err)).toBe(true);
- done();
- });
- });
-}
-
-//<#END_FILE: test-fs-copyfile-respect-permissions.js
diff --git a/test/js/node/test/parallel/fs-empty-readstream.test.js b/test/js/node/test/parallel/fs-empty-readstream.test.js
deleted file mode 100644
index cc018a90b7..0000000000
--- a/test/js/node/test/parallel/fs-empty-readstream.test.js
+++ /dev/null
@@ -1,68 +0,0 @@
-//#FILE: test-fs-empty-readStream.js
-//#SHA1: 979f558eb3c86e2d897cb766be1f300bbb0cbf8c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-'use strict';
-const fs = require('fs');
-const path = require('path');
-
-const emptyFile = path.join(__dirname, '..', 'fixtures', 'empty.txt');
-
-test('read stream on empty file should not emit data event', (done) => {
- fs.open(emptyFile, 'r', (err, fd) => {
- expect(err).toBeNull();
- const read = fs.createReadStream(emptyFile, { fd });
-
- const dataHandler = jest.fn();
- read.once('data', dataHandler);
-
- read.once('end', () => {
- expect(dataHandler).not.toHaveBeenCalled();
- done();
- });
- });
-});
-
-test('paused read stream on empty file should not emit data or end events', (done) => {
- fs.open(emptyFile, 'r', (err, fd) => {
- expect(err).toBeNull();
- const read = fs.createReadStream(emptyFile, { fd });
-
- read.pause();
-
- const dataHandler = jest.fn();
- read.once('data', dataHandler);
-
- const endHandler = jest.fn();
- read.once('end', endHandler);
-
- setTimeout(() => {
- expect(read.isPaused()).toBe(true);
- expect(dataHandler).not.toHaveBeenCalled();
- expect(endHandler).not.toHaveBeenCalled();
- done();
- }, 50);
- });
-});
-
-//<#END_FILE: test-fs-empty-readStream.js
diff --git a/test/js/node/test/parallel/fs-exists.test.js b/test/js/node/test/parallel/fs-exists.test.js
deleted file mode 100644
index 3cea91fc1c..0000000000
--- a/test/js/node/test/parallel/fs-exists.test.js
+++ /dev/null
@@ -1,74 +0,0 @@
-//#FILE: test-fs-exists.js
-//#SHA1: b7dcbc226b81e0ae4a111cbab39b87672a02172c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const f = __filename;
-
-test("fs.exists throws with invalid arguments", () => {
- expect(() => fs.exists(f)).toThrow(expect.objectContaining({ code: "ERR_INVALID_ARG_TYPE" }));
- expect(() => fs.exists()).toThrow(expect.objectContaining({ code: "ERR_INVALID_ARG_TYPE" }));
- expect(() => fs.exists(f, {})).toThrow(expect.objectContaining({ code: "ERR_INVALID_ARG_TYPE" }));
-});
-
-test("fs.exists with valid file", done => {
- fs.exists(f, y => {
- expect(y).toBe(true);
- done();
- });
-});
-
-test("fs.exists with non-existent file", done => {
- fs.exists(`${f}-NO`, y => {
- expect(y).toBe(false);
- done();
- });
-});
-
-test("fs.exists with invalid path", done => {
- fs.exists(new URL("https://foo"), y => {
- expect(y).toBe(false);
- done();
- });
-});
-
-test("fs.exists with object as path", done => {
- fs.exists({}, y => {
- expect(y).toBe(false);
- done();
- });
-});
-
-test("fs.existsSync", () => {
- expect(fs.existsSync(f)).toBe(true);
- expect(fs.existsSync(`${f}-NO`)).toBe(false);
-});
-
-test("fs.existsSync never throws", () => {
- expect(fs.existsSync()).toBe(false);
- expect(fs.existsSync({})).toBe(false);
- expect(fs.existsSync(new URL("https://foo"))).toBe(false);
-});
-
-//<#END_FILE: test-fs-exists.js
diff --git a/test/js/node/test/parallel/fs-fsync.test.js b/test/js/node/test/parallel/fs-fsync.test.js
deleted file mode 100644
index b4d17d9ac9..0000000000
--- a/test/js/node/test/parallel/fs-fsync.test.js
+++ /dev/null
@@ -1,79 +0,0 @@
-//#FILE: test-fs-fsync.js
-//#SHA1: 4225be75eaedfd17c32e0472e6739ba232b7f28e
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const fileFixture = path.join(__dirname, '..', 'fixtures', 'a.js');
-const tmpdir = path.join(os.tmpdir(), 'test-fs-fsync');
-const fileTemp = path.join(tmpdir, 'a.js');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- fs.copyFileSync(fileFixture, fileTemp);
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('fsync and fdatasync operations', (done) => {
- fs.open(fileTemp, 'a', 0o777, (err, fd) => {
- expect(err).toBeNull();
-
- fs.fdatasyncSync(fd);
- fs.fsyncSync(fd);
-
- fs.fdatasync(fd, (err) => {
- expect(err).toBeNull();
- fs.fsync(fd, (err) => {
- expect(err).toBeNull();
- fs.closeSync(fd);
- done();
- });
- });
- });
-});
-
-test('invalid inputs throw TypeError', () => {
- const invalidInputs = ['', false, null, undefined, {}, []];
- const errObj = {
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError'
- };
-
- invalidInputs.forEach((input) => {
- expect(() => fs.fdatasync(input)).toThrow(expect.objectContaining(errObj));
- expect(() => fs.fdatasyncSync(input)).toThrow(expect.objectContaining(errObj));
- expect(() => fs.fsync(input)).toThrow(expect.objectContaining(errObj));
- expect(() => fs.fsyncSync(input)).toThrow(expect.objectContaining(errObj));
- });
-});
-
-//<#END_FILE: test-fs-fsync.js
diff --git a/test/js/node/test/parallel/fs-link.test.js b/test/js/node/test/parallel/fs-link.test.js
deleted file mode 100644
index 4b6be724f2..0000000000
--- a/test/js/node/test/parallel/fs-link.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-fs-link.js
-//#SHA1: 255940f3f953a4bd693b3e475bc466d5f759875f
-//-----------------
-"use strict";
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const tmpdir = {
- refresh: () => {
- // Implement a simple tmpdir.refresh() function
- const testDir = path.join(os.tmpdir(), "test-fs-link");
- fs.rmSync(testDir, { recursive: true, force: true });
- fs.mkdirSync(testDir, { recursive: true });
- return testDir;
- },
- resolve: filename => path.join(tmpdir.refresh(), filename),
-};
-
-test("Test creating and reading hard link", done => {
- const srcPath = tmpdir.resolve("hardlink-target.txt");
- const dstPath = tmpdir.resolve("link1.js");
- fs.writeFileSync(srcPath, "hello world");
-
- fs.link(srcPath, dstPath, err => {
- expect(err).toBeFalsy();
- const dstContent = fs.readFileSync(dstPath, "utf8");
- expect(dstContent).toBe("hello world");
- done();
- });
-});
-
-test("test error outputs", () => {
- [false, 1, [], {}, null, undefined].forEach(i => {
- expect(() => fs.link(i, "", () => {})).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.link("", i, () => {})).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.linkSync(i, "")).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- expect(() => fs.linkSync("", i)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
- });
-});
-
-//<#END_FILE: test-fs-link.js
diff --git a/test/js/node/test/parallel/fs-make-callback.test.js b/test/js/node/test/parallel/fs-make-callback.test.js
deleted file mode 100644
index db3860cbd6..0000000000
--- a/test/js/node/test/parallel/fs-make-callback.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-fs-make-callback.js
-//#SHA1: 40bbb673a0865f464a2b9e40110e903b6cc9e0d6
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const { sep } = require("path");
-const tmpdir = require("../common/tmpdir");
-
-const callbackThrowValues = [null, true, false, 0, 1, "foo", /foo/, [], {}];
-
-beforeEach(() => {
- tmpdir.refresh();
-});
-
-function testMakeCallback(cb) {
- return function () {
- // fs.mkdtemp() calls makeCallback() on its third argument
- return fs.mkdtemp(`${tmpdir.path}${sep}`, {}, cb);
- };
-}
-
-describe("fs.makeCallback", () => {
- test("invalid callbacks throw TypeError", () => {
- callbackThrowValues.forEach(value => {
- expect(testMakeCallback(value)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
- });
-});
-
-//<#END_FILE: test-fs-make-callback.js
diff --git a/test/js/node/test/parallel/fs-makestatscallback.test.js b/test/js/node/test/parallel/fs-makestatscallback.test.js
deleted file mode 100644
index 839e3b4f45..0000000000
--- a/test/js/node/test/parallel/fs-makestatscallback.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-fs-makeStatsCallback.js
-//#SHA1: e8c59eddd5ca920ba0a1aaa4dd87c3af879db3b1
-//-----------------
-'use strict';
-const fs = require('fs');
-
-function testMakeStatsCallback(cb) {
- return function() {
- // fs.stat() calls makeStatsCallback() on its second argument
- fs.stat(__filename, cb);
- };
-}
-
-test('Verify the case where a callback function is provided', (done) => {
- testMakeStatsCallback(() => {
- done();
- })();
-});
-
-test('Invalid callback throws TypeError', () => {
- const callbackThrowValues = [null, true, false, 0, 1, 'foo', /foo/, [], {}];
-
- callbackThrowValues.forEach((value) => {
- expect(testMakeStatsCallback(value)).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
- });
-});
-
-//<#END_FILE: test-fs-makeStatsCallback.js
diff --git a/test/js/node/test/parallel/fs-mkdir-recursive-eaccess.test.js b/test/js/node/test/parallel/fs-mkdir-recursive-eaccess.test.js
deleted file mode 100644
index 570d2617ff..0000000000
--- a/test/js/node/test/parallel/fs-mkdir-recursive-eaccess.test.js
+++ /dev/null
@@ -1,81 +0,0 @@
-//#FILE: test-fs-mkdir-recursive-eaccess.js
-//#SHA1: 1e0e4f480b7573549c130b4177759bd60adc1890
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const { execSync } = require('child_process');
-const os = require('os');
-
-const isWindows = process.platform === 'win32';
-const isIBMi = process.platform === 'os400';
-
-if (isIBMi) {
- console.log('Skipped: IBMi has a different access permission mechanism');
- process.exit(0);
-}
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-mkdir-recursive-eaccess');
-
-let n = 0;
-
-function makeDirectoryReadOnly(dir) {
- let accessErrorCode = 'EACCES';
- if (isWindows) {
- accessErrorCode = 'EPERM';
- execSync(`icacls ${dir} /deny "everyone:(OI)(CI)(DE,DC,AD,WD)"`);
- } else {
- fs.chmodSync(dir, '444');
- }
- return accessErrorCode;
-}
-
-function makeDirectoryWritable(dir) {
- if (isWindows) {
- execSync(`icacls ${dir} /remove:d "everyone"`);
- }
-}
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('Synchronous API should return an EACCES/EPERM error with path populated', () => {
- const dir = path.join(tmpdir, `mkdirp_${n++}`);
- fs.mkdirSync(dir);
- const codeExpected = makeDirectoryReadOnly(dir);
-
- expect(() => {
- fs.mkdirSync(path.join(dir, '/foo'), { recursive: true });
- }).toThrow(expect.objectContaining({
- code: codeExpected,
- path: expect.any(String)
- }));
-
- makeDirectoryWritable(dir);
-});
-
-test('Asynchronous API should return an EACCES/EPERM error with path populated', (done) => {
- const dir = path.join(tmpdir, `mkdirp_${n++}`);
- fs.mkdirSync(dir);
- const codeExpected = makeDirectoryReadOnly(dir);
-
- fs.mkdir(path.join(dir, '/bar'), { recursive: true }, (err) => {
- makeDirectoryWritable(dir);
- expect(err).toEqual(expect.objectContaining({
- code: codeExpected,
- path: expect.any(String)
- }));
- done();
- });
-});
-
-//<#END_FILE: test-fs-mkdir-recursive-eaccess.js
diff --git a/test/js/node/test/parallel/fs-mkdtemp-prefix-check.test.js b/test/js/node/test/parallel/fs-mkdtemp-prefix-check.test.js
deleted file mode 100644
index 81690d9c17..0000000000
--- a/test/js/node/test/parallel/fs-mkdtemp-prefix-check.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-fs-mkdtemp-prefix-check.js
-//#SHA1: f17d58f63200ae9b8c855b9def7da223fc5db531
-//-----------------
-"use strict";
-const fs = require("fs");
-
-const prefixValues = [undefined, null, 0, true, false, 1];
-
-describe("fs.mkdtempSync prefix check", () => {
- test.each(prefixValues)("should throw for invalid prefix: %p", value => {
- expect(() => {
- fs.mkdtempSync(value, {});
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-describe("fs.mkdtemp prefix check", () => {
- test.each(prefixValues)("should throw for invalid prefix: %p", value => {
- expect(() => {
- fs.mkdtemp(value, jest.fn());
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-fs-mkdtemp-prefix-check.js
diff --git a/test/js/node/test/parallel/fs-non-number-arguments-throw.test.js b/test/js/node/test/parallel/fs-non-number-arguments-throw.test.js
deleted file mode 100644
index fa7ff3127d..0000000000
--- a/test/js/node/test/parallel/fs-non-number-arguments-throw.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-fs-non-number-arguments-throw.js
-//#SHA1: 65db5c653216831bc16d38c5d659fbffa296d3d8
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-non-number-arguments-throw');
-const tempFile = path.join(tmpdir, 'fs-non-number-arguments-throw');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- fs.writeFileSync(tempFile, 'abc\ndef');
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('createReadStream with valid number arguments', (done) => {
- const sanity = 'def';
- const saneEmitter = fs.createReadStream(tempFile, { start: 4, end: 6 });
-
- saneEmitter.on('data', (data) => {
- expect(data.toString('utf8')).toBe(sanity);
- done();
- });
-});
-
-test('createReadStream throws with string start argument', () => {
- expect(() => {
- fs.createReadStream(tempFile, { start: '4', end: 6 });
- }).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
-});
-
-test('createReadStream throws with string end argument', () => {
- expect(() => {
- fs.createReadStream(tempFile, { start: 4, end: '6' });
- }).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
-});
-
-test('createWriteStream throws with string start argument', () => {
- expect(() => {
- fs.createWriteStream(tempFile, { start: '4' });
- }).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
-});
-
-//<#END_FILE: test-fs-non-number-arguments-throw.js
diff --git a/test/js/node/test/parallel/fs-open-mode-mask.test.js b/test/js/node/test/parallel/fs-open-mode-mask.test.js
deleted file mode 100644
index 798005d296..0000000000
--- a/test/js/node/test/parallel/fs-open-mode-mask.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-fs-open-mode-mask.js
-//#SHA1: d290e7c1bced1fc3a98f27e2aeb463051581376c
-//-----------------
-"use strict";
-
-// This tests that the lower bits of mode > 0o777 still works in fs.open().
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const mode = process.platform === "win32" ? 0o444 : 0o644;
-
-const maskToIgnore = 0o10000;
-
-const tmpdir = path.join(os.tmpdir(), "test-fs-open-mode-mask");
-
-beforeAll(() => {
- try {
- fs.mkdirSync(tmpdir, { recursive: true });
- } catch (err) {
- // Directory might already exist
- }
-});
-
-afterAll(() => {
- try {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- } catch (err) {
- // Ignore errors during cleanup
- }
-});
-
-function test(mode, asString) {
- const suffix = asString ? "str" : "num";
- const input = asString ? (mode | maskToIgnore).toString(8) : mode | maskToIgnore;
-
- it(`should work with ${suffix} input`, () => {
- const file = path.join(tmpdir, `openSync-${suffix}.txt`);
- const fd = fs.openSync(file, "w+", input);
- expect(fs.fstatSync(fd).mode & 0o777).toBe(mode);
- fs.closeSync(fd);
- expect(fs.statSync(file).mode & 0o777).toBe(mode);
- });
-
- it(`should work with ${suffix} input using callback`, done => {
- const file = path.join(tmpdir, `open-${suffix}.txt`);
- fs.open(file, "w+", input, (err, fd) => {
- expect(err).toBeNull();
- expect(fs.fstatSync(fd).mode & 0o777).toBe(mode);
- fs.closeSync(fd);
- expect(fs.statSync(file).mode & 0o777).toBe(mode);
- done();
- });
- });
-}
-
-test(mode, true);
-test(mode, false);
-
-//<#END_FILE: test-fs-open-mode-mask.js
diff --git a/test/js/node/test/parallel/fs-open-no-close.test.js b/test/js/node/test/parallel/fs-open-no-close.test.js
deleted file mode 100644
index fbd17dc78c..0000000000
--- a/test/js/node/test/parallel/fs-open-no-close.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-fs-open-no-close.js
-//#SHA1: 3f09a04c65d9a376e5d9b82882d375ab1dc99ad9
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const debuglog = (arg) => {
- console.log(new Date().toLocaleString(), arg);
-};
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-open-no-close');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('fs.open should not keep the event loop open if file is not closed', (done) => {
- let openFd;
-
- fs.open(path.join(tmpdir, 'dummy'), 'wx+', (err, fd) => {
- debuglog('fs open() callback');
- expect(err).toBeFalsy();
- openFd = fd;
- done();
- });
-
- debuglog('waiting for callback');
-
- // Simulate process.on('beforeExit') behavior
- process.nextTick(() => {
- if (openFd) {
- fs.closeSync(openFd);
- }
- });
-});
-
-//<#END_FILE: test-fs-open-no-close.js
diff --git a/test/js/node/test/parallel/fs-open-numeric-flags.test.js b/test/js/node/test/parallel/fs-open-numeric-flags.test.js
deleted file mode 100644
index 4edec0e495..0000000000
--- a/test/js/node/test/parallel/fs-open-numeric-flags.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-fs-open-numeric-flags.js
-//#SHA1: 31a49fd78cbd63ab0b41de5f051d029bbe22fded
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// Create a temporary directory for our tests
-const tmpdir = path.join(os.tmpdir(), "test-fs-open-numeric-flags");
-
-beforeEach(() => {
- // Ensure the temporary directory exists and is empty
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterEach(() => {
- // Clean up the temporary directory after each test
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
-});
-
-test("O_WRONLY without O_CREAT shall fail with ENOENT", () => {
- const pathNE = path.join(tmpdir, "file-should-not-exist");
-
- expect(() => {
- fs.openSync(pathNE, fs.constants.O_WRONLY);
- }).toThrow(
- expect.objectContaining({
- code: "ENOENT",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-fs-open-numeric-flags.js
diff --git a/test/js/node/test/parallel/fs-open.test.js b/test/js/node/test/parallel/fs-open.test.js
deleted file mode 100644
index c8c102d7a3..0000000000
--- a/test/js/node/test/parallel/fs-open.test.js
+++ /dev/null
@@ -1,102 +0,0 @@
-//#FILE: test-fs-open.js
-//#SHA1: 0466ad8882a3256fdd8da5fc8da3167f6dde4fd6
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-
-test('fs.openSync throws ENOENT for non-existent file', () => {
- expect(() => {
- fs.openSync('/8hvftyuncxrt/path/to/file/that/does/not/exist', 'r');
- }).toThrow(expect.objectContaining({
- code: 'ENOENT',
- message: expect.any(String)
- }));
-});
-
-test('fs.openSync succeeds for existing file', () => {
- expect(() => fs.openSync(__filename)).not.toThrow();
-});
-
-test('fs.open succeeds with various valid arguments', async () => {
- await expect(fs.promises.open(__filename)).resolves.toBeDefined();
- await expect(fs.promises.open(__filename, 'r')).resolves.toBeDefined();
- await expect(fs.promises.open(__filename, 'rs')).resolves.toBeDefined();
- await expect(fs.promises.open(__filename, 'r', 0)).resolves.toBeDefined();
- await expect(fs.promises.open(__filename, 'r', null)).resolves.toBeDefined();
-});
-
-test('fs.open throws for invalid mode argument', () => {
- expect(() => fs.open(__filename, 'r', 'boom', () => {})).toThrow(({
- code: 'ERR_INVALID_ARG_VALUE',
- name: 'TypeError',
- message: `The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received boom`
- }));
- expect(() => fs.open(__filename, 'r', 5.5, () => {})).toThrow(({
- code: 'ERR_OUT_OF_RANGE',
- name: 'RangeError',
- message: `The value of "mode" is out of range. It must be an integer. Received 5.5`
- }));
- expect(() => fs.open(__filename, 'r', -7, () => {})).toThrow(({
- code: 'ERR_OUT_OF_RANGE',
- name: 'RangeError',
- message: `The value of "mode" is out of range. It must be >= 0 and <= 4294967295. Received -7`
- }));
- expect(() => fs.open(__filename, 'r', 4304967295, () => {})).toThrow(({
- code: 'ERR_OUT_OF_RANGE',
- name: 'RangeError',
- message: `The value of "mode" is out of range. It must be >= 0 and <= 4294967295. Received 4304967295`
- }));
-});
-
-test('fs.open throws for invalid argument combinations', () => {
- const invalidArgs = [[], ['r'], ['r', 0], ['r', 0, 'bad callback']];
- invalidArgs.forEach(args => {
- expect(() => fs.open(__filename, ...args)).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
- });
-});
-
-test('fs functions throw for invalid path types', () => {
- const invalidPaths = [false, 1, [], {}, null, undefined];
- invalidPaths.forEach(path => {
- expect(() => fs.open(path, 'r', () => {})).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
- expect(() => fs.openSync(path, 'r')).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
- expect(fs.promises.open(path, 'r')).rejects.toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
- });
-});
-
-test('fs functions throw for invalid modes', () => {
- const invalidModes = [false, [], {}];
- invalidModes.forEach(mode => {
- expect(() => fs.open(__filename, 'r', mode, () => {})).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- message: expect.any(String)
- }));
- expect(() => fs.openSync(__filename, 'r', mode)).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- message: expect.any(String)
- }));
- expect(fs.promises.open(__filename, 'r', mode)).rejects.toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- message: expect.any(String)
- }));
- });
-});
-
-//<#END_FILE: test-fs-open.js
diff --git a/test/js/node/test/parallel/fs-operations-with-surrogate-pairs.test.js b/test/js/node/test/parallel/fs-operations-with-surrogate-pairs.test.js
deleted file mode 100644
index 54c9021472..0000000000
--- a/test/js/node/test/parallel/fs-operations-with-surrogate-pairs.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-fs-operations-with-surrogate-pairs.js
-//#SHA1: c59fe103e9ec4edee50c9186d341f5fdd32e0af4
-//-----------------
-"use strict";
-
-const fs = require("node:fs");
-const path = require("node:path");
-const tmpdir = require("../common/tmpdir");
-
-tmpdir.refresh();
-
-describe("File operations with filenames containing surrogate pairs", () => {
- it("should write, read, and delete a file with surrogate pairs in the filename", () => {
- // Create a temporary directory
- const tempdir = fs.mkdtempSync(tmpdir.resolve("emoji-fruit-🍇 🍈 🍉 🍊 🍋"));
- expect(fs.existsSync(tempdir)).toBe(true);
-
- const filename = "🚀🔥🛸.txt";
- const content = "Test content";
-
- // Write content to a file
- fs.writeFileSync(path.join(tempdir, filename), content);
-
- // Read content from the file
- const readContent = fs.readFileSync(path.join(tempdir, filename), "utf8");
-
- // Check if the content matches
- expect(readContent).toBe(content);
- });
-});
-
-//<#END_FILE: test-fs-operations-with-surrogate-pairs.js
diff --git a/test/js/node/test/parallel/fs-options-immutable.test.js b/test/js/node/test/parallel/fs-options-immutable.test.js
deleted file mode 100644
index 9beef4c128..0000000000
--- a/test/js/node/test/parallel/fs-options-immutable.test.js
+++ /dev/null
@@ -1,148 +0,0 @@
-//#FILE: test-fs-options-immutable.js
-//#SHA1: 3e986f4e0d29505ada9980c8af5146abd307ddb7
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// These tests make sure that the `options` object passed to these functions are
-// never altered.
-//
-// Refer: https://github.com/nodejs/node/issues/7655
-
-const originalOptions = {};
-let options;
-
-beforeEach(() => {
- options = JSON.parse(JSON.stringify(originalOptions));
-});
-
-const tmpdir = {
- path: path.join(os.tmpdir(), "node-test-fs-options-immutable"),
- refresh: () => {
- try {
- fs.rmSync(tmpdir.path, { recursive: true, force: true });
- } catch (error) {
- // Ignore errors
- }
- fs.mkdirSync(tmpdir.path, { recursive: true });
- },
- resolve: filename => path.join(tmpdir.path, filename),
-};
-
-tmpdir.refresh();
-
-test("fs.readFile", async () => {
- await fs.promises.readFile(__filename, options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.readFileSync", () => {
- fs.readFileSync(__filename, options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.readdir", async () => {
- await fs.promises.readdir(__dirname, options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.readdirSync", () => {
- fs.readdirSync(__dirname, options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.readlink and fs.readlinkSync", async () => {
- const canCreateSymLink = await new Promise(resolve => {
- fs.symlink(__filename, "dummy-symlink", err => {
- if (err) resolve(false);
- fs.unlink("dummy-symlink", () => resolve(true));
- });
- });
-
- if (canCreateSymLink) {
- const sourceFile = tmpdir.resolve("test-readlink");
- const linkFile = tmpdir.resolve("test-readlink-link");
-
- await fs.promises.writeFile(sourceFile, "");
- await fs.promises.symlink(sourceFile, linkFile);
-
- await fs.promises.readlink(linkFile, options);
- expect(options).toEqual(originalOptions);
-
- fs.readlinkSync(linkFile, options);
- expect(options).toEqual(originalOptions);
- } else {
- test.skip("Symlink tests skipped - cannot create symlinks", () => {});
- }
-});
-
-test("fs.writeFile and fs.writeFileSync", async () => {
- const fileName = tmpdir.resolve("writeFile");
- fs.writeFileSync(fileName, "ABCD", options);
- expect(options).toEqual(originalOptions);
-
- await fs.promises.writeFile(fileName, "ABCD", options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.appendFile and fs.appendFileSync", async () => {
- const fileName = tmpdir.resolve("appendFile");
- fs.appendFileSync(fileName, "ABCD", options);
- expect(options).toEqual(originalOptions);
-
- await fs.promises.appendFile(fileName, "ABCD", options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.watch", () => {
- if (process.platform === "os400") {
- return test.skip("IBMi does not support fs.watch()");
- }
-
- const watch = fs.watch(__filename, options, () => {});
- watch.close();
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.watchFile and fs.unwatchFile", () => {
- fs.watchFile(__filename, options, () => {});
- fs.unwatchFile(__filename);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.realpath and fs.realpathSync", async () => {
- fs.realpathSync(__filename, options);
- expect(options).toEqual(originalOptions);
-
- await fs.promises.realpath(__filename, options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.mkdtemp and fs.mkdtempSync", async () => {
- const tempFileName = tmpdir.resolve("mkdtemp-");
- fs.mkdtempSync(tempFileName, options);
- expect(options).toEqual(originalOptions);
-
- await fs.promises.mkdtemp(tempFileName, options);
- expect(options).toEqual(originalOptions);
-});
-
-test("fs.WriteStream and fs.ReadStream", done => {
- const fileName = tmpdir.resolve("streams");
- const writeStream = fs.createWriteStream(fileName, options);
- writeStream.once("open", () => {
- expect(options).toEqual(originalOptions);
- const readStream = fs.createReadStream(fileName, options);
- readStream.once("open", () => {
- expect(options).toEqual(originalOptions);
- readStream.destroy();
- writeStream.end();
- done();
- });
- });
-});
-
-//<#END_FILE: test-fs-options-immutable.js
diff --git a/test/js/node/test/parallel/fs-promises-exists.test.js b/test/js/node/test/parallel/fs-promises-exists.test.js
deleted file mode 100644
index 303718b0ef..0000000000
--- a/test/js/node/test/parallel/fs-promises-exists.test.js
+++ /dev/null
@@ -1,14 +0,0 @@
-//#FILE: test-fs-promises-exists.js
-//#SHA1: 3766c49e29d13338f3124165428e3a8a37d47fab
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const fsPromises = require("fs/promises");
-
-test("fs.promises exists and is correctly linked", () => {
- expect(fsPromises).toBe(fs.promises);
- expect(fsPromises.constants).toBe(fs.constants);
-});
-
-//<#END_FILE: test-fs-promises-exists.js
diff --git a/test/js/node/test/parallel/fs-promises-file-handle-append-file.test.js b/test/js/node/test/parallel/fs-promises-file-handle-append-file.test.js
deleted file mode 100644
index 746b7614a8..0000000000
--- a/test/js/node/test/parallel/fs-promises-file-handle-append-file.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-fs-promises-file-handle-append-file.js
-//#SHA1: 2a1932450418ea18ef00a890342f29ab307006e7
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const { open } = fs.promises;
-const path = require('path');
-const os = require('os');
-
-const tmpDir = path.join(os.tmpdir(), 'test-fs-promises-file-handle-append-file');
-
-beforeAll(() => {
- if (fs.existsSync(tmpDir)) {
- fs.rmSync(tmpDir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpDir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpDir, { recursive: true, force: true });
-});
-
-test('FileHandle.appendFile with buffer', async () => {
- const filePath = path.resolve(tmpDir, 'tmp-append-file-buffer.txt');
- const fileHandle = await open(filePath, 'a');
- const buffer = Buffer.from('a&Dp'.repeat(100), 'utf8');
-
- await fileHandle.appendFile(buffer);
- const appendedFileData = fs.readFileSync(filePath);
- expect(appendedFileData).toEqual(buffer);
-
- await fileHandle.close();
-});
-
-test('FileHandle.appendFile with string', async () => {
- const filePath = path.resolve(tmpDir, 'tmp-append-file-string.txt');
- const fileHandle = await open(filePath, 'a');
- const string = 'x~yz'.repeat(100);
-
- await fileHandle.appendFile(string);
- const stringAsBuffer = Buffer.from(string, 'utf8');
- const appendedFileData = fs.readFileSync(filePath);
- expect(appendedFileData).toEqual(stringAsBuffer);
-
- await fileHandle.close();
-});
-
-//<#END_FILE: test-fs-promises-file-handle-append-file.js
diff --git a/test/js/node/test/parallel/fs-promises-file-handle-chmod.test.js b/test/js/node/test/parallel/fs-promises-file-handle-chmod.test.js
deleted file mode 100644
index 8bd751f1d1..0000000000
--- a/test/js/node/test/parallel/fs-promises-file-handle-chmod.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-//#FILE: test-fs-promises-file-handle-chmod.js
-//#SHA1: 50a28df8df34deeca4b2f9d7598fb596894d7541
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const { open } = fs.promises;
-const path = require("path");
-const os = require("os");
-
-const tmpDir = os.tmpdir();
-
-beforeEach(() => {
- jest.spyOn(fs, "statSync");
-});
-
-afterEach(() => {
- jest.restoreAllMocks();
-});
-
-test("FileHandle.chmod base functionality", async () => {
- const filePath = path.resolve(tmpDir, "tmp-chmod.txt");
- const fileHandle = await open(filePath, "w+", 0o444);
-
- // File created with r--r--r-- 444
- const statsBeforeMod = fs.statSync(filePath);
- expect(statsBeforeMod.mode & 0o444).toBe(0o444);
-
- let expectedAccess;
- const newPermissions = 0o765;
-
- if (process.platform === "win32") {
- // Chmod in Windows will only toggle read only/write access. The
- // fs.Stats.mode in Windows is computed using read/write
- // bits (not exec). Read-only at best returns 444; r/w 666.
- // Refer: /deps/uv/src/win/fs.cfs;
- expectedAccess = 0o664;
- } else {
- expectedAccess = newPermissions;
- }
-
- // Change the permissions to rwxr--r-x
- await fileHandle.chmod(newPermissions);
- const statsAfterMod = fs.statSync(filePath);
- expect(statsAfterMod.mode & expectedAccess).toBe(expectedAccess);
-
- await fileHandle.close();
-});
-
-//<#END_FILE: test-fs-promises-file-handle-chmod.js
diff --git a/test/js/node/test/parallel/fs-promises-file-handle-write.test.js b/test/js/node/test/parallel/fs-promises-file-handle-write.test.js
deleted file mode 100644
index 1652a75a05..0000000000
--- a/test/js/node/test/parallel/fs-promises-file-handle-write.test.js
+++ /dev/null
@@ -1,93 +0,0 @@
-//#FILE: test-fs-promises-file-handle-write.js
-//#SHA1: 6ca802494e0ce0ee3187b1661322f115cfd7340c
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const { open } = fs.promises;
-const path = require("path");
-const os = require("os");
-
-const tmpDir = path.join(os.tmpdir(), "test-fs-promises-file-handle-write");
-
-beforeAll(() => {
- if (fs.existsSync(tmpDir)) {
- fs.rmSync(tmpDir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpDir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpDir, { recursive: true, force: true });
-});
-
-test("validateWrite", async () => {
- const filePathForHandle = path.resolve(tmpDir, "tmp-write.txt");
- const fileHandle = await open(filePathForHandle, "w+");
- const buffer = Buffer.from("Hello world".repeat(100), "utf8");
-
- await fileHandle.write(buffer, 0, buffer.length);
- const readFileData = fs.readFileSync(filePathForHandle);
- expect(readFileData).toEqual(buffer);
-
- await fileHandle.close();
-});
-
-test("validateEmptyWrite", async () => {
- const filePathForHandle = path.resolve(tmpDir, "tmp-empty-write.txt");
- const fileHandle = await open(filePathForHandle, "w+");
- const buffer = Buffer.from(""); // empty buffer
-
- await fileHandle.write(buffer, 0, buffer.length);
- const readFileData = fs.readFileSync(filePathForHandle);
- expect(readFileData).toEqual(buffer);
-
- await fileHandle.close();
-});
-
-test("validateNonUint8ArrayWrite", async () => {
- const filePathForHandle = path.resolve(tmpDir, "tmp-data-write.txt");
- const fileHandle = await open(filePathForHandle, "w+");
- const buffer = Buffer.from("Hello world", "utf8").toString("base64");
-
- await fileHandle.write(buffer, 0, buffer.length);
- const readFileData = fs.readFileSync(filePathForHandle);
- expect(readFileData).toEqual(Buffer.from(buffer, "utf8"));
-
- await fileHandle.close();
-});
-
-test("validateNonStringValuesWrite", async () => {
- const filePathForHandle = path.resolve(tmpDir, "tmp-non-string-write.txt");
- const fileHandle = await open(filePathForHandle, "w+");
- const nonStringValues = [
- 123,
- {},
- new Map(),
- null,
- undefined,
- 0n,
- () => {},
- Symbol(),
- true,
- new String("notPrimitive"),
- {
- toString() {
- return "amObject";
- },
- },
- { [Symbol.toPrimitive]: hint => "amObject" },
- ];
- for (const nonStringValue of nonStringValues) {
- await expect(fileHandle.write(nonStringValue)).rejects.toThrow(
- expect.objectContaining({
- message: expect.stringMatching(/"buffer"/),
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
- }
-
- await fileHandle.close();
-});
-
-//<#END_FILE: test-fs-promises-file-handle-write.js
diff --git a/test/js/node/test/parallel/fs-promises-readfile-empty.test.js b/test/js/node/test/parallel/fs-promises-readfile-empty.test.js
deleted file mode 100644
index dc9d291e5f..0000000000
--- a/test/js/node/test/parallel/fs-promises-readfile-empty.test.js
+++ /dev/null
@@ -1,27 +0,0 @@
-//#FILE: test-fs-promises-readfile-empty.js
-//#SHA1: 6fcec9b5d3c9617426d46c79fb79244bc236574b
-//-----------------
-"use strict";
-
-const fs = require("fs").promises;
-const path = require("path");
-
-const fixturesPath = path.resolve(__dirname, "..", "fixtures");
-const fn = path.join(fixturesPath, "empty.txt");
-
-test("fs.readFile on empty file", async () => {
- const content = await fs.readFile(fn);
- expect(content).toBeTruthy();
-});
-
-test("fs.readFile on empty file with utf8 encoding", async () => {
- const content = await fs.readFile(fn, "utf8");
- expect(content).toBe("");
-});
-
-test("fs.readFile on empty file with options object", async () => {
- const content = await fs.readFile(fn, { encoding: "utf8" });
- expect(content).toBe("");
-});
-
-//<#END_FILE: test-fs-promises-readfile-empty.js
diff --git a/test/js/node/test/parallel/fs-promises-readfile-with-fd.test.js b/test/js/node/test/parallel/fs-promises-readfile-with-fd.test.js
deleted file mode 100644
index 1f286daab3..0000000000
--- a/test/js/node/test/parallel/fs-promises-readfile-with-fd.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-fs-promises-readfile-with-fd.js
-//#SHA1: 041811f02dddcdb9eba7d97e3943e26ec6b881cd
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const fsPromises = require('fs').promises;
-const path = require('path');
-const os = require('os');
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-promises-readfile-with-fd');
-const fn = path.join(tmpdir, 'test.txt');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- fs.writeFileSync(fn, 'Hello World');
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('readFile() reads from current position of the file', async () => {
- const handle = await fsPromises.open(fn, 'r');
-
- // Read only five bytes, so that the position moves to five.
- const buf = Buffer.alloc(5);
- const { bytesRead } = await handle.read(buf, 0, 5, null);
- expect(bytesRead).toBe(5);
- expect(buf.toString()).toBe('Hello');
-
- // readFile() should read from position five, instead of zero.
- expect((await handle.readFile()).toString()).toBe(' World');
-
- await handle.close();
-});
-
-//<#END_FILE: test-fs-promises-readfile-with-fd.js
diff --git a/test/js/node/test/parallel/fs-promises-writefile-typedarray.test.js b/test/js/node/test/parallel/fs-promises-writefile-typedarray.test.js
deleted file mode 100644
index bece880bd3..0000000000
--- a/test/js/node/test/parallel/fs-promises-writefile-typedarray.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-fs-promises-writefile-typedarray.js
-//#SHA1: 718d3827c56ad0b11c59a801bf9529a1e6e5ab89
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const fsPromises = fs.promises;
-const path = require("path");
-const os = require("os");
-
-const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "test-"));
-
-beforeAll(() => {
- // Ensure the temporary directory is clean
- fs.rmSync(tmpDir, { recursive: true, force: true });
- fs.mkdirSync(tmpDir, { recursive: true });
-});
-
-afterAll(() => {
- // Clean up the temporary directory
- fs.rmSync(tmpDir, { recursive: true, force: true });
-});
-
-const dest = path.resolve(tmpDir, "tmp.txt");
-// Use a file size larger than `kReadFileMaxChunkSize`.
-const buffer = Buffer.from("012".repeat(2 ** 14));
-
-test("fsPromises.writeFile with TypedArrays", async () => {
- const constructors = [Uint8Array, Uint16Array, Uint32Array];
-
- for (const Constructor of constructors) {
- const array = new Constructor(buffer.buffer);
- await fsPromises.writeFile(dest, array);
- const data = await fsPromises.readFile(dest);
- expect(data).toEqual(buffer);
- }
-});
-
-//<#END_FILE: test-fs-promises-writefile-typedarray.js
diff --git a/test/js/node/test/parallel/fs-promises-writefile-with-fd.test.js b/test/js/node/test/parallel/fs-promises-writefile-with-fd.test.js
deleted file mode 100644
index 17182bedb6..0000000000
--- a/test/js/node/test/parallel/fs-promises-writefile-with-fd.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-fs-promises-writefile-with-fd.js
-//#SHA1: 55be58e0edcbdc914795c46280459a85071f28eb
-//-----------------
-"use strict";
-
-// This test makes sure that `writeFile()` always writes from the current
-// position of the file, instead of truncating the file.
-
-const fs = require("fs");
-const fsPromises = require("fs").promises;
-const path = require("path");
-const os = require("os");
-
-let tmpdir;
-
-beforeEach(() => {
- tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "test-"));
-});
-
-afterEach(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test("writeFile() writes from current position", async () => {
- const fn = path.join(tmpdir, "test.txt");
-
- const handle = await fsPromises.open(fn, "w");
-
- /* Write only five bytes, so that the position moves to five. */
- const buf = Buffer.from("Hello");
- const { bytesWritten } = await handle.write(buf, 0, 5, null);
- expect(bytesWritten).toBe(5);
-
- /* Write some more with writeFile(). */
- await handle.writeFile("World");
-
- /* New content should be written at position five, instead of zero. */
- expect(fs.readFileSync(fn, "utf8")).toBe("HelloWorld");
-
- await handle.close();
-});
-
-//<#END_FILE: test-fs-promises-writefile-with-fd.js
diff --git a/test/js/node/test/parallel/fs-promisified.test.js b/test/js/node/test/parallel/fs-promisified.test.js
deleted file mode 100644
index 3df07cc98e..0000000000
--- a/test/js/node/test/parallel/fs-promisified.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-fs-promisified.js
-//#SHA1: 5366497c2a750295d2c5cf65c2938e27f573e8bb
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const { promisify } = require("util");
-
-const read = promisify(fs.read);
-const write = promisify(fs.write);
-const exists = promisify(fs.exists);
-
-test("promisified fs.read", async () => {
- const fd = fs.openSync(__filename, "r");
- const obj = await read(fd, Buffer.alloc(1024), 0, 1024, null);
- expect(typeof obj.bytesRead).toBe("number");
- expect(obj.buffer).toBeInstanceOf(Buffer);
- fs.closeSync(fd);
-});
-
-test("promisified fs.write", async () => {
- const tmpdir = require("../common/tmpdir");
- tmpdir.refresh();
- const filename = tmpdir.resolve("write-promise.txt");
- const fd = fs.openSync(filename, "w");
- const obj = await write(fd, Buffer.from("foobar"));
- expect(typeof obj.bytesWritten).toBe("number");
- expect(obj.buffer.toString()).toBe("foobar");
- fs.closeSync(fd);
-});
-
-test("promisified fs.exists", async () => {
- const result = await exists(__filename);
- expect(result).toBe(true);
-});
-
-//<#END_FILE: test-fs-promisified.js
diff --git a/test/js/node/test/parallel/fs-read-empty-buffer.test.js b/test/js/node/test/parallel/fs-read-empty-buffer.test.js
deleted file mode 100644
index 04fe94f967..0000000000
--- a/test/js/node/test/parallel/fs-read-empty-buffer.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-fs-read-empty-buffer.js
-//#SHA1: a2dc2c25e5a712b62c41298f885df24dd6106646
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-
-const filepath = path.resolve(__dirname, 'x.txt');
-let fd;
-
-beforeAll(() => {
- // Create a test file
- fs.writeFileSync(filepath, 'test content');
- fd = fs.openSync(filepath, 'r');
-});
-
-afterAll(() => {
- fs.closeSync(fd);
- fs.unlinkSync(filepath);
-});
-
-const buffer = new Uint8Array();
-
-test('fs.readSync throws ERR_INVALID_ARG_VALUE for empty buffer', () => {
- expect(() => fs.readSync(fd, buffer, 0, 10, 0)).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_VALUE',
- message: expect.stringContaining('The argument \'buffer\' is empty and cannot be written')
- }));
-});
-
-test('fs.read throws ERR_INVALID_ARG_VALUE for empty buffer', () => {
- expect(() => fs.read(fd, buffer, 0, 1, 0, () => {})).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_VALUE',
- message: expect.stringContaining('The argument \'buffer\' is empty and cannot be written')
- }));
-});
-
-test('fsPromises.filehandle.read rejects with ERR_INVALID_ARG_VALUE for empty buffer', async () => {
- const filehandle = await fs.promises.open(filepath, 'r');
- await expect(filehandle.read(buffer, 0, 1, 0)).rejects.toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_VALUE',
- message: expect.stringContaining('The argument \'buffer\' is empty and cannot be written')
- }));
- await filehandle.close();
-});
-
-//<#END_FILE: test-fs-read-empty-buffer.js
diff --git a/test/js/node/test/parallel/fs-read-file-sync-hostname.test.js b/test/js/node/test/parallel/fs-read-file-sync-hostname.test.js
deleted file mode 100644
index 9c4eb90ad8..0000000000
--- a/test/js/node/test/parallel/fs-read-file-sync-hostname.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-fs-read-file-sync-hostname.js
-//#SHA1: 6e8bd1a34277c7b98b985ba23843555b05f80ccb
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-
-if (process.platform !== "linux") {
- test.skip("Test is linux specific.", () => {});
-} else {
- test("reading /proc/sys/kernel/hostname", () => {
- // Test to make sure reading a file under the /proc directory works. See:
- // https://groups.google.com/forum/#!topic/nodejs-dev/rxZ_RoH1Gn0
- const hostname = fs.readFileSync("/proc/sys/kernel/hostname");
- expect(hostname.length).toBeGreaterThan(0);
- });
-}
-
-//<#END_FILE: test-fs-read-file-sync-hostname.js
diff --git a/test/js/node/test/parallel/fs-read-optional-params.test.js b/test/js/node/test/parallel/fs-read-optional-params.test.js
deleted file mode 100644
index 8abd08c20e..0000000000
--- a/test/js/node/test/parallel/fs-read-optional-params.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-//#FILE: test-fs-read-optional-params.js
-//#SHA1: daea619faa084927d87381fc60aedde3068a13ca
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const filepath = path.join(os.tmpdir(), "x.txt");
-const expected = Buffer.from("xyz\n");
-const defaultBufferAsync = Buffer.alloc(16384);
-const bufferAsOption = Buffer.allocUnsafe(expected.byteLength);
-
-beforeAll(() => {
- fs.writeFileSync(filepath, expected);
-});
-
-afterAll(() => {
- fs.unlinkSync(filepath);
-});
-
-function testValid(message, ...options) {
- test(`${message} (as params)`, async () => {
- const paramsFilehandle = fs.openSync(filepath, "r");
- await new Promise(resolve => {
- fs.read(paramsFilehandle, ...options, (err, bytesRead, buffer) => {
- expect(err).toBeNull();
- expect(bytesRead).toBe(expected.byteLength);
- expect(buffer.byteLength).toBe(defaultBufferAsync.byteLength);
- fs.closeSync(paramsFilehandle);
- resolve();
- });
- });
- });
-
- test(`${message} (as options)`, async () => {
- const optionsFilehandle = fs.openSync(filepath, "r");
- await new Promise(resolve => {
- fs.read(optionsFilehandle, bufferAsOption, ...options, (err, bytesRead, buffer) => {
- expect(err).toBeNull();
- expect(bytesRead).toBe(expected.byteLength);
- expect(buffer.byteLength).toBe(bufferAsOption.byteLength);
- fs.closeSync(optionsFilehandle);
- resolve();
- });
- });
- });
-}
-
-testValid("Not passing in any object");
-testValid("Passing in a null", null);
-testValid("Passing in an empty object", {});
-testValid("Passing in an object", {
- offset: 0,
- length: bufferAsOption.byteLength,
- position: 0,
-});
-
-//<#END_FILE: test-fs-read-optional-params.js
diff --git a/test/js/node/test/parallel/fs-read-promises-optional-params.test.js b/test/js/node/test/parallel/fs-read-promises-optional-params.test.js
deleted file mode 100644
index 60353b9226..0000000000
--- a/test/js/node/test/parallel/fs-read-promises-optional-params.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-fs-read-promises-optional-params.js
-//#SHA1: bc986664534329fd86b9aafd4c73a0159f71d388
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const { promisify } = require('util');
-const read = promisify(fs.read);
-
-const filepath = path.resolve(__dirname, 'x.txt');
-let fd;
-
-const expected = Buffer.from('xyz\n');
-const defaultBufferAsync = Buffer.alloc(16384);
-const bufferAsOption = Buffer.allocUnsafe(expected.byteLength);
-
-beforeAll(() => {
- // Create the test file
- fs.writeFileSync(filepath, expected);
- fd = fs.openSync(filepath, 'r');
-});
-
-afterAll(() => {
- fs.closeSync(fd);
- fs.unlinkSync(filepath);
-});
-
-test('read with empty options object', async () => {
- const { bytesRead, buffer } = await read(fd, {});
- expect(bytesRead).toBe(expected.byteLength);
- expect(buffer.byteLength).toBe(defaultBufferAsync.byteLength);
-});
-
-test('read with buffer and position options', async () => {
- const { bytesRead, buffer } = await read(fd, bufferAsOption, { position: 0 });
- expect(bytesRead).toBe(expected.byteLength);
- expect(buffer.byteLength).toBe(bufferAsOption.byteLength);
-});
-
-//<#END_FILE: test-fs-read-promises-optional-params.js
diff --git a/test/js/node/test/parallel/fs-read-stream-autoclose.test.js b/test/js/node/test/parallel/fs-read-stream-autoclose.test.js
deleted file mode 100644
index 36ab013cd8..0000000000
--- a/test/js/node/test/parallel/fs-read-stream-autoclose.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-fs-read-stream-autoClose.js
-//#SHA1: 0fbd57ecd5ae02143036c03cdca120bc7c3deea1
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const writeFile = path.join(os.tmpdir(), "write-autoClose.txt");
-
-beforeEach(() => {
- // Clean up the temporary directory
- try {
- fs.unlinkSync(writeFile);
- } catch (err) {
- // Ignore errors if file doesn't exist
- }
-});
-
-test("fs.createWriteStream with autoClose option", done => {
- const file = fs.createWriteStream(writeFile, { autoClose: true });
-
- file.on("finish", () => {
- expect(file.destroyed).toBe(false);
- done();
- });
-
- file.end("asd");
-});
-
-//<#END_FILE: test-fs-read-stream-autoClose.js
diff --git a/test/js/node/test/parallel/fs-read-stream-double-close.test.js b/test/js/node/test/parallel/fs-read-stream-double-close.test.js
deleted file mode 100644
index 73603d1f1c..0000000000
--- a/test/js/node/test/parallel/fs-read-stream-double-close.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-fs-read-stream-double-close.js
-//#SHA1: 066b117ee2b44bedfdce77d06389406b2474eb2f
-//-----------------
-'use strict';
-
-const fs = require('fs');
-
-test('double close on ReadStream', (done) => {
- const s = fs.createReadStream(__filename);
-
- let closeCount = 0;
- const checkClose = () => {
- closeCount++;
- if (closeCount === 2) {
- done();
- }
- };
-
- s.close(checkClose);
- s.close(checkClose);
-});
-
-test('double destroy on ReadStream', (done) => {
- const s = fs.createReadStream(__filename);
-
- let destroyCount = 0;
- const checkDestroy = () => {
- destroyCount++;
- if (destroyCount === 2) {
- done();
- }
- };
-
- // This is a private API, but it is worth testing. close calls this
- s.destroy(null, checkDestroy);
- s.destroy(null, checkDestroy);
-});
-
-//<#END_FILE: test-fs-read-stream-double-close.js
diff --git a/test/js/node/test/parallel/fs-read-stream-fd-leak.test.js b/test/js/node/test/parallel/fs-read-stream-fd-leak.test.js
deleted file mode 100644
index 5c4e0dd55b..0000000000
--- a/test/js/node/test/parallel/fs-read-stream-fd-leak.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-//#FILE: test-fs-read-stream-fd-leak.js
-//#SHA1: fc07b42f524d6a2f9743a5a7665c92096f58505b
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-
-let openCount = 0;
-const _fsopen = fs.open;
-const _fsclose = fs.close;
-
-const loopCount = 50;
-const totalCheck = 50;
-const emptyTxt = path.join(__dirname, "../fixtures/empty.txt");
-
-fs.open = function () {
- openCount++;
- return _fsopen.apply(null, arguments);
-};
-
-fs.close = function () {
- openCount--;
- return _fsclose.apply(null, arguments);
-};
-
-function testLeak(endFn) {
- return new Promise(resolve => {
- console.log(`testing for leaks from fs.createReadStream().${endFn}()...`);
-
- let i = 0;
- let check = 0;
-
- function checkFunction() {
- if (openCount !== 0 && check < totalCheck) {
- check++;
- setTimeout(checkFunction, 100);
- return;
- }
-
- expect(openCount).toBe(0);
- openCount = 0;
- resolve();
- }
-
- const interval = setInterval(() => {
- const s = fs.createReadStream(emptyTxt);
- s[endFn]();
-
- if (++i === loopCount) {
- clearInterval(interval);
- setTimeout(checkFunction, 100);
- }
- }, 2);
- });
-}
-
-test("no leaked file descriptors using close()", async () => {
- await testLeak("close");
-}, 10000);
-
-test("no leaked file descriptors using destroy()", async () => {
- await testLeak("destroy");
-}, 10000);
-
-//<#END_FILE: test-fs-read-stream-fd-leak.js
diff --git a/test/js/node/test/parallel/fs-read-stream-pos.test.js b/test/js/node/test/parallel/fs-read-stream-pos.test.js
deleted file mode 100644
index bdc551a7c1..0000000000
--- a/test/js/node/test/parallel/fs-read-stream-pos.test.js
+++ /dev/null
@@ -1,103 +0,0 @@
-//#FILE: test-fs-read-stream-pos.js
-//#SHA1: e44b357d8045cfa1e8129a160254dcfb9225d990
-//-----------------
-"use strict";
-
-// Refs: https://github.com/nodejs/node/issues/33940
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const tmpdir = {
- refresh: () => {
- // Implement tmpdir.refresh() if needed
- },
- resolve: filename => path.join(os.tmpdir(), filename),
-};
-
-tmpdir.refresh();
-
-const file = tmpdir.resolve("read_stream_pos_test.txt");
-
-fs.writeFileSync(file, "");
-
-let counter = 0;
-
-const writeInterval = setInterval(() => {
- counter = counter + 1;
- const line = `hello at ${counter}\n`;
- fs.writeFileSync(file, line, { flag: "a" });
-}, 1);
-
-const hwm = 10;
-let bufs = [];
-let isLow = false;
-let cur = 0;
-let stream;
-
-const readInterval = setInterval(() => {
- if (stream) return;
-
- stream = fs.createReadStream(file, {
- highWaterMark: hwm,
- start: cur,
- });
- stream.on(
- "data",
- jest.fn(chunk => {
- cur += chunk.length;
- bufs.push(chunk);
- if (isLow) {
- const brokenLines = Buffer.concat(bufs)
- .toString()
- .split("\n")
- .filter(line => {
- const s = "hello at".slice(0, line.length);
- if (line && !line.startsWith(s)) {
- return true;
- }
- return false;
- });
- expect(brokenLines.length).toBe(0);
- exitTest();
- return;
- }
- if (chunk.length !== hwm) {
- isLow = true;
- }
- }),
- );
- stream.on("end", () => {
- stream = null;
- isLow = false;
- bufs = [];
- });
-}, 10);
-
-// Time longer than 90 seconds to exit safely
-const endTimer = setTimeout(() => {
- exitTest();
-}, 90000);
-
-const exitTest = () => {
- clearInterval(readInterval);
- clearInterval(writeInterval);
- clearTimeout(endTimer);
- if (stream && !stream.destroyed) {
- stream.on("close", () => {
- process.exit();
- });
- stream.destroy();
- } else {
- process.exit();
- }
-};
-
-test("fs read stream position", () => {
- // This test is mostly about setting up the environment and running the intervals
- // The actual assertions are made within the intervals
- expect(true).toBe(true);
-});
-
-//<#END_FILE: test-fs-read-stream-pos.js
diff --git a/test/js/node/test/parallel/fs-readdir-buffer.test.js b/test/js/node/test/parallel/fs-readdir-buffer.test.js
deleted file mode 100644
index 4003405487..0000000000
--- a/test/js/node/test/parallel/fs-readdir-buffer.test.js
+++ /dev/null
@@ -1,23 +0,0 @@
-//#FILE: test-fs-readdir-buffer.js
-//#SHA1: 333645cb13aa3c15d61428ecfa2794e7393ef91c
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-if (process.platform !== "darwin") {
- it("skips test on non-MacOS platforms", () => {
- test.skip("this test works only on MacOS");
- });
-} else {
- test("readdir with buffer and withFileTypes options on MacOS", () => {
- return new Promise(resolve => {
- fs.readdir(Buffer.from("/dev"), { withFileTypes: true, encoding: "buffer" }, (err, files) => {
- expect(err).toBeNull();
- resolve();
- });
- });
- });
-}
-
-//<#END_FILE: test-fs-readdir-buffer.js
diff --git a/test/js/node/test/parallel/fs-readdir-recursive.test.js b/test/js/node/test/parallel/fs-readdir-recursive.test.js
deleted file mode 100644
index 32c284e827..0000000000
--- a/test/js/node/test/parallel/fs-readdir-recursive.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-fs-readdir-recursive.js
-//#SHA1: daa6ac8e46cd3d530e4546354a11f87f1b1c092d
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const net = require("net");
-const path = require("path");
-const os = require("os");
-
-const tmpdir = path.join(os.tmpdir(), "node-test-fs-readdir-recursive");
-
-beforeAll(() => {
- // Refresh tmpdir
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- // Clean up tmpdir
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test("fs.readdirSync with recursive option should not crash", done => {
- const server = net.createServer().listen(path.join(tmpdir, "test.sock"), () => {
- // The process should not crash
- // See https://github.com/nodejs/node/issues/52159
- expect(() => {
- fs.readdirSync(tmpdir, { recursive: true });
- }).not.toThrow();
-
- server.close();
- done();
- });
-});
-
-//<#END_FILE: test-fs-readdir-recursive.js
diff --git a/test/js/node/test/parallel/fs-readdir.test.js b/test/js/node/test/parallel/fs-readdir.test.js
deleted file mode 100644
index 1e98f2f1b6..0000000000
--- a/test/js/node/test/parallel/fs-readdir.test.js
+++ /dev/null
@@ -1,90 +0,0 @@
-//#FILE: test-fs-readdir.js
-//#SHA1: ce2c5a12cb271c5023f965afe712e78b1a484ad5
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const readdirDir = path.join(os.tmpdir(), "test-fs-readdir");
-const files = ["empty", "files", "for", "just", "testing"];
-
-beforeAll(() => {
- // Make sure tmp directory is clean
- if (fs.existsSync(readdirDir)) {
- fs.rmSync(readdirDir, { recursive: true, force: true });
- }
- fs.mkdirSync(readdirDir, { recursive: true });
-
- // Create the necessary files
- files.forEach(currentFile => {
- fs.closeSync(fs.openSync(path.join(readdirDir, currentFile), "w"));
- });
-});
-
-afterAll(() => {
- // Clean up
- fs.rmSync(readdirDir, { recursive: true, force: true });
-});
-
-test("fs.readdirSync returns correct files", () => {
- expect(fs.readdirSync(readdirDir).sort()).toEqual(files);
-});
-
-test("fs.readdir returns correct files", async () => {
- await new Promise(resolve => {
- fs.readdir(readdirDir, (err, f) => {
- expect(err).toBeNull();
- expect(f.sort()).toEqual(files);
- resolve();
- });
- });
-});
-
-test("fs.readdirSync throws ENOTDIR on file", () => {
- expect(() => {
- fs.readdirSync(__filename);
- }).toThrow(
- expect.objectContaining({
- code: "ENOTDIR",
- message: expect.any(String),
- }),
- );
-});
-
-test("fs.readdir throws ENOTDIR on file", async () => {
- await new Promise(resolve => {
- fs.readdir(__filename, e => {
- expect(e).toEqual(
- expect.objectContaining({
- code: "ENOTDIR",
- message: expect.any(String),
- }),
- );
- resolve();
- });
- });
-});
-
-test("fs.readdir and fs.readdirSync throw on invalid input", () => {
- [false, 1, [], {}, null, undefined].forEach(i => {
- expect(() => fs.readdir(i, () => {})).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-
- expect(() => fs.readdirSync(i)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-fs-readdir.js
diff --git a/test/js/node/test/parallel/fs-readfile-empty.test.js b/test/js/node/test/parallel/fs-readfile-empty.test.js
deleted file mode 100644
index ae4bdb4eb5..0000000000
--- a/test/js/node/test/parallel/fs-readfile-empty.test.js
+++ /dev/null
@@ -1,67 +0,0 @@
-//#FILE: test-fs-readfile-empty.js
-//#SHA1: a78ffc8186bc3e0a7d8d8dcf0f292ef4220817a5
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-
-const fixturesPath = path.join(__dirname, '..', 'fixtures');
-const fn = path.join(fixturesPath, 'empty.txt');
-
-test('fs.readFile on an empty file', (done) => {
- fs.readFile(fn, (err, data) => {
- expect(err).toBeNull();
- expect(data).toBeTruthy();
- done();
- });
-});
-
-test('fs.readFile on an empty file with utf8 encoding', (done) => {
- fs.readFile(fn, 'utf8', (err, data) => {
- expect(err).toBeNull();
- expect(data).toBe('');
- done();
- });
-});
-
-test('fs.readFile on an empty file with encoding option', (done) => {
- fs.readFile(fn, { encoding: 'utf8' }, (err, data) => {
- expect(err).toBeNull();
- expect(data).toBe('');
- done();
- });
-});
-
-test('fs.readFileSync on an empty file', () => {
- const data = fs.readFileSync(fn);
- expect(data).toBeTruthy();
-});
-
-test('fs.readFileSync on an empty file with utf8 encoding', () => {
- const data = fs.readFileSync(fn, 'utf8');
- expect(data).toBe('');
-});
-
-//<#END_FILE: test-fs-readfile-empty.js
diff --git a/test/js/node/test/parallel/fs-readfile-eof.test.js b/test/js/node/test/parallel/fs-readfile-eof.test.js
deleted file mode 100644
index f1b68ffccf..0000000000
--- a/test/js/node/test/parallel/fs-readfile-eof.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-fs-readfile-eof.js
-//#SHA1: 89b7efe6c30d2316249bfae1d01f16f97e32be04
-//-----------------
-"use strict";
-
-const fs = require("fs/promises");
-const { exec } = require("child_process");
-
-const childType = ["child-encoding", "child-non-encoding"];
-
-if (process.argv[2] === childType[0]) {
- fs.readFile("/dev/stdin", "utf8").then(data => {
- process.stdout.write(data);
- });
-} else if (process.argv[2] === childType[1]) {
- fs.readFile("/dev/stdin").then(data => {
- process.stdout.write(data);
- });
-} else {
- const data1 = "Hello";
- const data2 = "World";
- const expected = `${data1}\n${data2}\n`;
-
- const f = JSON.stringify(__filename);
- const node = JSON.stringify(process.execPath);
-
- function testReadFile(child) {
- return new Promise((resolve, reject) => {
- const cmd = `(echo ${data1}; sleep 0.5; echo ${data2}) | ${node} ${f} ${child}`;
- exec(cmd, (error, stdout, stderr) => {
- if (error) reject(error);
- else resolve({ stdout, stderr });
- });
- });
- }
-
- if (process.platform === "win32" || process.platform === "aix" || process.platform === "os400") {
- test.skip(`No /dev/stdin on ${process.platform}.`, () => {});
- } else {
- test("readFile with encoding", async () => {
- const { stdout, stderr } = await testReadFile(childType[0]);
- expect(stdout).toBe(expected);
- expect(stderr).toBe("");
- });
-
- test("readFile without encoding", async () => {
- const { stdout, stderr } = await testReadFile(childType[1]);
- expect(stdout).toBe(expected);
- expect(stderr).toBe("");
- });
- }
-}
-
-//<#END_FILE: test-fs-readfile-eof.js
diff --git a/test/js/node/test/parallel/fs-readfile-fd.test.js b/test/js/node/test/parallel/fs-readfile-fd.test.js
deleted file mode 100644
index b62d15b9e6..0000000000
--- a/test/js/node/test/parallel/fs-readfile-fd.test.js
+++ /dev/null
@@ -1,111 +0,0 @@
-//#FILE: test-fs-readfile-fd.js
-//#SHA1: ec2bc78cb0bab7b8e9b23c1c44a77b227294d8b4
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-readfile-fd');
-const emptyFilePath = path.join(tmpdir, 'empty.txt');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- fs.writeFileSync(emptyFilePath, '');
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-function tempFd(callback) {
- fs.open(emptyFilePath, 'r', (err, fd) => {
- expect(err).toBeFalsy();
- callback(fd, () => {
- fs.close(fd, (err) => {
- expect(err).toBeFalsy();
- });
- });
- });
-}
-
-function tempFdSync(callback) {
- const fd = fs.openSync(emptyFilePath, 'r');
- callback(fd);
- fs.closeSync(fd);
-}
-
-test('fs.readFile with file descriptor', (done) => {
- tempFd((fd, close) => {
- fs.readFile(fd, (err, data) => {
- expect(data).toBeTruthy();
- close();
- done();
- });
- });
-});
-
-test('fs.readFile with file descriptor and utf8 encoding', (done) => {
- tempFd((fd, close) => {
- fs.readFile(fd, 'utf8', (err, data) => {
- expect(data).toBe('');
- close();
- done();
- });
- });
-});
-
-test('fs.readFileSync with file descriptor', () => {
- tempFdSync((fd) => {
- expect(fs.readFileSync(fd)).toBeTruthy();
- });
-});
-
-test('fs.readFileSync with file descriptor and utf8 encoding', () => {
- tempFdSync((fd) => {
- expect(fs.readFileSync(fd, 'utf8')).toBe('');
- });
-});
-
-test('readFile() reads from current position of file descriptor', (done) => {
- const filename = path.join(tmpdir, 'test.txt');
- fs.writeFileSync(filename, 'Hello World');
-
- fs.open(filename, 'r', (err, fd) => {
- expect(err).toBeFalsy();
- const buf = Buffer.alloc(5);
-
- fs.read(fd, buf, 0, 5, null, (err, bytes) => {
- expect(err).toBeFalsy();
- expect(bytes).toBe(5);
- expect(buf.toString()).toBe('Hello');
-
- fs.readFile(fd, (err, data) => {
- expect(err).toBeFalsy();
- expect(data.toString()).toBe(' World');
- fs.closeSync(fd);
- done();
- });
- });
- });
-});
-
-test('readFileSync() reads from current position of file descriptor', () => {
- const filename = path.join(tmpdir, 'test.txt');
- fs.writeFileSync(filename, 'Hello World');
-
- const fd = fs.openSync(filename, 'r');
-
- const buf = Buffer.alloc(5);
- expect(fs.readSync(fd, buf, 0, 5)).toBe(5);
- expect(buf.toString()).toBe('Hello');
-
- expect(fs.readFileSync(fd).toString()).toBe(' World');
-
- fs.closeSync(fd);
-});
-
-//<#END_FILE: test-fs-readfile-fd.js
diff --git a/test/js/node/test/parallel/fs-readfile-pipe-large.test.js b/test/js/node/test/parallel/fs-readfile-pipe-large.test.js
deleted file mode 100644
index 815db4cedd..0000000000
--- a/test/js/node/test/parallel/fs-readfile-pipe-large.test.js
+++ /dev/null
@@ -1,68 +0,0 @@
-//#FILE: test-fs-readfile-pipe-large.js
-//#SHA1: 5e2fa068dc742cfe617ccf3f08df6725e92a51f6
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const { exec } = require('child_process');
-const os = require('os');
-
-const isWindows = process.platform === 'win32';
-const isAIX = process.platform === 'aix';
-const isIBMi = process.platform === 'os400';
-
-const skipPlatforms = ['win32', 'aix', 'os400'];
-
-// Separate child process logic
-if (process.argv[2] === 'child') {
- fs.readFile('/dev/stdin', (err, data) => {
- if (err) {
- console.error(err);
- process.exit(1);
- }
- process.stdout.write(data);
- });
-} else {
- // Jest test code
- describe('fs.readFile pipe large', () => {
- const tmpdir = os.tmpdir();
- const filename = path.join(tmpdir, 'readfile_pipe_large_test.txt');
- const dataExpected = 'a'.repeat(999999);
-
- beforeAll(() => {
- if (!skipPlatforms.includes(process.platform)) {
- fs.writeFileSync(filename, dataExpected);
- }
- });
-
- afterAll(() => {
- if (!skipPlatforms.includes(process.platform)) {
- fs.unlinkSync(filename);
- }
- });
-
- test('should read from /dev/stdin and write to stdout', () => {
- if (skipPlatforms.includes(process.platform)) {
- return test.skip(`No /dev/stdin on ${process.platform}.`);
- }
-
- const f = JSON.stringify(__filename);
- const node = JSON.stringify(process.execPath);
- const cmd = `cat ${filename} | ${node} ${f} child`;
-
- return new Promise((resolve, reject) => {
- exec(cmd, { maxBuffer: 1000000 }, (error, stdout, stderr) => {
- if (error) {
- reject(error);
- return;
- }
-
- expect(stdout).toBe(dataExpected);
- expect(stderr).toBe('');
- resolve();
- });
- });
- });
- });
-}
-//<#END_FILE: test-fs-readfile-pipe-large.js
diff --git a/test/js/node/test/parallel/fs-readfile-pipe.test.js b/test/js/node/test/parallel/fs-readfile-pipe.test.js
deleted file mode 100644
index 9d9cec5cb7..0000000000
--- a/test/js/node/test/parallel/fs-readfile-pipe.test.js
+++ /dev/null
@@ -1,52 +0,0 @@
-//#FILE: test-fs-readfile-pipe.js
-//#SHA1: b78e6ea1bbcdaf74b6363f4740bdf2393ed28938
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const { exec } = require('child_process');
-
-const isWindows = process.platform === 'win32';
-const isAIX = process.platform === 'aix';
-const isIBMi = process.platform === 'os400';
-
-const fixturesPath = path.join(__dirname, '..', 'fixtures');
-
-if (isWindows || isAIX || isIBMi) {
- test.skip(`No /dev/stdin on ${process.platform}.`, () => {});
-} else {
- if (process.argv[2] === 'child') {
- fs.readFile('/dev/stdin', (err, data) => {
- if (err) {
- console.error(err);
- process.exit(1);
- }
- process.stdout.write(data);
- });
- } else {
- test('readFile pipe test', (done) => {
- const filename = path.join(fixturesPath, 'readfile_pipe_test.txt');
- const dataExpected = fs.readFileSync(filename, 'utf8');
-
- const f = JSON.stringify(__filename);
- const node = JSON.stringify(process.execPath);
- const cmd = `cat ${filename} | ${node} ${f} child`;
-
- exec(cmd, (error, stdout, stderr) => {
- if (error) {
- done(error);
- return;
- }
- try {
- expect(stdout).toBe(dataExpected);
- expect(stderr).toBe('');
- done();
- } catch (error) {
- done(error);
- }
- });
- }, 10000); // Increase timeout to 10 seconds
- }
-}
-
-//<#END_FILE: test-fs-readfile-pipe.js
diff --git a/test/js/node/test/parallel/fs-readfile-unlink.test.js b/test/js/node/test/parallel/fs-readfile-unlink.test.js
deleted file mode 100644
index 85475f6488..0000000000
--- a/test/js/node/test/parallel/fs-readfile-unlink.test.js
+++ /dev/null
@@ -1,52 +0,0 @@
-//#FILE: test-fs-readfile-unlink.js
-//#SHA1: a7107747d7901dfcc1ffd0e7adbf548412a1016a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// Test that unlink succeeds immediately after readFile completes.
-
-test("unlink succeeds immediately after readFile completes", async () => {
- const tmpdir = path.join(os.tmpdir(), "node-test-fs-readfile-unlink");
- await fs.promises.mkdir(tmpdir, { recursive: true });
-
- const fileName = path.join(tmpdir, "test.bin");
- const buf = Buffer.alloc(512 * 1024, 42);
-
- await fs.promises.writeFile(fileName, buf);
-
- const data = await fs.promises.readFile(fileName);
-
- expect(data.length).toBe(buf.length);
- expect(data[0]).toBe(42);
-
- // Unlink should not throw. This is part of the test. It used to throw on
- // Windows due to a bug.
- await expect(fs.promises.unlink(fileName)).resolves.toBeUndefined();
-});
-
-//<#END_FILE: test-fs-readfile-unlink.js
diff --git a/test/js/node/test/parallel/fs-readfile-zero-byte-liar.test.js b/test/js/node/test/parallel/fs-readfile-zero-byte-liar.test.js
deleted file mode 100644
index 0e3799ec0e..0000000000
--- a/test/js/node/test/parallel/fs-readfile-zero-byte-liar.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-fs-readfile-zero-byte-liar.js
-//#SHA1: ddca2f114cf32b03f36405a21c81058e7a1f0c18
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const fs = require("fs");
-
-// Test that readFile works even when stat returns size 0.
-
-const dataExpected = fs.readFileSync(__filename, "utf8");
-
-// Sometimes stat returns size=0, but it's a lie.
-fs._fstat = fs.fstat;
-fs._fstatSync = fs.fstatSync;
-
-fs.fstat = (fd, cb) => {
- fs._fstat(fd, (er, st) => {
- if (er) return cb(er);
- st.size = 0;
- return cb(er, st);
- });
-};
-
-fs.fstatSync = fd => {
- const st = fs._fstatSync(fd);
- st.size = 0;
- return st;
-};
-
-test("readFileSync works with zero byte liar", () => {
- const d = fs.readFileSync(__filename, "utf8");
- expect(d).toBe(dataExpected);
-});
-
-test("readFile works with zero byte liar", async () => {
- const d = await fs.promises.readFile(__filename, "utf8");
- expect(d).toBe(dataExpected);
-});
-
-//<#END_FILE: test-fs-readfile-zero-byte-liar.js
diff --git a/test/js/node/test/parallel/fs-readfilesync-pipe-large.test.js b/test/js/node/test/parallel/fs-readfilesync-pipe-large.test.js
deleted file mode 100644
index 8df6c2e1f0..0000000000
--- a/test/js/node/test/parallel/fs-readfilesync-pipe-large.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-//#FILE: test-fs-readfilesync-pipe-large.js
-//#SHA1: 669e419b344b375a028fa352c7a29eec2d5d52af
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const { exec } = require('child_process');
-const os = require('os');
-const { describe, test, expect, beforeAll, afterAll } = require('@jest/globals');
-
-const isWindows = process.platform === 'win32';
-const isAIX = process.platform === 'aix';
-const isIBMi = process.platform === 'os400';
-
-const shouldSkip = isWindows || isAIX || isIBMi;
-
-const tmpdir = os.tmpdir();
-
-if (process.argv[2] === 'child') {
- process.stdout.write(fs.readFileSync('/dev/stdin', 'utf8'));
- process.exit(0);
-}
-
-describe('fs.readFileSync pipe large', () => {
- const filename = path.join(tmpdir, 'readfilesync_pipe_large_test.txt');
- const dataExpected = 'a'.repeat(999999);
-
- beforeAll(() => {
- if (!shouldSkip) {
- fs.writeFileSync(filename, dataExpected);
- }
- });
-
- afterAll(() => {
- if (!shouldSkip) {
- fs.unlinkSync(filename);
- }
- });
-
- const testFn = shouldSkip ? test.skip : test;
-
- testFn('should read large file through pipe', (done) => {
- const childScriptPath = path.join(__dirname, 'child-script.js');
- fs.writeFileSync(childScriptPath, `
- const fs = require('fs');
- process.stdout.write(fs.readFileSync('/dev/stdin', 'utf8'));
- `);
-
- const cmd = `cat ${filename} | "${process.execPath}" "${childScriptPath}"`;
-
- exec(cmd, { maxBuffer: 1000000 }, (error, stdout, stderr) => {
- try {
- expect(error).toBeNull();
- expect(stdout).toBe(dataExpected);
- expect(stderr).toBe('');
- fs.unlinkSync(childScriptPath);
- done();
- } catch (err) {
- fs.unlinkSync(childScriptPath);
- done(err);
- }
- });
- }, 30000); // Increase timeout to 30 seconds
-});
-
-//<#END_FILE: test-fs-readfilesync-pipe-large.js
diff --git a/test/js/node/test/parallel/fs-readlink-type-check.test.js b/test/js/node/test/parallel/fs-readlink-type-check.test.js
deleted file mode 100644
index c0ee6e8b00..0000000000
--- a/test/js/node/test/parallel/fs-readlink-type-check.test.js
+++ /dev/null
@@ -1,30 +0,0 @@
-//#FILE: test-fs-readlink-type-check.js
-//#SHA1: dd36bda8e12e6c22c342325345dd8d1de2097d9c
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-[false, 1, {}, [], null, undefined].forEach(i => {
- test(`fs.readlink throws for invalid input: ${JSON.stringify(i)}`, () => {
- expect(() => fs.readlink(i, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-
- test(`fs.readlinkSync throws for invalid input: ${JSON.stringify(i)}`, () => {
- expect(() => fs.readlinkSync(i)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-fs-readlink-type-check.js
diff --git a/test/js/node/test/parallel/fs-readv-promises.test.js b/test/js/node/test/parallel/fs-readv-promises.test.js
deleted file mode 100644
index ff66cc9354..0000000000
--- a/test/js/node/test/parallel/fs-readv-promises.test.js
+++ /dev/null
@@ -1,69 +0,0 @@
-//#FILE: test-fs-readv-promises.js
-//#SHA1: 43d801fa8a2eabf438e98f5aa713eb9680fe798b
-//-----------------
-"use strict";
-
-const fs = require("fs").promises;
-const path = require("path");
-const os = require("os");
-
-const expected = "ümlaut. Лорем 運務ホソモ指及 आपको करने विकास 紙読決多密所 أضف";
-const expectedBuff = Buffer.from(expected);
-
-let cnt = 0;
-function getFileName() {
- return path.join(os.tmpdir(), `readv_promises_${++cnt}.txt`);
-}
-
-const allocateEmptyBuffers = combinedLength => {
- const bufferArr = [];
- // Allocate two buffers, each half the size of expectedBuff
- bufferArr[0] = Buffer.alloc(Math.floor(combinedLength / 2));
- bufferArr[1] = Buffer.alloc(combinedLength - bufferArr[0].length);
-
- return bufferArr;
-};
-
-describe("fs.promises.readv", () => {
- beforeEach(() => {
- cnt = 0;
- });
-
- test("readv with position", async () => {
- const filename = getFileName();
- await fs.writeFile(filename, expectedBuff);
- const handle = await fs.open(filename, "r");
- const bufferArr = allocateEmptyBuffers(expectedBuff.length);
- const expectedLength = expectedBuff.length;
-
- let { bytesRead, buffers } = await handle.readv([Buffer.from("")], null);
- expect(bytesRead).toBe(0);
- expect(buffers).toEqual([Buffer.from("")]);
-
- ({ bytesRead, buffers } = await handle.readv(bufferArr, null));
- expect(bytesRead).toBe(expectedLength);
- expect(buffers).toEqual(bufferArr);
- expect(Buffer.concat(bufferArr)).toEqual(await fs.readFile(filename));
- await handle.close();
- });
-
- test("readv without position", async () => {
- const filename = getFileName();
- await fs.writeFile(filename, expectedBuff);
- const handle = await fs.open(filename, "r");
- const bufferArr = allocateEmptyBuffers(expectedBuff.length);
- const expectedLength = expectedBuff.length;
-
- let { bytesRead, buffers } = await handle.readv([Buffer.from("")]);
- expect(bytesRead).toBe(0);
- expect(buffers).toEqual([Buffer.from("")]);
-
- ({ bytesRead, buffers } = await handle.readv(bufferArr));
- expect(bytesRead).toBe(expectedLength);
- expect(buffers).toEqual(bufferArr);
- expect(Buffer.concat(bufferArr)).toEqual(await fs.readFile(filename));
- await handle.close();
- });
-});
-
-//<#END_FILE: test-fs-readv-promises.js
diff --git a/test/js/node/test/parallel/fs-readv-sync.test.js b/test/js/node/test/parallel/fs-readv-sync.test.js
deleted file mode 100644
index f4ab916f05..0000000000
--- a/test/js/node/test/parallel/fs-readv-sync.test.js
+++ /dev/null
@@ -1,104 +0,0 @@
-//#FILE: test-fs-readv-sync.js
-//#SHA1: e9a4527b118e4a814a04c976eaafb5127f7c7c9d
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const expected = "ümlaut. Лорем 運務ホソモ指及 आपको करने विकास 紙読決多密所 أضف";
-
-const exptectedBuff = Buffer.from(expected);
-const expectedLength = exptectedBuff.length;
-
-let filename;
-let tmpdir;
-
-beforeAll(() => {
- tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "test-fs-readv-sync-"));
- filename = path.join(tmpdir, "readv_sync.txt");
- fs.writeFileSync(filename, exptectedBuff);
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-const allocateEmptyBuffers = combinedLength => {
- const bufferArr = [];
- // Allocate two buffers, each half the size of exptectedBuff
- bufferArr[0] = Buffer.alloc(Math.floor(combinedLength / 2));
- bufferArr[1] = Buffer.alloc(combinedLength - bufferArr[0].length);
-
- return bufferArr;
-};
-
-// fs.readvSync with array of buffers with all parameters
-test("fs.readvSync with array of buffers with all parameters", () => {
- const fd = fs.openSync(filename, "r");
-
- const bufferArr = allocateEmptyBuffers(exptectedBuff.length);
-
- let read = fs.readvSync(fd, [Buffer.from("")], 0);
- expect(read).toBe(0);
-
- read = fs.readvSync(fd, bufferArr, 0);
- expect(read).toBe(expectedLength);
-
- fs.closeSync(fd);
-
- expect(Buffer.concat(bufferArr)).toEqual(fs.readFileSync(filename));
-});
-
-// fs.readvSync with array of buffers without position
-test("fs.readvSync with array of buffers without position", () => {
- const fd = fs.openSync(filename, "r");
-
- const bufferArr = allocateEmptyBuffers(exptectedBuff.length);
-
- let read = fs.readvSync(fd, [Buffer.from("")]);
- expect(read).toBe(0);
-
- read = fs.readvSync(fd, bufferArr);
- expect(read).toBe(expectedLength);
-
- fs.closeSync(fd);
-
- expect(Buffer.concat(bufferArr)).toEqual(fs.readFileSync(filename));
-});
-
-/**
- * Testing with incorrect arguments
- */
-const wrongInputs = [false, "test", {}, [{}], ["sdf"], null, undefined];
-
-test("fs.readvSync with incorrect arguments", () => {
- const fd = fs.openSync(filename, "r");
-
- for (const wrongInput of wrongInputs) {
- expect(() => fs.readvSync(fd, wrongInput, null)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- }
-
- fs.closeSync(fd);
-});
-
-test("fs.readvSync with wrong fd argument", () => {
- for (const wrongInput of wrongInputs) {
- expect(() => fs.readvSync(wrongInput)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- }
-});
-
-//<#END_FILE: test-fs-readv-sync.js
diff --git a/test/js/node/test/parallel/fs-readv.test.js b/test/js/node/test/parallel/fs-readv.test.js
deleted file mode 100644
index 58f9977c3b..0000000000
--- a/test/js/node/test/parallel/fs-readv.test.js
+++ /dev/null
@@ -1,110 +0,0 @@
-//#FILE: test-fs-readv.js
-//#SHA1: 07d6fe434017163aea491c98db8127bc2c942b96
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const expected = "ümlaut. Лорем 運務ホソモ指及 आपको करने विकास 紙読決多密所 أضف";
-
-let cnt = 0;
-const getFileName = () => path.join(os.tmpdir(), `readv_${++cnt}.txt`);
-const expectedBuff = Buffer.from(expected);
-
-const allocateEmptyBuffers = combinedLength => {
- const bufferArr = [];
- // Allocate two buffers, each half the size of expectedBuff
- bufferArr[0] = Buffer.alloc(Math.floor(combinedLength / 2));
- bufferArr[1] = Buffer.alloc(combinedLength - bufferArr[0].length);
-
- return bufferArr;
-};
-
-const getCallback = (fd, bufferArr) => {
- return (err, bytesRead, buffers) => {
- expect(err).toBeNull();
- expect(bufferArr).toEqual(buffers);
- const expectedLength = expectedBuff.length;
- expect(bytesRead).toBe(expectedLength);
- fs.closeSync(fd);
-
- expect(Buffer.concat(bufferArr).equals(expectedBuff)).toBe(true);
- };
-};
-
-beforeEach(() => {
- jest.spyOn(fs, "writeSync");
- jest.spyOn(fs, "writeFileSync");
- jest.spyOn(fs, "openSync");
- jest.spyOn(fs, "closeSync");
-});
-
-afterEach(() => {
- jest.restoreAllMocks();
-});
-
-test("fs.readv with array of buffers with all parameters", done => {
- const filename = getFileName();
- const fd = fs.openSync(filename, "w+");
- fs.writeSync(fd, expectedBuff);
-
- const bufferArr = allocateEmptyBuffers(expectedBuff.length);
- const callback = getCallback(fd, bufferArr);
-
- fs.readv(fd, bufferArr, 0, (err, bytesRead, buffers) => {
- callback(err, bytesRead, buffers);
- done();
- });
-});
-
-test("fs.readv with array of buffers without position", done => {
- const filename = getFileName();
- fs.writeFileSync(filename, expectedBuff);
- const fd = fs.openSync(filename, "r");
-
- const bufferArr = allocateEmptyBuffers(expectedBuff.length);
- const callback = getCallback(fd, bufferArr);
-
- fs.readv(fd, bufferArr, (err, bytesRead, buffers) => {
- callback(err, bytesRead, buffers);
- done();
- });
-});
-
-describe("Testing with incorrect arguments", () => {
- const wrongInputs = [false, "test", {}, [{}], ["sdf"], null, undefined];
-
- test("fs.readv with wrong buffers argument", () => {
- const filename = getFileName();
- fs.writeFileSync(filename, expectedBuff);
- const fd = fs.openSync(filename, "r");
-
- for (const wrongInput of wrongInputs) {
- expect(() => fs.readv(fd, wrongInput, null, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- }
-
- fs.closeSync(fd);
- });
-
- test("fs.readv with wrong fd argument", () => {
- for (const wrongInput of wrongInputs) {
- expect(() => fs.readv(wrongInput, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- }
- });
-});
-
-//<#END_FILE: test-fs-readv.js
diff --git a/test/js/node/test/parallel/fs-realpath-pipe.test.js b/test/js/node/test/parallel/fs-realpath-pipe.test.js
deleted file mode 100644
index 6c461e9d36..0000000000
--- a/test/js/node/test/parallel/fs-realpath-pipe.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-fs-realpath-pipe.js
-//#SHA1: 2a876967f5134cd77e2214f2abcbf753d46983cf
-//-----------------
-"use strict";
-
-const { spawnSync } = require("child_process");
-
-// Skip test for Windows, AIX, and IBMi
-const isSkippedPlatform = ["win32", "aix", "os400"].includes(process.platform);
-const testName = `No /dev/stdin on ${process.platform}.`;
-
-(isSkippedPlatform ? test.skip : test)(testName, () => {
- const testCases = [
- `require('fs').realpath('/dev/stdin', (err, resolvedPath) => {
- if (err) {
- console.error(err);
- process.exit(1);
- }
- if (resolvedPath) {
- process.exit(2);
- }
- });`,
- `try {
- if (require('fs').realpathSync('/dev/stdin')) {
- process.exit(2);
- }
- } catch (e) {
- console.error(e);
- process.exit(1);
- }`,
- ];
-
- for (const code of testCases) {
- const child = spawnSync(process.execPath, ["-e", code], {
- stdio: "pipe",
- });
-
- if (child.status !== 2) {
- console.log(code);
- console.log(child.stderr.toString());
- }
-
- expect(child.status).toBe(2);
- }
-});
-
-//<#END_FILE: test-fs-realpath-pipe.js
diff --git a/test/js/node/test/parallel/fs-rmdir-type-check.test.js b/test/js/node/test/parallel/fs-rmdir-type-check.test.js
deleted file mode 100644
index 3148f0ba3a..0000000000
--- a/test/js/node/test/parallel/fs-rmdir-type-check.test.js
+++ /dev/null
@@ -1,28 +0,0 @@
-//#FILE: test-fs-rmdir-type-check.js
-//#SHA1: 2a00191160af6f0f76a82dcaef31d13c9b223d3b
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-test("fs.rmdir and fs.rmdirSync with invalid arguments", () => {
- [false, 1, [], {}, null, undefined].forEach(i => {
- expect(() => fs.rmdir(i, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-
- expect(() => fs.rmdirSync(i)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-fs-rmdir-type-check.js
diff --git a/test/js/node/test/parallel/fs-sir-writes-alot.test.js b/test/js/node/test/parallel/fs-sir-writes-alot.test.js
deleted file mode 100644
index b8eefc6642..0000000000
--- a/test/js/node/test/parallel/fs-sir-writes-alot.test.js
+++ /dev/null
@@ -1,84 +0,0 @@
-//#FILE: test-fs-sir-writes-alot.js
-//#SHA1: d6f4574d48b9a85ee1276e4e0499f3fc32096d24
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-sir-writes-alot');
-const filename = path.join(tmpdir, 'out.txt');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('multiple async writes to a file', async () => {
- const fd = fs.openSync(filename, 'w');
-
- const line = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n';
- const N = 10240;
- let complete = 0;
- let bytesChecked = 0;
-
- function testBuffer(b) {
- for (let i = 0; i < b.length; i++) {
- bytesChecked++;
- if (b[i] !== 'a'.charCodeAt(0) && b[i] !== '\n'.charCodeAt(0)) {
- throw new Error(`invalid char ${i},${b[i]}`);
- }
- }
- }
-
- await new Promise((resolve) => {
- for (let i = 0; i < N; i++) {
- // Create a new buffer for each write. Before the write is actually
- // executed by the thread pool, the buffer will be collected.
- const buffer = Buffer.from(line);
- fs.write(fd, buffer, 0, buffer.length, null, function(er, written) {
- complete++;
- if (complete === N) {
- fs.closeSync(fd);
- const s = fs.createReadStream(filename);
- s.on('data', testBuffer);
- s.on('end', resolve);
- }
- });
- }
- });
-
- // Probably some of the writes are going to overlap, so we can't assume
- // that we get (N * line.length). Let's just make sure we've checked a
- // few...
- expect(bytesChecked).toBeGreaterThan(1000);
-});
-
-//<#END_FILE: test-fs-sir-writes-alot.js
diff --git a/test/js/node/test/parallel/fs-stat-bigint.test.js b/test/js/node/test/parallel/fs-stat-bigint.test.js
deleted file mode 100644
index d7eb29c3f0..0000000000
--- a/test/js/node/test/parallel/fs-stat-bigint.test.js
+++ /dev/null
@@ -1,209 +0,0 @@
-//#FILE: test-fs-stat-bigint.js
-//#SHA1: c8ba0bacb927432a68a677cd3a304e8e058fb070
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const promiseFs = require("fs").promises;
-const tmpdir = require("../common/tmpdir");
-const { isDate } = require("util").types;
-const { inspect } = require("util");
-
-tmpdir.refresh();
-
-let testIndex = 0;
-
-function getFilename() {
- const filename = tmpdir.resolve(`test-file-${++testIndex}`);
- fs.writeFileSync(filename, "test");
- return filename;
-}
-
-function verifyStats(bigintStats, numStats, allowableDelta) {
- // allowableDelta: It's possible that the file stats are updated between the
- // two stat() calls so allow for a small difference.
- for (const key of Object.keys(numStats)) {
- const val = numStats[key];
- if (isDate(val)) {
- const time = val.getTime();
- const time2 = bigintStats[key].getTime();
- expect(time - time2).toBeLessThanOrEqual(allowableDelta);
- } else if (key === "mode") {
- expect(bigintStats[key]).toBe(BigInt(val));
- expect(bigintStats.isBlockDevice()).toBe(numStats.isBlockDevice());
- expect(bigintStats.isCharacterDevice()).toBe(numStats.isCharacterDevice());
- expect(bigintStats.isDirectory()).toBe(numStats.isDirectory());
- expect(bigintStats.isFIFO()).toBe(numStats.isFIFO());
- expect(bigintStats.isFile()).toBe(numStats.isFile());
- expect(bigintStats.isSocket()).toBe(numStats.isSocket());
- expect(bigintStats.isSymbolicLink()).toBe(numStats.isSymbolicLink());
- } else if (key.endsWith("Ms")) {
- const nsKey = key.replace("Ms", "Ns");
- const msFromBigInt = bigintStats[key];
- const nsFromBigInt = bigintStats[nsKey];
- const msFromBigIntNs = Number(nsFromBigInt / 10n ** 6n);
- const msFromNum = numStats[key];
-
- expect(msFromNum - Number(msFromBigInt)).toBeLessThanOrEqual(allowableDelta);
- expect(msFromNum - Number(msFromBigIntNs)).toBeLessThanOrEqual(allowableDelta);
- } else if (Number.isSafeInteger(val)) {
- expect(bigintStats[key]).toBe(BigInt(val));
- } else {
- expect(Number(bigintStats[key]) - val).toBeLessThan(1);
- }
- }
-}
-
-const runSyncTest = (func, arg) => {
- const startTime = process.hrtime.bigint();
- const bigintStats = func(arg, { bigint: true });
- const numStats = func(arg);
- const endTime = process.hrtime.bigint();
- const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6);
- verifyStats(bigintStats, numStats, allowableDelta);
-};
-
-test("fs.statSync", () => {
- const filename = getFilename();
- runSyncTest(fs.statSync, filename);
-});
-
-if (!process.platform.startsWith("win")) {
- test("fs.lstatSync", () => {
- const filename = getFilename();
- const link = `${filename}-link`;
- fs.symlinkSync(filename, link);
- runSyncTest(fs.lstatSync, link);
- });
-}
-
-test("fs.fstatSync", () => {
- const filename = getFilename();
- const fd = fs.openSync(filename, "r");
- runSyncTest(fs.fstatSync, fd);
- fs.closeSync(fd);
-});
-
-test("fs.statSync with non-existent file", () => {
- expect(() => fs.statSync("does_not_exist")).toThrow(expect.objectContaining({ code: "ENOENT" }));
- expect(fs.statSync("does_not_exist", { throwIfNoEntry: false })).toBeUndefined();
-});
-
-test("fs.lstatSync with non-existent file", () => {
- expect(() => fs.lstatSync("does_not_exist")).toThrow(expect.objectContaining({ code: "ENOENT" }));
- expect(fs.lstatSync("does_not_exist", { throwIfNoEntry: false })).toBeUndefined();
-});
-
-test("fs.fstatSync with invalid file descriptor", () => {
- expect(() => fs.fstatSync(9999)).toThrow(expect.objectContaining({ code: "EBADF" }));
- expect(() => fs.fstatSync(9999, { throwIfNoEntry: false })).toThrow(expect.objectContaining({ code: "EBADF" }));
-});
-
-const runCallbackTest = (func, arg) => {
- return new Promise(resolve => {
- const startTime = process.hrtime.bigint();
- func(arg, { bigint: true }, (err, bigintStats) => {
- expect(err).toBeFalsy();
- func(arg, (err, numStats) => {
- expect(err).toBeFalsy();
- const endTime = process.hrtime.bigint();
- const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6);
- verifyStats(bigintStats, numStats, allowableDelta);
- resolve();
- });
- });
- });
-};
-
-test("fs.stat callback", async () => {
- const filename = getFilename();
- await runCallbackTest(fs.stat, filename);
-});
-
-if (!process.platform.startsWith("win")) {
- test("fs.lstat callback", async () => {
- const filename = getFilename();
- const link = `${filename}-link`;
- fs.symlinkSync(filename, link);
- await runCallbackTest(fs.lstat, link);
- });
-}
-
-test("fs.fstat callback", async () => {
- const filename = getFilename();
- const fd = fs.openSync(filename, "r");
- await runCallbackTest(fs.fstat, fd);
- fs.closeSync(fd);
-});
-
-const runPromiseTest = async (func, arg) => {
- const startTime = process.hrtime.bigint();
- const bigintStats = await func(arg, { bigint: true });
- const numStats = await func(arg);
- const endTime = process.hrtime.bigint();
- const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6);
- verifyStats(bigintStats, numStats, allowableDelta);
-};
-
-test("promiseFs.stat", async () => {
- const filename = getFilename();
- await runPromiseTest(promiseFs.stat, filename);
-});
-
-if (!process.platform.startsWith("win")) {
- test("promiseFs.lstat", async () => {
- const filename = getFilename();
- const link = `${filename}-link`;
- fs.symlinkSync(filename, link);
- await runPromiseTest(promiseFs.lstat, link);
- });
-}
-
-test("promiseFs handle.stat", async () => {
- const filename = getFilename();
- const handle = await promiseFs.open(filename, "r");
- const startTime = process.hrtime.bigint();
- const bigintStats = await handle.stat({ bigint: true });
- const numStats = await handle.stat();
- const endTime = process.hrtime.bigint();
- const allowableDelta = Math.ceil(Number(endTime - startTime) / 1e6);
- verifyStats(bigintStats, numStats, allowableDelta);
- await handle.close();
-});
-
-test("BigIntStats Date properties can be set before reading them", done => {
- fs.stat(__filename, { bigint: true }, (err, s) => {
- expect(err).toBeFalsy();
- s.atime = 2;
- s.mtime = 3;
- s.ctime = 4;
- s.birthtime = 5;
-
- expect(s.atime).toBe(2);
- expect(s.mtime).toBe(3);
- expect(s.ctime).toBe(4);
- expect(s.birthtime).toBe(5);
- done();
- });
-});
-
-test("BigIntStats Date properties can be set after reading them", done => {
- fs.stat(__filename, { bigint: true }, (err, s) => {
- expect(err).toBeFalsy();
- // eslint-disable-next-line no-unused-expressions
- s.atime, s.mtime, s.ctime, s.birthtime;
-
- s.atime = 2;
- s.mtime = 3;
- s.ctime = 4;
- s.birthtime = 5;
-
- expect(s.atime).toBe(2);
- expect(s.mtime).toBe(3);
- expect(s.ctime).toBe(4);
- expect(s.birthtime).toBe(5);
- done();
- });
-});
-
-//<#END_FILE: test-fs-stat-bigint.js
diff --git a/test/js/node/test/parallel/fs-stream-double-close.test.js b/test/js/node/test/parallel/fs-stream-double-close.test.js
deleted file mode 100644
index 0e89c7bf26..0000000000
--- a/test/js/node/test/parallel/fs-stream-double-close.test.js
+++ /dev/null
@@ -1,84 +0,0 @@
-//#FILE: test-fs-stream-double-close.js
-//#SHA1: 25fa219f7ee462e67611751f996393afc1869490
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const tmpdir = path.join(os.tmpdir(), "node-test-fs-stream-double-close");
-beforeAll(() => {
- if (!fs.existsSync(tmpdir)) {
- fs.mkdirSync(tmpdir, { recursive: true });
- }
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test("test1 with ReadStream", () => {
- test1(fs.createReadStream(__filename));
-});
-
-test("test2 with ReadStream", () => {
- test2(fs.createReadStream(__filename));
-});
-
-test("test3 with ReadStream", () => {
- test3(fs.createReadStream(__filename));
-});
-
-test("test1 with WriteStream", () => {
- test1(fs.createWriteStream(path.join(tmpdir, "dummy1")));
-});
-
-test("test2 with WriteStream", () => {
- test2(fs.createWriteStream(path.join(tmpdir, "dummy2")));
-});
-
-test("test3 with WriteStream", () => {
- test3(fs.createWriteStream(path.join(tmpdir, "dummy3")));
-});
-
-function test1(stream) {
- stream.destroy();
- stream.destroy();
-}
-
-function test2(stream) {
- stream.destroy();
- stream.on("open", jest.fn());
-}
-
-function test3(stream) {
- const openHandler = jest.fn();
- stream.on("open", openHandler);
- stream.emit("open");
- expect(openHandler).toHaveBeenCalledTimes(1);
- stream.destroy();
- stream.destroy();
-}
-
-//<#END_FILE: test-fs-stream-double-close.js
diff --git a/test/js/node/test/parallel/fs-symlink-buffer-path.test.js b/test/js/node/test/parallel/fs-symlink-buffer-path.test.js
deleted file mode 100644
index 17bde4dccb..0000000000
--- a/test/js/node/test/parallel/fs-symlink-buffer-path.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-fs-symlink-buffer-path.js
-//#SHA1: 73fa7d9b492bd23730f1a8763caac92a9f4a1896
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const canCreateSymLink = () => {
- try {
- fs.symlinkSync('test-file', 'test-symlink');
- fs.unlinkSync('test-symlink');
- return true;
- } catch (err) {
- return false;
- }
-};
-
-if (!canCreateSymLink()) {
- test.skip('insufficient privileges', () => {});
-} else {
- const tmpdir = path.join(os.tmpdir(), 'test-fs-symlink-buffer-path');
- const fixturesPath = path.join(__dirname, '..', 'fixtures');
-
- beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- });
-
- afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- });
-
- test('creating and reading symbolic link', async () => {
- const linkData = path.join(fixturesPath, 'cycles', 'root.js');
- const linkPath = path.join(tmpdir, 'symlink1.js');
-
- fs.symlinkSync(Buffer.from(linkData), linkPath);
-
- const linkStats = await fs.promises.lstat(linkPath);
- const linkTime = linkStats.mtime.getTime();
-
- const fileStats = await fs.promises.stat(linkPath);
- const fileTime = fileStats.mtime.getTime();
-
- const destination = await fs.promises.readlink(linkPath);
- expect(destination).toBe(linkData);
-
- expect(linkTime).not.toBe(fileTime);
- });
-}
-
-//<#END_FILE: test-fs-symlink-buffer-path.js
diff --git a/test/js/node/test/parallel/fs-symlink.test.js b/test/js/node/test/parallel/fs-symlink.test.js
deleted file mode 100644
index c4e68336ba..0000000000
--- a/test/js/node/test/parallel/fs-symlink.test.js
+++ /dev/null
@@ -1,148 +0,0 @@
-//#FILE: test-fs-symlink.js
-//#SHA1: 4861a453e314d789a1b933d7179da96b7a35378c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const canCreateSymLink = () => {
- try {
- fs.symlinkSync("", "");
- fs.unlinkSync("");
- return true;
- } catch (e) {
- return false;
- }
-};
-
-if (!canCreateSymLink()) {
- it.skip("insufficient privileges", () => {});
-} else {
- let linkTime;
- let fileTime;
- const tmpdir = os.tmpdir();
-
- beforeEach(() => {
- jest.spyOn(fs, "symlink");
- jest.spyOn(fs, "lstat");
- jest.spyOn(fs, "stat");
- jest.spyOn(fs, "readlink");
- });
-
- afterEach(() => {
- jest.restoreAllMocks();
- });
-
- test("Test creating and reading symbolic link", async () => {
- const linkData = path.resolve(__dirname, "../fixtures/cycles/root.js");
- const linkPath = path.resolve(tmpdir, "symlink1.js");
-
- await new Promise(resolve => {
- fs.symlink(linkData, linkPath, resolve);
- });
-
- expect(fs.symlink).toHaveBeenCalled();
-
- await new Promise(resolve => {
- fs.lstat(linkPath, (err, stats) => {
- expect(err).toBeNull();
- linkTime = stats.mtime.getTime();
- resolve();
- });
- });
-
- await new Promise(resolve => {
- fs.stat(linkPath, (err, stats) => {
- expect(err).toBeNull();
- fileTime = stats.mtime.getTime();
- resolve();
- });
- });
-
- await new Promise(resolve => {
- fs.readlink(linkPath, (err, destination) => {
- expect(err).toBeNull();
- expect(destination).toBe(linkData);
- resolve();
- });
- });
- });
-
- test("Test invalid symlink", async () => {
- const linkData = path.resolve(__dirname, "../fixtures/not/exists/file");
- const linkPath = path.resolve(tmpdir, "symlink2.js");
-
- await new Promise(resolve => {
- fs.symlink(linkData, linkPath, resolve);
- });
-
- expect(fs.existsSync(linkPath)).toBe(false);
- });
-
- test("Test invalid inputs", () => {
- const invalidInputs = [false, 1, {}, [], null, undefined];
- const errObj = expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.stringMatching(/target|path/),
- });
-
- invalidInputs.forEach(input => {
- expect(() => fs.symlink(input, "", () => {})).toThrow(errObj);
- expect(() => fs.symlinkSync(input, "")).toThrow(errObj);
-
- expect(() => fs.symlink("", input, () => {})).toThrow(errObj);
- expect(() => fs.symlinkSync("", input)).toThrow(errObj);
- });
- });
-
- test("Test invalid type inputs", () => {
- const errObj = expect.objectContaining({
- code: "ERR_INVALID_ARG_VALUE",
- name: "TypeError",
- });
-
- expect(() => fs.symlink("", "", "🍏", () => {})).toThrow(errObj);
- expect(() => fs.symlinkSync("", "", "🍏")).toThrow(errObj);
-
- expect(() => fs.symlink("", "", "nonExistentType", () => {})).toThrow(errObj);
- expect(() => fs.symlinkSync("", "", "nonExistentType")).toThrow(errObj);
- expect(fs.promises.symlink("", "", "nonExistentType")).rejects.toMatchObject(errObj);
-
- expect(() => fs.symlink("", "", false, () => {})).toThrow(errObj);
- expect(() => fs.symlinkSync("", "", false)).toThrow(errObj);
- expect(fs.promises.symlink("", "", false)).rejects.toMatchObject(errObj);
-
- expect(() => fs.symlink("", "", {}, () => {})).toThrow(errObj);
- expect(() => fs.symlinkSync("", "", {})).toThrow(errObj);
- expect(fs.promises.symlink("", "", {})).rejects.toMatchObject(errObj);
- });
-
- test("Link time should not be equal to file time", () => {
- expect(linkTime).not.toBe(fileTime);
- });
-}
-
-//<#END_FILE: test-fs-symlink.js
diff --git a/test/js/node/test/parallel/fs-truncate-clear-file-zero.test.js b/test/js/node/test/parallel/fs-truncate-clear-file-zero.test.js
deleted file mode 100644
index 8dc9566b1f..0000000000
--- a/test/js/node/test/parallel/fs-truncate-clear-file-zero.test.js
+++ /dev/null
@@ -1,67 +0,0 @@
-//#FILE: test-fs-truncate-clear-file-zero.js
-//#SHA1: 28aa057c9903ea2436c340ccecfec093c647714c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// This test ensures that `fs.truncate` opens the file with `r+` and not `w`,
-// which had earlier resulted in the target file's content getting zeroed out.
-// https://github.com/nodejs/node-v0.x-archive/issues/6233
-
-const filename = path.join(os.tmpdir(), "truncate-file.txt");
-
-beforeEach(() => {
- // Clean up any existing test file
- try {
- fs.unlinkSync(filename);
- } catch (err) {
- if (err.code !== "ENOENT") throw err;
- }
-});
-
-test("fs.truncateSync", () => {
- fs.writeFileSync(filename, "0123456789");
- expect(fs.readFileSync(filename, "utf8")).toBe("0123456789");
- fs.truncateSync(filename, 5);
- expect(fs.readFileSync(filename, "utf8")).toBe("01234");
-});
-
-test("fs.truncate", async () => {
- fs.writeFileSync(filename, "0123456789");
- expect(fs.readFileSync(filename, "utf8")).toBe("0123456789");
-
- await new Promise((resolve, reject) => {
- fs.truncate(filename, 5, err => {
- if (err) reject(err);
- else resolve();
- });
- });
-
- expect(fs.readFileSync(filename, "utf8")).toBe("01234");
-});
-
-//<#END_FILE: test-fs-truncate-clear-file-zero.js
diff --git a/test/js/node/test/parallel/fs-truncate-sync.test.js b/test/js/node/test/parallel/fs-truncate-sync.test.js
deleted file mode 100644
index cdf9a5f739..0000000000
--- a/test/js/node/test/parallel/fs-truncate-sync.test.js
+++ /dev/null
@@ -1,31 +0,0 @@
-//#FILE: test-fs-truncate-sync.js
-//#SHA1: 6b4ccbf9b9fab199c6b258374cf0a1665b1c21fe
-//-----------------
-"use strict";
-
-const path = require("path");
-const fs = require("fs");
-const tmpdir = require("../common/tmpdir");
-const tmp = tmpdir.path;
-
-describe("fs.truncateSync", () => {
- beforeEach(() => {
- tmpdir.refresh();
- });
-
- test("truncates file correctly", () => {
- const filename = path.resolve(tmp, "truncate-sync-file.txt");
-
- fs.writeFileSync(filename, "hello world", "utf8");
-
- const fd = fs.openSync(filename, "r+");
-
- fs.truncateSync(fd, 5);
- expect(fs.readFileSync(fd)).toEqual(Buffer.from("hello"));
-
- fs.closeSync(fd);
- fs.unlinkSync(filename);
- });
-});
-
-//<#END_FILE: test-fs-truncate-sync.js
diff --git a/test/js/node/test/parallel/fs-unlink-type-check.test.js b/test/js/node/test/parallel/fs-unlink-type-check.test.js
deleted file mode 100644
index 4f819feecd..0000000000
--- a/test/js/node/test/parallel/fs-unlink-type-check.test.js
+++ /dev/null
@@ -1,30 +0,0 @@
-//#FILE: test-fs-unlink-type-check.js
-//#SHA1: 337e42f3b15589a7652c32c0a1c92292abf098d0
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-test("fs.unlink and fs.unlinkSync with invalid types", () => {
- const invalidTypes = [false, 1, {}, [], null, undefined];
-
- invalidTypes.forEach(invalidType => {
- expect(() => fs.unlink(invalidType, jest.fn())).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-
- expect(() => fs.unlinkSync(invalidType)).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-fs-unlink-type-check.js
diff --git a/test/js/node/test/parallel/fs-util-validateoffsetlength.test.js b/test/js/node/test/parallel/fs-util-validateoffsetlength.test.js
deleted file mode 100644
index 1cc49c3be9..0000000000
--- a/test/js/node/test/parallel/fs-util-validateoffsetlength.test.js
+++ /dev/null
@@ -1,85 +0,0 @@
-//#FILE: test-fs-util-validateoffsetlength.js
-//#SHA1: d5c952d2e87072352a6a60351ede415d1925cf21
-//-----------------
-'use strict';
-
-// Implement the functions we want to test
-function validateOffsetLengthRead(offset, length, byteLength) {
- if (offset < 0) {
- throw new RangeError('The value of "offset" is out of range. ' +
- `It must be >= 0. Received ${offset}`);
- }
- if (length < 0) {
- throw new RangeError('The value of "length" is out of range. ' +
- `It must be >= 0. Received ${length}`);
- }
- if (offset + length > byteLength) {
- throw new RangeError('The value of "length" is out of range. ' +
- `It must be <= ${byteLength - offset}. Received ${length}`);
- }
-}
-
-function validateOffsetLengthWrite(offset, length, byteLength) {
- if (offset > byteLength) {
- throw new RangeError('The value of "offset" is out of range. ' +
- `It must be <= ${byteLength}. Received ${offset}`);
- }
- if (length > byteLength - offset) {
- throw new RangeError('The value of "length" is out of range. ' +
- `It must be <= ${byteLength - offset}. Received ${length}`);
- }
-}
-
-describe('validateOffsetLengthRead', () => {
- test('throws RangeError when offset is negative', () => {
- const offset = -1;
- expect(() => validateOffsetLengthRead(offset, 0, 0)).toThrow(expect.objectContaining({
- name: 'RangeError',
- message: expect.stringContaining(`It must be >= 0. Received ${offset}`)
- }));
- });
-
- test('throws RangeError when length is negative', () => {
- const length = -1;
- expect(() => validateOffsetLengthRead(0, length, 0)).toThrow(expect.objectContaining({
- name: 'RangeError',
- message: expect.stringContaining(`It must be >= 0. Received ${length}`)
- }));
- });
-
- test('throws RangeError when length is out of range', () => {
- const offset = 1;
- const length = 1;
- const byteLength = offset + length - 1;
- expect(() => validateOffsetLengthRead(offset, length, byteLength)).toThrow(expect.objectContaining({
- name: 'RangeError',
- message: expect.stringContaining(`It must be <= ${byteLength - offset}. Received ${length}`)
- }));
- });
-});
-
-describe('validateOffsetLengthWrite', () => {
- const kIoMaxLength = 2 ** 31 - 1;
-
- test('throws RangeError when offset > byteLength', () => {
- const offset = 100;
- const length = 100;
- const byteLength = 50;
- expect(() => validateOffsetLengthWrite(offset, length, byteLength)).toThrow(expect.objectContaining({
- name: 'RangeError',
- message: expect.stringContaining(`It must be <= ${byteLength}. Received ${offset}`)
- }));
- });
-
- test('throws RangeError when byteLength < kIoMaxLength and length > byteLength - offset', () => {
- const offset = kIoMaxLength - 150;
- const length = 200;
- const byteLength = kIoMaxLength - 100;
- expect(() => validateOffsetLengthWrite(offset, length, byteLength)).toThrow(expect.objectContaining({
- name: 'RangeError',
- message: expect.stringContaining(`It must be <= ${byteLength - offset}. Received ${length}`)
- }));
- });
-});
-
-//<#END_FILE: test-fs-util-validateoffsetlength.js
diff --git a/test/js/node/test/parallel/fs-watch-abort-signal.test.js b/test/js/node/test/parallel/fs-watch-abort-signal.test.js
deleted file mode 100644
index 030e33814e..0000000000
--- a/test/js/node/test/parallel/fs-watch-abort-signal.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-fs-watch-abort-signal.js
-//#SHA1: 6f0b7fcc2f597faa8e1353559d5d007cd744614a
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const isIBMi = process.platform === 'os400';
-
-if (isIBMi) {
- test.skip('IBMi does not support `fs.watch()`', () => {});
-} else {
- const tmpdir = path.join(os.tmpdir(), 'test-fs-watch-abort-signal');
- const emptyFile = path.join(tmpdir, 'empty.js');
-
- beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- fs.writeFileSync(emptyFile, '');
- });
-
- afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- });
-
- test('Signal aborted after creating the watcher', (done) => {
- const ac = new AbortController();
- const { signal } = ac;
- const watcher = fs.watch(emptyFile, { signal });
- watcher.once('close', () => {
- done();
- });
- setImmediate(() => ac.abort());
- });
-
- test('Signal aborted before creating the watcher', (done) => {
- const signal = AbortSignal.abort();
- const watcher = fs.watch(emptyFile, { signal });
- watcher.once('close', () => {
- done();
- });
- });
-}
-
-//<#END_FILE: test-fs-watch-abort-signal.js
diff --git a/test/js/node/test/parallel/fs-watch-close-when-destroyed.test.js b/test/js/node/test/parallel/fs-watch-close-when-destroyed.test.js
deleted file mode 100644
index 5749125642..0000000000
--- a/test/js/node/test/parallel/fs-watch-close-when-destroyed.test.js
+++ /dev/null
@@ -1,63 +0,0 @@
-//#FILE: test-fs-watch-close-when-destroyed.js
-//#SHA1: f062b7243d0c42722a289a6228d4c2c1a503be1b
-//-----------------
-"use strict";
-
-// This tests that closing a watcher when the underlying handle is
-// already destroyed will result in a noop instead of a crash.
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// fs-watch on folders have limited capability in AIX.
-// The testcase makes use of folder watching, and causes
-// hang. This behavior is documented. Skip this for AIX.
-
-if (process.platform === "aix") {
- it.skip("folder watch capability is limited in AIX.");
-} else if (process.platform === "os400") {
- it.skip("IBMi does not support `fs.watch()`");
-} else {
- let root;
-
- beforeEach(() => {
- root = path.join(os.tmpdir(), "watched-directory-" + Math.random().toString(36).slice(2));
- fs.mkdirSync(root);
- });
-
- afterEach(() => {
- try {
- fs.rmdirSync(root);
- } catch (error) {
- // Ignore errors, directory might already be removed
- }
- });
-
- it("should not crash when closing watcher after handle is destroyed", done => {
- const watcher = fs.watch(root, { persistent: false, recursive: false });
-
- // The following listeners may or may not be invoked.
-
- watcher.addListener("error", () => {
- setTimeout(
- () => {
- watcher.close();
- }, // Should not crash if it's invoked
- 10,
- );
- });
-
- watcher.addListener("change", () => {
- setTimeout(() => {
- watcher.close();
- }, 10);
- });
-
- fs.rmdirSync(root);
- // Wait for the listener to hit
- setTimeout(done, 100);
- });
-}
-
-//<#END_FILE: test-fs-watch-close-when-destroyed.js
diff --git a/test/js/node/test/parallel/fs-watch-encoding.test.js b/test/js/node/test/parallel/fs-watch-encoding.test.js
deleted file mode 100644
index 472a77d57a..0000000000
--- a/test/js/node/test/parallel/fs-watch-encoding.test.js
+++ /dev/null
@@ -1,76 +0,0 @@
-//#FILE: test-fs-watch-encoding.js
-//#SHA1: 63f7e4008743417c7ee5995bbf16a28ade764e48
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-watch-encoding');
-const fn = '新建文夹件.txt';
-const a = path.join(tmpdir, fn);
-
-let interval;
-
-beforeAll(() => {
- if (process.platform === 'aix') {
- return test.skip('folder watch capability is limited in AIX.');
- }
- if (process.platform === 'os400') {
- return test.skip('IBMi does not support `fs.watch()`');
- }
-
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- clearInterval(interval);
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-const watcherTests = [
- {
- name: 'with hex encoding',
- options: { encoding: 'hex' },
- expectedFilenames: ['e696b0e5bbbae69687e5a4b9e4bbb62e747874', null],
- },
- {
- name: 'without encoding option',
- options: {},
- expectedFilenames: [fn, null],
- },
- {
- name: 'with buffer encoding',
- options: { encoding: 'buffer' },
- expectedFilenames: [Buffer.from(fn), null],
- },
-];
-
-watcherTests.forEach(({ name, options, expectedFilenames }) => {
- test(`fs.watch ${name}`, (done) => {
- const watcher = fs.watch(tmpdir, options, (event, filename) => {
- if (expectedFilenames.some(expected =>
- expected instanceof Buffer
- ? expected.equals(filename)
- : expected === filename)) {
- watcher.close();
- done();
- }
- });
-
- // Start the interval after setting up the watcher
- if (!interval) {
- interval = setInterval(() => {
- const fd = fs.openSync(a, 'w+');
- fs.closeSync(fd);
- fs.unlinkSync(a);
- }, 100);
- }
- }, 10000); // Increased timeout to allow for file operations
-});
-
-//<#END_FILE: test-fs-watch-encoding.js
diff --git a/test/js/node/test/parallel/fs-watch-file-enoent-after-deletion.test.js b/test/js/node/test/parallel/fs-watch-file-enoent-after-deletion.test.js
deleted file mode 100644
index ee439c8272..0000000000
--- a/test/js/node/test/parallel/fs-watch-file-enoent-after-deletion.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-fs-watch-file-enoent-after-deletion.js
-//#SHA1: d6c93db608d119bd35fcab0e1e9307bfd6558b68
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// Make sure the deletion event gets reported in the following scenario:
-// 1. Watch a file.
-// 2. The initial stat() goes okay.
-// 3. Something deletes the watched file.
-// 4. The second stat() fails with ENOENT.
-
-// The second stat() translates into the first 'change' event but a logic error
-// stopped it from getting emitted.
-// https://github.com/nodejs/node-v0.x-archive/issues/4027
-
-test("fs.watchFile reports deletion", done => {
- const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "test-"));
- const filename = path.join(tmpdir, "watched");
- fs.writeFileSync(filename, "quis custodiet ipsos custodes");
-
- const watcher = jest.fn();
- fs.watchFile(filename, { interval: 50 }, watcher);
-
- setTimeout(() => {
- fs.unlinkSync(filename);
-
- setTimeout(() => {
- expect(watcher).toHaveBeenCalledTimes(1);
- const [curr, prev] = watcher.mock.calls[0];
- expect(curr.nlink).toBe(0);
- expect(prev.nlink).toBe(1);
-
- fs.unwatchFile(filename);
- fs.rmdirSync(tmpdir);
- done();
- }, 100);
- }, 100);
-});
-
-//<#END_FILE: test-fs-watch-file-enoent-after-deletion.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-add-file-to-existing-subfolder.test.js b/test/js/node/test/parallel/fs-watch-recursive-add-file-to-existing-subfolder.test.js
deleted file mode 100644
index 3e2c067792..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-add-file-to-existing-subfolder.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-fs-watch-recursive-add-file-to-existing-subfolder.js
-//#SHA1: 7d4414be8a9ba35f2ebdb685037951133137b6ef
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const testDir = path.join(os.tmpdir(), 'test-fs-watch-recursive-add-file-to-existing-subfolder');
-
-beforeAll(() => {
- if (fs.existsSync(testDir)) {
- fs.rmSync(testDir, { recursive: true, force: true });
- }
- fs.mkdirSync(testDir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(testDir, { recursive: true, force: true });
-});
-
-test('fs.watch detects file added to existing subfolder', (done) => {
- const rootDirectory = fs.mkdtempSync(path.join(testDir, 'test-'));
- const testDirectory = path.join(rootDirectory, 'test-4');
- fs.mkdirSync(testDirectory);
-
- const file = 'folder-5';
- const filePath = path.join(testDirectory, file);
- fs.mkdirSync(filePath);
-
- const subfolderPath = path.join(filePath, 'subfolder-6');
- fs.mkdirSync(subfolderPath);
-
- const childrenFile = 'file-7.txt';
- const childrenAbsolutePath = path.join(subfolderPath, childrenFile);
- const relativePath = path.join(file, path.basename(subfolderPath), childrenFile);
-
- const watcher = fs.watch(testDirectory, { recursive: true });
- let watcherClosed = false;
-
- watcher.on('change', (event, filename) => {
- expect(event).toBe('rename');
-
- if (filename === relativePath) {
- watcher.close();
- watcherClosed = true;
- expect(watcherClosed).toBe(true);
- done();
- }
- });
-
- // Do the write with a delay to ensure that the OS is ready to notify us.
- setTimeout(() => {
- fs.writeFileSync(childrenAbsolutePath, 'world');
- }, 200);
-}, 10000); // Increased timeout to 10 seconds
-
-//<#END_FILE: test-fs-watch-recursive-add-file-to-existing-subfolder.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-add-file-with-url.test.js b/test/js/node/test/parallel/fs-watch-recursive-add-file-with-url.test.js
deleted file mode 100644
index 2131b1dbe5..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-add-file-with-url.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-fs-watch-recursive-add-file-with-url.js
-//#SHA1: e6498ea80abdf69cb66d888bbd7d631931970c0a
-//-----------------
-"use strict";
-
-const { setTimeout } = require("timers/promises");
-const path = require("path");
-const fs = require("fs");
-const { pathToFileURL } = require("url");
-const os = require("os");
-
-const isIBMi = process.platform === "os400";
-const isAIX = process.platform === "aix";
-
-if (isIBMi) {
- it.skip("IBMi does not support `fs.watch()`", () => {});
-} else if (isAIX) {
- it.skip("folder watch capability is limited in AIX.", () => {});
-} else {
- it("should watch for file changes using URL as path", async () => {
- const testDir = fs.mkdtempSync(path.join(os.tmpdir(), "test-"));
-
- // Add a file to already watching folder, and use URL as the path
- const rootDirectory = fs.mkdtempSync(path.join(testDir, path.sep));
- const testDirectory = path.join(rootDirectory, "test-5");
- fs.mkdirSync(testDirectory);
-
- const filePath = path.join(testDirectory, "file-8.txt");
- const url = pathToFileURL(testDirectory);
-
- const watcher = fs.watch(url, { recursive: true });
- let watcherClosed = false;
-
- const watchPromise = new Promise(resolve => {
- watcher.on("change", function (event, filename) {
- expect(event).toBe("rename");
-
- if (filename === path.basename(filePath)) {
- watcher.close();
- watcherClosed = true;
- resolve();
- }
- });
- });
-
- await setTimeout(100);
- fs.writeFileSync(filePath, "world");
-
- await watchPromise;
-
- expect(watcherClosed).toBe(true);
- }, 10000); // Increase timeout to 10 seconds
-}
-
-//<#END_FILE: test-fs-watch-recursive-add-file-with-url.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-add-file.test.js b/test/js/node/test/parallel/fs-watch-recursive-add-file.test.js
deleted file mode 100644
index 00c5fcf7e6..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-add-file.test.js
+++ /dev/null
@@ -1,63 +0,0 @@
-//#FILE: test-fs-watch-recursive-add-file.js
-//#SHA1: e87d2c9f4789a6e6a83fbdca56e39683625bd0af
-//-----------------
-"use strict";
-
-const path = require("path");
-const fs = require("fs");
-const os = require("os");
-
-const isIBMi = os.platform() === "os400";
-const isAIX = os.platform() === "aix";
-
-if (isIBMi) {
- it.skip("IBMi does not support `fs.watch()`", () => {});
-} else if (isAIX) {
- it.skip("folder watch capability is limited in AIX.", () => {});
-} else {
- const tmpdir = {
- path: path.join(os.tmpdir(), "jest-test-fs-watch-recursive-add-file"),
- refresh: () => {
- if (fs.existsSync(tmpdir.path)) {
- fs.rmSync(tmpdir.path, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir.path, { recursive: true });
- },
- };
-
- beforeEach(() => {
- tmpdir.refresh();
- });
-
- it("should detect file added to already watching folder", done => {
- const rootDirectory = fs.mkdtempSync(tmpdir.path + path.sep);
- const testDirectory = path.join(rootDirectory, "test-1");
- fs.mkdirSync(testDirectory);
-
- const testFile = path.join(testDirectory, "file-1.txt");
-
- const watcher = fs.watch(testDirectory, { recursive: true });
- let watcherClosed = false;
-
- watcher.on("change", function (event, filename) {
- expect(event).toBe("rename");
-
- if (filename === path.basename(testFile)) {
- watcher.close();
- watcherClosed = true;
- expect(watcherClosed).toBe(true);
- done();
- }
- });
-
- // Do the write with a delay to ensure that the OS is ready to notify us.
- setTimeout(
- () => {
- fs.writeFileSync(testFile, "world");
- },
- process.platform === "win32" ? 200 : 100,
- );
- });
-}
-
-//<#END_FILE: test-fs-watch-recursive-add-file.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-add-folder.test.js b/test/js/node/test/parallel/fs-watch-recursive-add-folder.test.js
deleted file mode 100644
index dbe75002f5..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-add-folder.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-fs-watch-recursive-add-folder.js
-//#SHA1: 4c2908ccc8502f5f760963a9b9a6db6ddadd4c1c
-//-----------------
-"use strict";
-
-const { setTimeout } = require("timers/promises");
-const assert = require("assert");
-const path = require("path");
-const fs = require("fs");
-const os = require("os");
-
-const isIBMi = os.platform() === "os400";
-const isAIX = os.platform() === "aix";
-
-if (isIBMi) {
- it.skip("IBMi does not support `fs.watch()`", () => {});
-} else if (isAIX) {
- it.skip("folder watch capability is limited in AIX.", () => {});
-} else {
- const testDir = fs.mkdtempSync(path.join(os.tmpdir(), "test-"));
-
- afterAll(() => {
- fs.rmSync(testDir, { recursive: true, force: true });
- });
-
- test("Add a folder to already watching folder", async () => {
- // Add a folder to already watching folder
-
- const rootDirectory = fs.mkdtempSync(path.join(testDir, "root-"));
- const testDirectory = path.join(rootDirectory, "test-2");
- fs.mkdirSync(testDirectory);
-
- const testFile = path.join(testDirectory, "folder-2");
-
- const watcher = fs.watch(testDirectory, { recursive: true });
- let watcherClosed = false;
-
- const watchPromise = new Promise(resolve => {
- watcher.on("change", function (event, filename) {
- expect(event).toBe("rename");
-
- if (filename === path.basename(testFile)) {
- watcher.close();
- watcherClosed = true;
- resolve();
- }
- });
- });
-
- await setTimeout(100);
- fs.mkdirSync(testFile);
-
- await watchPromise;
-
- expect(watcherClosed).toBe(true);
- });
-}
-
-//<#END_FILE: test-fs-watch-recursive-add-folder.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-assert-leaks.test.js b/test/js/node/test/parallel/fs-watch-recursive-assert-leaks.test.js
deleted file mode 100644
index 69ec1c857c..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-assert-leaks.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-fs-watch-recursive-assert-leaks.js
-//#SHA1: 316f1b184840ce5a8f2f92f4ab205038f4acaf9d
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-const { setTimeout } = require('timers/promises');
-
-const testDir = path.join(os.tmpdir(), 'test-fs-watch-recursive-assert-leaks');
-
-beforeAll(() => {
- if (fs.existsSync(testDir)) {
- fs.rmSync(testDir, { recursive: true, force: true });
- }
- fs.mkdirSync(testDir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(testDir, { recursive: true, force: true });
-});
-
-// Skip test for IBMi and AIX
-const isIBMi = process.platform === 'os400';
-const isAIX = process.platform === 'aix';
-
-if (isIBMi) {
- test.skip('IBMi does not support `fs.watch()`', () => {});
-} else if (isAIX) {
- test.skip('folder watch capability is limited in AIX', () => {});
-} else {
- test('recursive watch does not leak handles', async () => {
- const rootDirectory = fs.mkdtempSync(path.join(testDir, 'root-'));
- const testDirectory = path.join(rootDirectory, 'test-7');
- const filePath = path.join(testDirectory, 'only-file.txt');
- fs.mkdirSync(testDirectory);
-
- let watcherClosed = false;
- const watcher = fs.watch(testDirectory, { recursive: true });
-
- const watchPromise = new Promise((resolve) => {
- watcher.on('change', async (event, filename) => {
- await setTimeout(100);
- if (filename === path.basename(filePath)) {
- watcher.close();
- watcherClosed = true;
- resolve();
- }
- await setTimeout(100);
- expect(process._getActiveHandles().some((handle) => handle.constructor.name === 'StatWatcher')).toBe(false);
- });
- });
-
- // Do the write with a delay to ensure that the OS is ready to notify us.
- await setTimeout(200);
- fs.writeFileSync(filePath, 'content');
-
- await watchPromise;
- expect(watcherClosed).toBe(true);
- }, 10000); // Increased timeout to 10 seconds
-}
-
-//<#END_FILE: test-fs-watch-recursive-assert-leaks.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-linux-parallel-remove.test.js b/test/js/node/test/parallel/fs-watch-recursive-linux-parallel-remove.test.js
deleted file mode 100644
index b109622f57..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-linux-parallel-remove.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-fs-watch-recursive-linux-parallel-remove.js
-//#SHA1: ed10536d8d54febe24a3dcf494a26eab06bc4f66
-//-----------------
-"use strict";
-
-const path = require("node:path");
-const fs = require("node:fs");
-const { spawn } = require("node:child_process");
-const os = require("node:os");
-
-// Skip test if not running on Linux
-if (os.platform() !== "linux") {
- test.skip("This test can run only on Linux", () => {});
-} else {
- // Test that the watcher do not crash if the file "disappears" while
- // watch is being set up.
-
- let testDir;
- let watcher;
-
- beforeEach(() => {
- testDir = fs.mkdtempSync(path.join(os.tmpdir(), "test-"));
- });
-
- afterEach(() => {
- if (watcher) {
- watcher.close();
- }
- fs.rmSync(testDir, { recursive: true, force: true });
- });
-
- test("fs.watch does not crash on parallel file removal", done => {
- watcher = fs.watch(testDir, { recursive: true });
- watcher.on("change", function (event, filename) {
- // This console.log makes the error happen
- // do not remove
- console.log(filename, event);
- });
-
- const testFile = path.join(testDir, "a");
- const child = spawn(
- process.argv[0],
- [
- "-e",
- `const fs = require('node:fs'); for (let i = 0; i < 10000; i++) { const fd = fs.openSync('${testFile}', 'w'); fs.writeSync(fd, Buffer.from('hello')); fs.rmSync('${testFile}') }`,
- ],
- {
- stdio: "inherit",
- },
- );
-
- child.on("exit", function () {
- watcher.close();
- done();
- });
- });
-}
-
-//<#END_FILE: test-fs-watch-recursive-linux-parallel-remove.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-sync-write.test.js b/test/js/node/test/parallel/fs-watch-recursive-sync-write.test.js
deleted file mode 100644
index fa80c9a8e3..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-sync-write.test.js
+++ /dev/null
@@ -1,63 +0,0 @@
-//#FILE: test-fs-watch-recursive-sync-write.js
-//#SHA1: 436087aa83502744252800b9a93dbe88a4ca3822
-//-----------------
-'use strict';
-
-const fs = require('node:fs');
-const path = require('node:path');
-const os = require('os');
-
-const tmpDir = path.join(os.tmpdir(), 'test-fs-watch-recursive-sync-write');
-const filename = path.join(tmpDir, 'test.file');
-
-beforeAll(() => {
- if (fs.existsSync(tmpDir)) {
- fs.rmSync(tmpDir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpDir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpDir, { recursive: true, force: true });
-});
-
-// Skip test for IBMi and AIX
-const isIBMi = process.platform === 'os400';
-const isAIX = process.platform === 'aix';
-
-if (isIBMi) {
- test.skip('IBMi does not support `fs.watch()`', () => {});
-} else if (isAIX) {
- test.skip('folder watch capability is limited in AIX', () => {});
-} else {
- test('fs.watch detects file creation with recursive option', (done) => {
- const timeout = setTimeout(() => {
- done(new Error('timed out'));
- }, 30000);
-
- function doWatch() {
- const watcher = fs.watch(tmpDir, { recursive: true }, (eventType, _filename) => {
- clearTimeout(timeout);
- watcher.close();
- expect(eventType).toBe('rename');
- expect(path.join(tmpDir, _filename)).toBe(filename);
- done();
- });
-
- // Do the write with a delay to ensure that the OS is ready to notify us.
- setTimeout(() => {
- fs.writeFileSync(filename, 'foobar2');
- }, 200);
- }
-
- if (process.platform === 'darwin') {
- // On macOS delay watcher start to avoid leaking previous events.
- // Refs: https://github.com/libuv/libuv/pull/4503
- setTimeout(doWatch, 100);
- } else {
- doWatch();
- }
- }, 35000); // Increase timeout to account for the 30 second timeout in the test
-}
-
-//<#END_FILE: test-fs-watch-recursive-sync-write.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-update-file.test.js b/test/js/node/test/parallel/fs-watch-recursive-update-file.test.js
deleted file mode 100644
index 331df95da8..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-update-file.test.js
+++ /dev/null
@@ -1,48 +0,0 @@
-//#FILE: test-fs-watch-recursive-update-file.js
-//#SHA1: d197449fc5f430b9ce49e7f75b57a44dd4f2259a
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const testDir = path.join(os.tmpdir(), 'test-fs-watch-recursive-update-file');
-
-beforeAll(() => {
- if (fs.existsSync(testDir)) {
- fs.rmSync(testDir, { recursive: true, force: true });
- }
- fs.mkdirSync(testDir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(testDir, { recursive: true, force: true });
-});
-
-test('Watch a folder and update an already existing file in it', (done) => {
- const rootDirectory = fs.mkdtempSync(path.join(testDir, 'test-'));
- const testDirectory = path.join(rootDirectory, 'test-0');
- fs.mkdirSync(testDirectory);
-
- const testFile = path.join(testDirectory, 'file-1.txt');
- fs.writeFileSync(testFile, 'hello');
-
- const watcher = fs.watch(testDirectory, { recursive: true });
-
- watcher.on('change', (event, filename) => {
- expect(event === 'change' || event === 'rename').toBe(true);
-
- if (filename === path.basename(testFile)) {
- watcher.close();
- done();
- }
- });
-
- // Do the write with a delay to ensure that the OS is ready to notify us.
- setTimeout(() => {
- fs.writeFileSync(testFile, 'hello');
- }, 200);
-}, 10000); // Increased timeout to allow for file system operations
-
-//<#END_FILE: test-fs-watch-recursive-update-file.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-validate.test.js b/test/js/node/test/parallel/fs-watch-recursive-validate.test.js
deleted file mode 100644
index aeed19b67d..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-validate.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-fs-watch-recursive-validate.js
-//#SHA1: eb5d9ff1caac7f9d4acf694c43e4f634f538befb
-//-----------------
-"use strict";
-
-const path = require("path");
-const fs = require("fs");
-const os = require("os");
-
-const isIBMi = process.platform === "os400";
-const isAIX = process.platform === "aix";
-const isWindows = process.platform === "win32";
-const isOSX = process.platform === "darwin";
-
-if (isIBMi) {
- test.skip("IBMi does not support `fs.watch()`", () => {});
-} else if (isAIX) {
- test.skip("folder watch capability is limited in AIX.", () => {});
-} else {
- const tmpdir = {
- path: path.join(os.tmpdir(), "jest-fs-watch-recursive-validate"),
- refresh: () => {
- if (fs.existsSync(tmpdir.path)) {
- fs.rmSync(tmpdir.path, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir.path, { recursive: true });
- },
- };
-
- beforeEach(() => {
- tmpdir.refresh();
- });
-
- test("Handle non-boolean values for options.recursive", async () => {
- if (!isWindows && !isOSX) {
- expect(() => {
- const testsubdir = fs.mkdtempSync(tmpdir.path + path.sep);
- fs.watch(testsubdir, { recursive: "1" });
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- message: expect.any(String),
- }),
- );
- }
- });
-}
-
-//<#END_FILE: test-fs-watch-recursive-validate.js
diff --git a/test/js/node/test/parallel/fs-watch-recursive-watch-file.test.js b/test/js/node/test/parallel/fs-watch-recursive-watch-file.test.js
deleted file mode 100644
index bf7b6e0212..0000000000
--- a/test/js/node/test/parallel/fs-watch-recursive-watch-file.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-//#FILE: test-fs-watch-recursive-watch-file.js
-//#SHA1: 1f06958f6f645cb5c80b424a24b046f107ab83ae
-//-----------------
-"use strict";
-
-const path = require("path");
-const fs = require("fs");
-const os = require("os");
-
-const isIBMi = os.platform() === "os400";
-const isAIX = os.platform() === "aix";
-
-if (isIBMi) {
- test.skip("IBMi does not support `fs.watch()`");
-}
-
-// fs-watch on folders have limited capability in AIX.
-// The testcase makes use of folder watching, and causes
-// hang. This behavior is documented. Skip this for AIX.
-
-if (isAIX) {
- test.skip("folder watch capability is limited in AIX.");
-}
-
-const platformTimeout = ms => ms * (process.platform === "win32" ? 2 : 1);
-
-test("Watch a file (not a folder) using fs.watch", async () => {
- // Create a temporary directory for testing
- const testDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "test-"));
- const rootDirectory = await fs.promises.mkdtemp(path.join(testDir, path.sep));
- const testDirectory = path.join(rootDirectory, "test-6");
- await fs.promises.mkdir(testDirectory);
-
- const filePath = path.join(testDirectory, "only-file.txt");
- await fs.promises.writeFile(filePath, "hello");
-
- let watcherClosed = false;
- let interval;
-
- const watcher = fs.watch(filePath, { recursive: true });
-
- const watchPromise = new Promise(resolve => {
- watcher.on("change", function (event, filename) {
- expect(event).toBe("change");
-
- if (filename === path.basename(filePath)) {
- clearInterval(interval);
- interval = null;
- watcher.close();
- watcherClosed = true;
- resolve();
- }
- });
- });
-
- interval = setInterval(() => {
- fs.writeFileSync(filePath, "world");
- }, platformTimeout(10));
-
- await watchPromise;
-
- expect(watcherClosed).toBe(true);
- expect(interval).toBeNull();
-});
-
-//<#END_FILE: test-fs-watch-recursive-watch-file.js
diff --git a/test/js/node/test/parallel/fs-watch-ref-unref.test.js b/test/js/node/test/parallel/fs-watch-ref-unref.test.js
deleted file mode 100644
index c8d92a6eaa..0000000000
--- a/test/js/node/test/parallel/fs-watch-ref-unref.test.js
+++ /dev/null
@@ -1,32 +0,0 @@
-//#FILE: test-fs-watch-ref-unref.js
-//#SHA1: ffceabfd7f8fef655b05735b8bba7fb059609980
-//-----------------
-"use strict";
-
-const fs = require("fs");
-
-if (process.platform === "os400") {
- test.skip("IBMi does not support `fs.watch()`");
-}
-
-test("fs.watch() can be unref()ed and ref()ed", () => {
- const watcher = fs.watch(__filename, () => {
- // This callback should not be called
- expect(true).toBe(false);
- });
-
- watcher.unref();
-
- return new Promise(resolve => {
- setTimeout(
- () => {
- watcher.ref();
- watcher.unref();
- resolve();
- },
- process.platform === "win32" ? 100 : 50,
- );
- });
-});
-
-//<#END_FILE: test-fs-watch-ref-unref.js
diff --git a/test/js/node/test/parallel/fs-watch-stop-sync.test.js b/test/js/node/test/parallel/fs-watch-stop-sync.test.js
deleted file mode 100644
index fe1eae0f1c..0000000000
--- a/test/js/node/test/parallel/fs-watch-stop-sync.test.js
+++ /dev/null
@@ -1,27 +0,0 @@
-//#FILE: test-fs-watch-stop-sync.js
-//#SHA1: 8285d2bd43d2f9be7be525417cf51f9336b2f379
-//-----------------
-"use strict";
-
-// This test checks that the `stop` event is emitted asynchronously.
-//
-// If it isn't asynchronous, then the listener will be called during the
-// execution of `watch.stop()`. That would be a bug.
-//
-// If it is asynchronous, then the listener will be removed before the event is
-// emitted.
-
-const fs = require("fs");
-
-test("stop event is emitted asynchronously", () => {
- const listener = jest.fn();
-
- const watch = fs.watchFile(__filename, jest.fn());
- watch.once("stop", listener);
- watch.stop();
- watch.removeListener("stop", listener);
-
- expect(listener).not.toHaveBeenCalled();
-});
-
-//<#END_FILE: test-fs-watch-stop-sync.js
diff --git a/test/js/node/test/parallel/fs-watch.test.js b/test/js/node/test/parallel/fs-watch.test.js
deleted file mode 100644
index 117b2611dc..0000000000
--- a/test/js/node/test/parallel/fs-watch.test.js
+++ /dev/null
@@ -1,122 +0,0 @@
-//#FILE: test-fs-watch.js
-//#SHA1: 07373db00b057e796555cac6f75973e9e4358284
-//-----------------
-'use strict';
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const isIBMi = process.platform === 'os400';
-const isLinux = process.platform === 'linux';
-const isMacOS = process.platform === 'darwin';
-const isWindows = process.platform === 'win32';
-const isAIX = process.platform === 'aix';
-
-if (isIBMi) {
- test.skip('IBMi does not support `fs.watch()`', () => {});
-} else {
- const tmpdir = path.join(os.tmpdir(), 'test-fs-watch');
-
- class WatchTestCase {
- constructor(shouldInclude, dirName, fileName, field) {
- this.dirName = dirName;
- this.fileName = fileName;
- this.field = field;
- this.shouldSkip = !shouldInclude;
- }
- get dirPath() { return path.join(tmpdir, this.dirName); }
- get filePath() { return path.join(this.dirPath, this.fileName); }
- }
-
- const cases = [
- new WatchTestCase(
- isLinux || isMacOS || isWindows || isAIX,
- 'watch1',
- 'foo',
- 'filePath'
- ),
- new WatchTestCase(
- isLinux || isMacOS || isWindows,
- 'watch2',
- 'bar',
- 'dirPath'
- ),
- ];
-
- beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
- });
-
- afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- });
-
- function doWatchTest(testCase) {
- return new Promise((resolve, reject) => {
- let interval;
- const pathToWatch = testCase[testCase.field];
- const watcher = fs.watch(pathToWatch);
-
- watcher.on('error', (err) => {
- if (interval) {
- clearInterval(interval);
- interval = null;
- }
- reject(err);
- });
-
- watcher.on('change', (eventType, argFilename) => {
- if (interval) {
- clearInterval(interval);
- interval = null;
- }
- if (isMacOS)
- expect(['rename', 'change'].includes(eventType)).toBe(true);
- else
- expect(eventType).toBe('change');
- expect(argFilename).toBe(testCase.fileName);
-
- watcher.close();
- watcher.close(); // Closing a closed watcher should be a noop
- resolve();
- });
-
- const content2 = Date.now() + testCase.fileName.toUpperCase().repeat(1e4);
- interval = setInterval(() => {
- fs.writeFileSync(testCase.filePath, '');
- fs.writeFileSync(testCase.filePath, content2);
- }, 100);
- });
- }
-
- test.each(cases.filter(testCase => !testCase.shouldSkip))(
- 'Watch test for $dirName',
- async (testCase) => {
- fs.mkdirSync(testCase.dirPath, { recursive: true });
- const content1 = Date.now() + testCase.fileName.toLowerCase().repeat(1e4);
- fs.writeFileSync(testCase.filePath, content1);
-
- if (isMacOS) {
- await new Promise(resolve => setTimeout(resolve, 100));
- }
-
- await doWatchTest(testCase);
- },
- 30000 // Increase timeout to 30 seconds
- );
-
- test('fs.watch throws for invalid inputs', () => {
- [false, 1, {}, [], null, undefined].forEach((input) => {
- expect(() => fs.watch(input, () => {})).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_TYPE',
- name: 'TypeError',
- message: expect.any(String)
- }));
- });
- });
-}
-
-//<#END_FILE: test-fs-watch.js
diff --git a/test/js/node/test/parallel/fs-watchfile-bigint.test.js b/test/js/node/test/parallel/fs-watchfile-bigint.test.js
deleted file mode 100644
index bf4c61d5b9..0000000000
--- a/test/js/node/test/parallel/fs-watchfile-bigint.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-//#FILE: test-fs-watchfile-bigint.js
-//#SHA1: 3b2e1f656e95137ca75dedd42e71ba49e6405441
-//-----------------
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const os = require('os');
-
-const tmpdir = path.join(os.tmpdir(), 'test-fs-watchfile-bigint');
-const enoentFile = path.join(tmpdir, 'non-existent-file');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('fs.watchFile with bigint option', (done) => {
- let fileExists = false;
- const options = { interval: 0, bigint: true };
-
- const watcher = fs.watchFile(enoentFile, options, (curr, prev) => {
- if (!fileExists) {
- // If the file does not exist, all the fields should be zero and the date
- // fields should be UNIX EPOCH time
- expect(curr.ino).toBe(0n);
- expect(prev.ino).toBe(0n);
- // Create the file now, so that the callback will be called back once the
- // event loop notices it.
- fs.closeSync(fs.openSync(enoentFile, 'w'));
- fileExists = true;
- } else {
- // If the ino (inode) value is greater than zero, it means that the file
- // is present in the filesystem and it has a valid inode number.
- expect(curr.ino).toBeGreaterThan(0n);
- // As the file just got created, previous ino value should be lesser than
- // or equal to zero (non-existent file).
- expect(prev.ino).toBeLessThanOrEqual(0n);
- // Stop watching the file
- fs.unwatchFile(enoentFile);
- watcher.stop(); // Stopping a stopped watcher should be a noop
- done();
- }
- });
-
- // 'stop' should only be emitted once - stopping a stopped watcher should
- // not trigger a 'stop' event.
- watcher.on('stop', jest.fn());
-
- // Ensure the test times out if the callback is not called twice
- jest.setTimeout(10000);
-});
-
-//<#END_FILE: test-fs-watchfile-bigint.js
diff --git a/test/js/node/test/parallel/fs-write-file-buffer.test.js b/test/js/node/test/parallel/fs-write-file-buffer.test.js
deleted file mode 100644
index 774f93cfb8..0000000000
--- a/test/js/node/test/parallel/fs-write-file-buffer.test.js
+++ /dev/null
@@ -1,71 +0,0 @@
-//#FILE: test-fs-write-file-buffer.js
-//#SHA1: f721ad0f6969d6cf1ba78f96ccf9600a7f93458d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const path = require("path");
-
-let data = [
- "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcH",
- "Bw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/",
- "2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4e",
- "Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAAQABADASIAAhEBAxEB/8QA",
- "HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF",
- "BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK",
- "FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1",
- "dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG",
- "x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEB",
- "AQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC",
- "AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRom",
- "JygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE",
- "hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU",
- "1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDhfBUFl/wk",
- "OmPqKJJZw3aiZFBw4z93jnkkc9u9dj8XLfSI/EBt7DTo7ea2Ox5YXVo5FC7g",
- "Tjq24nJPXNVtO0KATRvNHCIg3zoWJWQHqp+o4pun+EtJ0zxBq8mnLJa2d1L5",
- "0NvnKRjJBUE5PAx3NYxxUY0pRtvYHSc5Ka2X9d7H/9k=",
-];
-
-data = data.join("\n");
-
-let tmpdir;
-
-beforeEach(() => {
- tmpdir = fs.mkdtempSync(path.join(process.env.TEST_TMPDIR || "/tmp", "test-fs-write-file-buffer-"));
-});
-
-afterEach(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test("writeFileSync with Buffer", () => {
- const buf = Buffer.from(data, "base64");
- const testFile = path.join(tmpdir, "test.jpg");
-
- fs.writeFileSync(testFile, buf);
-
- expect(fs.existsSync(testFile)).toBe(true);
- expect(fs.readFileSync(testFile)).toEqual(buf);
-});
-
-//<#END_FILE: test-fs-write-file-buffer.js
diff --git a/test/js/node/test/parallel/fs-write-no-fd.test.js b/test/js/node/test/parallel/fs-write-no-fd.test.js
deleted file mode 100644
index 6750c80c46..0000000000
--- a/test/js/node/test/parallel/fs-write-no-fd.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-fs-write-no-fd.js
-//#SHA1: eade06241743a0d7e72b5239633e1ddd947f3a28
-//-----------------
-"use strict";
-const fs = require("fs");
-
-test("fs.write with null fd and Buffer throws TypeError", () => {
- expect(() => {
- fs.write(null, Buffer.allocUnsafe(1), 0, 1, () => {});
- }).toThrow(
- expect.objectContaining({
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-});
-
-test("fs.write with null fd and string throws TypeError", () => {
- expect(() => {
- fs.write(null, "1", 0, 1, () => {});
- }).toThrow(
- expect.objectContaining({
- name: "TypeError",
- message: expect.any(String),
- }),
- );
-});
-
-//<#END_FILE: test-fs-write-no-fd.js
diff --git a/test/js/node/test/parallel/fs-write-stream-close-without-callback.test.js b/test/js/node/test/parallel/fs-write-stream-close-without-callback.test.js
deleted file mode 100644
index 969a581bb5..0000000000
--- a/test/js/node/test/parallel/fs-write-stream-close-without-callback.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-fs-write-stream-close-without-callback.js
-//#SHA1: 63e0c345b440c8cfb157aa84340f387cf314e20f
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const tmpdir = path.join(os.tmpdir(), "test-fs-write-stream-close-without-callback");
-
-beforeEach(() => {
- // Create a fresh temporary directory before each test
- if (!fs.existsSync(tmpdir)) {
- fs.mkdirSync(tmpdir, { recursive: true });
- }
-});
-
-afterEach(() => {
- // Clean up the temporary directory after each test
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
-});
-
-test("fs.WriteStream can be closed without a callback", () => {
- const filePath = path.join(tmpdir, "nocallback");
- const s = fs.createWriteStream(filePath);
-
- s.end("hello world");
- s.close();
-
- // We don't need to assert anything here as the test is checking
- // that the above operations don't throw an error
- expect(true).toBe(true);
-});
-
-//<#END_FILE: test-fs-write-stream-close-without-callback.js
diff --git a/test/js/node/test/parallel/fs-write-stream-encoding.test.js b/test/js/node/test/parallel/fs-write-stream-encoding.test.js
deleted file mode 100644
index ee0135bd36..0000000000
--- a/test/js/node/test/parallel/fs-write-stream-encoding.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-fs-write-stream-encoding.js
-//#SHA1: a2f61bd26151411263b933d254ec75a7ca4056fc
-//-----------------
-'use strict';
-const fs = require('fs');
-const stream = require('stream');
-const path = require('path');
-const os = require('os');
-
-const fixturesPath = path.join(__dirname, '..', 'fixtures');
-const tmpdir = path.join(os.tmpdir(), 'test-fs-write-stream-encoding');
-
-const firstEncoding = 'base64';
-const secondEncoding = 'latin1';
-
-const examplePath = path.join(fixturesPath, 'x.txt');
-const dummyPath = path.join(tmpdir, 'x.txt');
-
-beforeAll(() => {
- if (fs.existsSync(tmpdir)) {
- fs.rmSync(tmpdir, { recursive: true, force: true });
- }
- fs.mkdirSync(tmpdir, { recursive: true });
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test('write stream encoding', (done) => {
- const exampleReadStream = fs.createReadStream(examplePath, {
- encoding: firstEncoding
- });
-
- const dummyWriteStream = fs.createWriteStream(dummyPath, {
- encoding: firstEncoding
- });
-
- exampleReadStream.pipe(dummyWriteStream).on('finish', () => {
- const assertWriteStream = new stream.Writable({
- write: function(chunk, enc, next) {
- const expected = Buffer.from('xyz\n');
- expect(chunk).toEqual(expected);
- next();
- }
- });
- assertWriteStream.setDefaultEncoding(secondEncoding);
-
- fs.createReadStream(dummyPath, {
- encoding: secondEncoding
- }).pipe(assertWriteStream).on('finish', done);
- });
-});
-
-//<#END_FILE: test-fs-write-stream-encoding.js
diff --git a/test/js/node/test/parallel/fs-write-stream-end.test.js b/test/js/node/test/parallel/fs-write-stream-end.test.js
deleted file mode 100644
index a73488cb3b..0000000000
--- a/test/js/node/test/parallel/fs-write-stream-end.test.js
+++ /dev/null
@@ -1,76 +0,0 @@
-//#FILE: test-fs-write-stream-end.js
-//#SHA1: a4194cfb1f416f5fddd5edc55b7d867db14a5320
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const path = require("path");
-
-const tmpdir = path.join(__dirname, "tmp");
-
-beforeAll(() => {
- if (!fs.existsSync(tmpdir)) {
- fs.mkdirSync(tmpdir, { recursive: true });
- }
-});
-
-afterAll(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test("end without data", done => {
- const file = path.join(tmpdir, "write-end-test0.txt");
- const stream = fs.createWriteStream(file);
- stream.end();
- stream.on("close", () => {
- done();
- });
-});
-
-test("end with data", done => {
- const file = path.join(tmpdir, "write-end-test1.txt");
- const stream = fs.createWriteStream(file);
- stream.end("a\n", "utf8");
- stream.on("close", () => {
- const content = fs.readFileSync(file, "utf8");
- expect(content).toBe("a\n");
- done();
- });
-});
-
-test("end triggers open and finish events", done => {
- const file = path.join(tmpdir, "write-end-test2.txt");
- const stream = fs.createWriteStream(file);
- stream.end();
-
- let calledOpen = false;
- stream.on("open", () => {
- calledOpen = true;
- });
- stream.on("finish", () => {
- expect(calledOpen).toBe(true);
- done();
- });
-});
-
-//<#END_FILE: test-fs-write-stream-end.js
diff --git a/test/js/node/test/parallel/fs-write-sync.test.js b/test/js/node/test/parallel/fs-write-sync.test.js
deleted file mode 100644
index 5e277e75e5..0000000000
--- a/test/js/node/test/parallel/fs-write-sync.test.js
+++ /dev/null
@@ -1,66 +0,0 @@
-//#FILE: test-fs-write-sync.js
-//#SHA1: 4ae5fa7550eefe258b9c1de798f4a4092e9d15d1
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const filename = path.join(os.tmpdir(), "write.txt");
-
-beforeEach(() => {
- try {
- fs.unlinkSync(filename);
- } catch (err) {
- // Ignore errors if file doesn't exist
- }
-});
-
-test("fs.writeSync with various parameter combinations", () => {
- const parameters = [Buffer.from("bár"), 0, Buffer.byteLength("bár")];
-
- // The first time fs.writeSync is called with all parameters provided.
- // After that, each pop in the cycle removes the final parameter. So:
- // - The 2nd time fs.writeSync with a buffer, without the length parameter.
- // - The 3rd time fs.writeSync with a buffer, without the offset and length
- // parameters.
- while (parameters.length > 0) {
- const fd = fs.openSync(filename, "w");
-
- let written = fs.writeSync(fd, "");
- expect(written).toBe(0);
-
- fs.writeSync(fd, "foo");
-
- written = fs.writeSync(fd, ...parameters);
- expect(written).toBeGreaterThan(3);
- fs.closeSync(fd);
-
- expect(fs.readFileSync(filename, "utf-8")).toBe("foobár");
-
- parameters.pop();
- }
-});
-
-//<#END_FILE: test-fs-write-sync.js
diff --git a/test/js/node/test/parallel/fs-writestream-open-write.test.js b/test/js/node/test/parallel/fs-writestream-open-write.test.js
deleted file mode 100644
index c641c31ce8..0000000000
--- a/test/js/node/test/parallel/fs-writestream-open-write.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-fs-writestream-open-write.js
-//#SHA1: a4cb8508ae1f366c94442a43312a817f00b68de6
-//-----------------
-"use strict";
-
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-// Regression test for https://github.com/nodejs/node/issues/51993
-
-let tmpdir;
-
-beforeEach(() => {
- tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "test-fs-writestream-open-write-"));
-});
-
-afterEach(() => {
- fs.rmSync(tmpdir, { recursive: true, force: true });
-});
-
-test("fs.createWriteStream opens and writes correctly", done => {
- const file = path.join(tmpdir, "test-fs-writestream-open-write.txt");
-
- const w = fs.createWriteStream(file);
-
- w.on("open", () => {
- w.write("hello");
-
- process.nextTick(() => {
- w.write("world");
- w.end();
- });
- });
-
- w.on("close", () => {
- expect(fs.readFileSync(file, "utf8")).toBe("helloworld");
- fs.unlinkSync(file);
- done();
- });
-});
-
-//<#END_FILE: test-fs-writestream-open-write.js
diff --git a/test/js/node/test/parallel/global-customevent.test.js b/test/js/node/test/parallel/global-customevent.test.js
deleted file mode 100644
index 988e0cd447..0000000000
--- a/test/js/node/test/parallel/global-customevent.test.js
+++ /dev/null
@@ -1,19 +0,0 @@
-//#FILE: test-global-customevent.js
-//#SHA1: 754c1b6babd0e73fa3206c9c9179ff3a034eba9b
-//-----------------
-"use strict";
-
-// Global
-test("CustomEvent is defined globally", () => {
- expect(CustomEvent).toBeDefined();
-});
-
-test("CustomEvent is the same as internal CustomEvent", () => {
- // We can't use internal modules in Jest, so we'll skip this test
- // and add a comment explaining why.
- console.log("Skipping test for internal CustomEvent comparison");
- // The original test was:
- // strictEqual(CustomEvent, internalCustomEvent);
-});
-
-//<#END_FILE: test-global-customevent.js
diff --git a/test/js/node/test/parallel/global-domexception.test.js b/test/js/node/test/parallel/global-domexception.test.js
deleted file mode 100644
index 2ebf63c2fd..0000000000
--- a/test/js/node/test/parallel/global-domexception.test.js
+++ /dev/null
@@ -1,18 +0,0 @@
-//#FILE: test-global-domexception.js
-//#SHA1: 9a8d5eacea5ae98814fa6312b5f10089034c1ef4
-//-----------------
-"use strict";
-
-// This test checks the global availability and behavior of DOMException
-
-test("DOMException is a global function", () => {
- expect(typeof DOMException).toBe("function");
-});
-
-test("atob throws a DOMException for invalid input", () => {
- expect(() => {
- atob("我要抛错!");
- }).toThrow(DOMException);
-});
-
-//<#END_FILE: test-global-domexception.js
diff --git a/test/js/node/test/parallel/global-encoder.test.js b/test/js/node/test/parallel/global-encoder.test.js
deleted file mode 100644
index a9a928fb17..0000000000
--- a/test/js/node/test/parallel/global-encoder.test.js
+++ /dev/null
@@ -1,13 +0,0 @@
-//#FILE: test-global-encoder.js
-//#SHA1: 7397937d3493488fc47e8ba6ba8fcb4f5bdd97fa
-//-----------------
-"use strict";
-
-test("TextDecoder and TextEncoder are globally available", () => {
- const util = require("util");
-
- expect(TextDecoder).toBe(util.TextDecoder);
- expect(TextEncoder).toBe(util.TextEncoder);
-});
-
-//<#END_FILE: test-global-encoder.js
diff --git a/test/js/node/test/parallel/global-webcrypto.test.js b/test/js/node/test/parallel/global-webcrypto.test.js
deleted file mode 100644
index a936c6b593..0000000000
--- a/test/js/node/test/parallel/global-webcrypto.test.js
+++ /dev/null
@@ -1,27 +0,0 @@
-//#FILE: test-global-webcrypto.js
-//#SHA1: 3ae34178f201f6dfeb3ca5ec6e0914e6de63d64b
-//-----------------
-"use strict";
-
-const crypto = require("crypto");
-
-// Skip the test if crypto is not available
-if (!crypto) {
- test.skip("missing crypto", () => {});
-} else {
- describe("Global WebCrypto", () => {
- test("globalThis.crypto is crypto.webcrypto", () => {
- expect(globalThis.crypto).toBe(crypto.webcrypto);
- });
-
- test("Crypto is the constructor of crypto.webcrypto", () => {
- expect(Crypto).toBe(crypto.webcrypto.constructor);
- });
-
- test("SubtleCrypto is the constructor of crypto.webcrypto.subtle", () => {
- expect(SubtleCrypto).toBe(crypto.webcrypto.subtle.constructor);
- });
- });
-}
-
-//<#END_FILE: test-global-webcrypto.js
diff --git a/test/js/node/test/parallel/heap-prof-exec-argv.test.js b/test/js/node/test/parallel/heap-prof-exec-argv.test.js
deleted file mode 100644
index aa64858dbb..0000000000
--- a/test/js/node/test/parallel/heap-prof-exec-argv.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-heap-prof-exec-argv.js
-//#SHA1: 77c3a447116b06f03f52fd56efe928699ba6d60d
-//-----------------
-"use strict";
-
-// Tests --heap-prof generates a heap profile from worker
-// when execArgv is set.
-
-const fixtures = require("../common/fixtures");
-const assert = require("assert");
-const { spawnSync } = require("child_process");
-const tmpdir = require("../common/tmpdir");
-const { getHeapProfiles, verifyFrames } = require("../common/prof");
-
-// Skip the test if inspector is disabled
-const isInspectorEnabled = process.execArgv.some(arg => arg.startsWith("--inspect"));
-if (!isInspectorEnabled) {
- test.skip("Inspector is disabled", () => {});
-} else {
- test("--heap-prof generates a heap profile from worker when execArgv is set", () => {
- tmpdir.refresh();
- const output = spawnSync(process.execPath, [fixtures.path("workload", "allocation-worker-argv.js")], {
- cwd: tmpdir.path,
- env: {
- ...process.env,
- HEAP_PROF_INTERVAL: "128",
- },
- });
-
- if (output.status !== 0) {
- console.log(output.stderr.toString());
- }
-
- expect(output.status).toBe(0);
-
- const profiles = getHeapProfiles(tmpdir.path);
- expect(profiles.length).toBe(1);
-
- verifyFrames(output, profiles[0], "runAllocation");
- });
-}
-
-//<#END_FILE: test-heap-prof-exec-argv.js
diff --git a/test/js/node/test/parallel/http-abort-before-end.test.js b/test/js/node/test/parallel/http-abort-before-end.test.js
deleted file mode 100644
index 0df59e1fcf..0000000000
--- a/test/js/node/test/parallel/http-abort-before-end.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-//#FILE: test-http-abort-before-end.js
-//#SHA1: ccb82c66677f07f3ee815846261393edb8bfe5d4
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP request abort before end", async () => {
- const server = http.createServer(jest.fn());
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const req = http.request({
- method: "GET",
- host: "127.0.0.1",
- port: server.address().port,
- });
-
- const abortPromise = new Promise(resolve => {
- req.on("abort", resolve);
- });
-
- req.on("error", jest.fn());
-
- req.abort();
- req.end();
-
- await abortPromise;
-
- expect(server.listeners("request")[0]).not.toHaveBeenCalled();
- expect(req.listeners("error")[0]).not.toHaveBeenCalled();
-
- await new Promise(resolve => {
- server.close(resolve);
- });
-});
-
-//<#END_FILE: test-http-abort-before-end.js
diff --git a/test/js/node/test/parallel/http-abort-queued.test.js b/test/js/node/test/parallel/http-abort-queued.test.js
deleted file mode 100644
index d5c7fea669..0000000000
--- a/test/js/node/test/parallel/http-abort-queued.test.js
+++ /dev/null
@@ -1,102 +0,0 @@
-//#FILE: test-http-abort-queued.js
-//#SHA1: e0fcd4a5eb0466a1e218147e8eb53714311a6f42
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-let complete;
-
-test("http abort queued request", async () => {
- const server = http.createServer((req, res) => {
- // We should not see the queued /thatotherone request within the server
- // as it should be aborted before it is sent.
- expect(req.url).toBe("/");
-
- res.writeHead(200);
- res.write("foo");
-
- complete =
- complete ||
- function () {
- res.end();
- };
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const agent = new http.Agent({ maxSockets: 1 });
- expect(Object.keys(agent.sockets)).toHaveLength(0);
-
- const options = {
- hostname: "localhost",
- port: server.address().port,
- method: "GET",
- path: "/",
- agent: agent,
- };
-
- const req1 = http.request(options);
- req1.on("response", res1 => {
- expect(Object.keys(agent.sockets)).toHaveLength(1);
- expect(Object.keys(agent.requests)).toHaveLength(0);
-
- const req2 = http.request({
- method: "GET",
- host: "localhost",
- port: server.address().port,
- path: "/thatotherone",
- agent: agent,
- });
- expect(Object.keys(agent.sockets)).toHaveLength(1);
- expect(Object.keys(agent.requests)).toHaveLength(1);
-
- // TODO(jasnell): This event does not appear to currently be triggered.
- // is this handler actually required?
- req2.on("error", err => {
- // This is expected in response to our explicit abort call
- expect(err.code).toBe("ECONNRESET");
- });
-
- req2.end();
- req2.abort();
-
- expect(Object.keys(agent.sockets)).toHaveLength(1);
- expect(Object.keys(agent.requests)).toHaveLength(1);
-
- res1.on("data", chunk => complete());
-
- res1.on("end", () => {
- setTimeout(() => {
- expect(Object.keys(agent.sockets)).toHaveLength(0);
- expect(Object.keys(agent.requests)).toHaveLength(0);
-
- server.close();
- }, 100);
- });
- });
-
- req1.end();
-});
-
-//<#END_FILE: test-http-abort-queued.js
diff --git a/test/js/node/test/parallel/http-agent-false.test.js b/test/js/node/test/parallel/http-agent-false.test.js
deleted file mode 100644
index c99f236785..0000000000
--- a/test/js/node/test/parallel/http-agent-false.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-http-agent-false.js
-//#SHA1: ba987050ea069a591615a69e341cf6f9c7298e5a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("http.request with agent: false and port: null", async () => {
- // Sending `agent: false` when `port: null` is also passed in (i.e. the result
- // of a `url.parse()` call with the default port used, 80 or 443), should not
- // result in an assertion error...
- const opts = {
- host: "127.0.0.1",
- port: null,
- path: "/",
- method: "GET",
- agent: false,
- };
-
- // We just want an "error" (no local HTTP server on port 80) or "response"
- // to happen (user happens ot have HTTP server running on port 80).
- // As long as the process doesn't crash from a C++ assertion then we're good.
- const req = http.request(opts);
-
- // Will be called by either the response event or error event, not both
- const oneResponse = jest.fn();
- req.on("response", oneResponse);
- req.on("error", oneResponse);
- req.end();
-
- // Wait for the request to complete
- await new Promise(resolve => {
- req.on("response", resolve);
- req.on("error", resolve);
- });
-
- // Check that oneResponse was called exactly once
- expect(oneResponse).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-http-agent-false.js
diff --git a/test/js/node/test/parallel/http-agent-no-protocol.test.js b/test/js/node/test/parallel/http-agent-no-protocol.test.js
deleted file mode 100644
index 99d0acc26f..0000000000
--- a/test/js/node/test/parallel/http-agent-no-protocol.test.js
+++ /dev/null
@@ -1,63 +0,0 @@
-//#FILE: test-http-agent-no-protocol.js
-//#SHA1: f1b40623163271a500c87971bf996466e006130e
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-test("http agent with no protocol", async () => {
- const serverCallback = jest.fn((req, res) => {
- res.end();
- });
-
- const server = http.createServer(serverCallback);
-
- await new Promise(resolve => {
- server.listen(0, "127.0.0.1", resolve);
- });
-
- const opts = url.parse(`http://127.0.0.1:${server.address().port}/`);
-
- // Remove the `protocol` field… the `http` module should fall back
- // to "http:", as defined by the global, default `http.Agent` instance.
- opts.agent = new http.Agent();
- opts.agent.protocol = null;
-
- const responseCallback = jest.fn(res => {
- res.resume();
- server.close();
- });
-
- await new Promise(resolve => {
- http.get(opts, res => {
- responseCallback(res);
- resolve();
- });
- });
-
- expect(serverCallback).toHaveBeenCalledTimes(1);
- expect(responseCallback).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-http-agent-no-protocol.js
diff --git a/test/js/node/test/parallel/http-agent-null.test.js b/test/js/node/test/parallel/http-agent-null.test.js
deleted file mode 100644
index c44c03f788..0000000000
--- a/test/js/node/test/parallel/http-agent-null.test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-//#FILE: test-http-agent-null.js
-//#SHA1: 65fb22d32bae2a7eecc4242b5b2d2d693849641c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("http.get with null agent", async () => {
- const server = http.createServer((req, res) => {
- res.end();
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const options = {
- agent: null,
- port: server.address().port,
- };
-
- const responsePromise = new Promise(resolve => {
- http.get(options, res => {
- res.resume();
- resolve(res);
- });
- });
-
- await expect(responsePromise).resolves.toBeDefined();
-
- await new Promise(resolve => {
- server.close(resolve);
- });
-});
-
-//<#END_FILE: test-http-agent-null.js
diff --git a/test/js/node/test/parallel/http-agent-uninitialized-with-handle.test.js b/test/js/node/test/parallel/http-agent-uninitialized-with-handle.test.js
deleted file mode 100644
index b78aacf5b6..0000000000
--- a/test/js/node/test/parallel/http-agent-uninitialized-with-handle.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-http-agent-uninitialized-with-handle.js
-//#SHA1: 828942acbc68f8fd92425ecdf0e754ab13b4baff
-//-----------------
-"use strict";
-
-const http = require("http");
-const net = require("net");
-
-test("http agent with uninitialized socket handle", done => {
- const agent = new http.Agent({
- keepAlive: true,
- });
- const socket = new net.Socket();
- // If _handle exists then internals assume a couple methods exist.
- socket._handle = {
- ref() {},
- readStart() {},
- };
-
- const server = http.createServer((req, res) => {
- res.end();
- });
-
- server.listen(0, () => {
- const req = new http.ClientRequest(`http://localhost:${server.address().port}/`);
-
- // Manually add the socket without a _handle.
- agent.freeSockets[agent.getName(req)] = [socket];
- // Now force the agent to use the socket and check that _handle exists before
- // calling asyncReset().
- agent.addRequest(req, {});
- req.on("response", () => {
- server.close();
- done();
- });
- req.end();
- });
-
- expect(server).toHaveProperty("listen");
- expect(server).toHaveProperty("close");
-});
-
-//<#END_FILE: test-http-agent-uninitialized-with-handle.js
diff --git a/test/js/node/test/parallel/http-agent-uninitialized.test.js b/test/js/node/test/parallel/http-agent-uninitialized.test.js
deleted file mode 100644
index 43e447a063..0000000000
--- a/test/js/node/test/parallel/http-agent-uninitialized.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-//#FILE: test-http-agent-uninitialized.js
-//#SHA1: 00034f4963a5620af8a58e68c262c92ea9ec982b
-//-----------------
-"use strict";
-
-const http = require("http");
-const net = require("net");
-
-test("http agent handles uninitialized socket", done => {
- const agent = new http.Agent({
- keepAlive: true,
- });
- const socket = new net.Socket();
-
- const server = http
- .createServer((req, res) => {
- res.end();
- })
- .listen(0, () => {
- const req = new http.ClientRequest(`http://localhost:${server.address().port}/`);
-
- // Manually add the socket without a _handle.
- agent.freeSockets[agent.getName(req)] = [socket];
- // Now force the agent to use the socket and check that _handle exists before
- // calling asyncReset().
- agent.addRequest(req, {});
- req.on("response", () => {
- server.close();
- done();
- });
- req.end();
- });
-
- expect(server).toBeDefined();
-});
-
-//<#END_FILE: test-http-agent-uninitialized.js
diff --git a/test/js/node/test/parallel/http-agent.test.js b/test/js/node/test/parallel/http-agent.test.js
deleted file mode 100644
index 900ad21d17..0000000000
--- a/test/js/node/test/parallel/http-agent.test.js
+++ /dev/null
@@ -1,97 +0,0 @@
-//#FILE: test-http-agent.js
-//#SHA1: c5bb5b1b47100659ac17ae6c4ba084c6974ddaa7
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const N = 4;
-const M = 4;
-
-let server;
-
-beforeEach(() => {
- server = http.Server((req, res) => {
- res.writeHead(200);
- res.end("hello world\n");
- });
-});
-
-afterEach(() => {
- server.close();
-});
-
-function makeRequests(outCount, inCount, shouldFail) {
- return new Promise(resolve => {
- const totalRequests = outCount * inCount;
- let completedRequests = 0;
-
- const onRequest = jest.fn(res => {
- completedRequests++;
- if (completedRequests === totalRequests) {
- resolve();
- }
-
- if (!shouldFail) {
- res.resume();
- }
- });
-
- server.listen(0, () => {
- const port = server.address().port;
- for (let i = 0; i < outCount; i++) {
- setTimeout(() => {
- for (let j = 0; j < inCount; j++) {
- const req = http.get({ port: port, path: "/" }, onRequest);
- if (shouldFail) {
- req.on("error", onRequest);
- } else {
- req.on("error", e => {
- throw e;
- });
- }
- }
- }, i);
- }
- });
- });
-}
-
-test("makeRequests successful", async () => {
- await makeRequests(N, M);
- expect(server.listenerCount("request")).toBe(1);
-});
-
-test("makeRequests with failing requests", async () => {
- const originalCreateConnection = http.Agent.prototype.createConnection;
-
- http.Agent.prototype.createConnection = function createConnection(_, cb) {
- process.nextTick(cb, new Error("nothing"));
- };
-
- await makeRequests(N, M, true);
-
- http.Agent.prototype.createConnection = originalCreateConnection;
-});
-
-//<#END_FILE: test-http-agent.js
diff --git a/test/js/node/test/parallel/http-bind-twice.test.js b/test/js/node/test/parallel/http-bind-twice.test.js
deleted file mode 100644
index 99917ffc27..0000000000
--- a/test/js/node/test/parallel/http-bind-twice.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http-bind-twice.js
-//#SHA1: 71319f0a5445d1ea7644e952ec4048d8996be1bc
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP server bind twice", async () => {
- const server1 = http.createServer(jest.fn());
- const server1ListenPromise = new Promise(resolve => {
- server1.listen(0, "127.0.0.1", resolve);
- });
-
- await server1ListenPromise;
-
- const server2 = http.createServer(jest.fn());
- const server2ErrorPromise = new Promise(resolve => {
- server2.on("error", resolve);
- });
-
- server2.listen(server1.address().port, "127.0.0.1");
-
- const error = await server2ErrorPromise;
-
- expect(error).toEqual(
- expect.objectContaining({
- code: "EADDRINUSE",
- message: expect.any(String),
- }),
- );
-
- await new Promise(resolve => server1.close(resolve));
-});
-
-//<#END_FILE: test-http-bind-twice.js
diff --git a/test/js/node/test/parallel/http-chunked-smuggling.test.js b/test/js/node/test/parallel/http-chunked-smuggling.test.js
deleted file mode 100644
index e1ab305b10..0000000000
--- a/test/js/node/test/parallel/http-chunked-smuggling.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-http-chunked-smuggling.js
-//#SHA1: c146d9dc37a522ac07d943b4c40b3301923659fa
-//-----------------
-"use strict";
-
-const http = require("http");
-const net = require("net");
-
-// Verify that invalid chunk extensions cannot be used to perform HTTP request
-// smuggling attacks.
-
-describe("HTTP Chunked Smuggling", () => {
- let server;
- let serverPort;
-
- beforeAll(done => {
- server = http.createServer((request, response) => {
- expect(request.url).not.toBe("/admin");
- response.end("hello world");
- });
-
- server.listen(0, () => {
- serverPort = server.address().port;
- done();
- });
- });
-
- afterAll(done => {
- server.close(done);
- });
-
- test("invalid chunk extensions", done => {
- const sock = net.connect(serverPort);
-
- sock.write(
- "" +
- "GET / HTTP/1.1\r\n" +
- "Host: localhost:8080\r\n" +
- "Transfer-Encoding: chunked\r\n" +
- "\r\n" +
- "2;\n" +
- "xx\r\n" +
- "4c\r\n" +
- "0\r\n" +
- "\r\n" +
- "GET /admin HTTP/1.1\r\n" +
- "Host: localhost:8080\r\n" +
- "Transfer-Encoding: chunked\r\n" +
- "\r\n" +
- "0\r\n" +
- "\r\n",
- );
-
- sock.resume();
- sock.on("end", () => {
- done();
- });
- });
-});
-
-//<#END_FILE: test-http-chunked-smuggling.js
diff --git a/test/js/node/test/parallel/http-client-abort2.test.js b/test/js/node/test/parallel/http-client-abort2.test.js
deleted file mode 100644
index 416be11173..0000000000
--- a/test/js/node/test/parallel/http-client-abort2.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http-client-abort2.js
-//#SHA1: 9accf5214e90cab96d06a59931e65718616b85f3
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("http client abort", async () => {
- const serverHandler = jest.fn((req, res) => {
- res.end("Hello");
- });
-
- const server = http.createServer(serverHandler);
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const options = { port: server.address().port };
-
- const req = http.get(options, res => {
- res.on("data", data => {
- req.abort();
- server.close();
- });
- });
-
- await new Promise(resolve => {
- server.on("close", resolve);
- });
-
- expect(serverHandler).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-http-client-abort2.js
diff --git a/test/js/node/test/parallel/http-client-defaults.test.js b/test/js/node/test/parallel/http-client-defaults.test.js
deleted file mode 100644
index f527d6ade8..0000000000
--- a/test/js/node/test/parallel/http-client-defaults.test.js
+++ /dev/null
@@ -1,28 +0,0 @@
-//#FILE: test-http-client-defaults.js
-//#SHA1: 7209a7752de52cc378c3b29eda88c82d71e6839d
-//-----------------
-"use strict";
-
-const http = require("http");
-
-describe("ClientRequest defaults", () => {
- test("default path and method", () => {
- const req = new http.ClientRequest({ createConnection: () => {} });
- expect(req.path).toBe("/");
- expect(req.method).toBe("GET");
- });
-
- test("empty method defaults to GET", () => {
- const req = new http.ClientRequest({ method: "", createConnection: () => {} });
- expect(req.path).toBe("/");
- expect(req.method).toBe("GET");
- });
-
- test("empty path defaults to /", () => {
- const req = new http.ClientRequest({ path: "", createConnection: () => {} });
- expect(req.path).toBe("/");
- expect(req.method).toBe("GET");
- });
-});
-
-//<#END_FILE: test-http-client-defaults.js
diff --git a/test/js/node/test/parallel/http-client-encoding.test.js b/test/js/node/test/parallel/http-client-encoding.test.js
deleted file mode 100644
index b0455d81bb..0000000000
--- a/test/js/node/test/parallel/http-client-encoding.test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-//#FILE: test-http-client-encoding.js
-//#SHA1: a3e1a0cc1bf9352602068f323d90071d3c2d5f7d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP client encoding", async () => {
- const server = http.createServer((req, res) => {
- res.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const port = server.address().port;
- const req = http.request(
- {
- port: port,
- encoding: "utf8",
- },
- res => {
- let data = "";
- res.on("data", chunk => (data += chunk));
- res.on("end", () => {
- expect(data).toBe("ok");
- resolve();
- });
- },
- );
- req.end();
- });
- });
-});
-
-//<#END_FILE: test-http-client-encoding.js
diff --git a/test/js/node/test/parallel/http-client-get-url.test.js b/test/js/node/test/parallel/http-client-get-url.test.js
deleted file mode 100644
index e13f87f7d4..0000000000
--- a/test/js/node/test/parallel/http-client-get-url.test.js
+++ /dev/null
@@ -1,78 +0,0 @@
-//#FILE: test-http-client-get-url.js
-//#SHA1: 0329da4beb5be5da0ab6652b246dd912935e56af
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-const testPath = "/foo?bar";
-
-let server;
-let serverAddress;
-
-beforeAll(async () => {
- server = http.createServer((req, res) => {
- expect(req.method).toBe("GET");
- expect(req.url).toBe(testPath);
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.write("hello\n");
- res.end();
- });
-
- await new Promise(resolve => {
- server.listen(0, "127.0.0.1", () => {
- serverAddress = `http://127.0.0.1:${server.address().port}${testPath}`;
- resolve();
- });
- });
-});
-
-afterAll(() => {
- server.close();
-});
-
-test("http.get with string URL", async () => {
- await new Promise(resolve => {
- http.get(serverAddress, () => {
- resolve();
- });
- });
-});
-
-test("http.get with parsed URL", async () => {
- await new Promise(resolve => {
- http.get(url.parse(serverAddress), () => {
- resolve();
- });
- });
-});
-
-test("http.get with URL object", async () => {
- await new Promise(resolve => {
- http.get(new URL(serverAddress), () => {
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-client-get-url.js
diff --git a/test/js/node/test/parallel/http-client-input-function.test.js b/test/js/node/test/parallel/http-client-input-function.test.js
deleted file mode 100644
index e34ee9a0d5..0000000000
--- a/test/js/node/test/parallel/http-client-input-function.test.js
+++ /dev/null
@@ -1,42 +0,0 @@
-//#FILE: test-http-client-input-function.js
-//#SHA1: 2ca0147b992331ea69803031f33076c685bce264
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("http.ClientRequest with server response", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200);
- res.end("hello world");
- });
-
- await new Promise(resolve => {
- server.listen(0, "127.0.0.1", resolve);
- });
-
- const serverAddress = server.address();
-
- const responsePromise = new Promise(resolve => {
- const req = new http.ClientRequest(serverAddress, response => {
- let body = "";
- response.setEncoding("utf8");
- response.on("data", chunk => {
- body += chunk;
- });
-
- response.on("end", () => {
- resolve(body);
- });
- });
-
- req.end();
- });
-
- const body = await responsePromise;
- expect(body).toBe("hello world");
-
- await new Promise(resolve => server.close(resolve));
-});
-
-//<#END_FILE: test-http-client-input-function.js
diff --git a/test/js/node/test/parallel/http-client-keep-alive-release-before-finish.test.js b/test/js/node/test/parallel/http-client-keep-alive-release-before-finish.test.js
deleted file mode 100644
index 5e7ca84113..0000000000
--- a/test/js/node/test/parallel/http-client-keep-alive-release-before-finish.test.js
+++ /dev/null
@@ -1,57 +0,0 @@
-//#FILE: test-http-client-keep-alive-release-before-finish.js
-//#SHA1: 198cd4a6c28c8a7dda45f003305e8fa80f05469d
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("HTTP client keep-alive release before finish", done => {
- const server = http.createServer((req, res) => {
- res.end();
- });
-
- server.listen(0, () => {
- const agent = new http.Agent({
- maxSockets: 1,
- keepAlive: true,
- });
-
- const port = server.address().port;
-
- const post = http.request(
- {
- agent,
- method: "POST",
- port,
- },
- res => {
- res.resume();
- },
- );
-
- // What happens here is that the server `end`s the response before we send
- // `something`, and the client thought that this is a green light for sending
- // next GET request
- post.write(Buffer.alloc(16 * 1024, "X"));
- setTimeout(() => {
- post.end("something");
- }, 100);
-
- http
- .request(
- {
- agent,
- method: "GET",
- port,
- },
- res => {
- server.close();
- res.connection.end();
- done();
- },
- )
- .end();
- });
-});
-
-//<#END_FILE: test-http-client-keep-alive-release-before-finish.js
diff --git a/test/js/node/test/parallel/http-client-race-2.test.js b/test/js/node/test/parallel/http-client-race-2.test.js
deleted file mode 100644
index bc4c83b4f4..0000000000
--- a/test/js/node/test/parallel/http-client-race-2.test.js
+++ /dev/null
@@ -1,136 +0,0 @@
-//#FILE: test-http-client-race-2.js
-//#SHA1: f1e2a4ecdd401cb9fcf615496d1376ce0a94ad73
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-//
-// Slight variation on test-http-client-race to test for another race
-// condition involving the parsers FreeList used internally by http.Client.
-//
-
-const body1_s = "1111111111111111";
-const body2_s = "22222";
-const body3_s = "3333333333333333333";
-
-let server;
-let port;
-
-beforeAll(() => {
- return new Promise(resolve => {
- server = http.createServer(function (req, res) {
- const pathname = url.parse(req.url).pathname;
-
- let body;
- switch (pathname) {
- case "/1":
- body = body1_s;
- break;
- case "/2":
- body = body2_s;
- break;
- default:
- body = body3_s;
- }
-
- res.writeHead(200, {
- "Content-Type": "text/plain",
- "Content-Length": body.length,
- });
- res.end(body);
- });
-
- server.listen(0, () => {
- port = server.address().port;
- resolve();
- });
- });
-});
-
-afterAll(() => {
- return new Promise(resolve => {
- server.close(resolve);
- });
-});
-
-test("HTTP client race condition", async () => {
- let body1 = "";
- let body2 = "";
- let body3 = "";
-
- // Client #1 is assigned Parser #1
- const req1 = http.get({ port, path: "/1" });
- await new Promise(resolve => {
- req1.on("response", function (res1) {
- res1.setEncoding("utf8");
-
- res1.on("data", function (chunk) {
- body1 += chunk;
- });
-
- res1.on("end", function () {
- // Delay execution a little to allow the 'close' event to be processed
- // (required to trigger this bug!)
- setTimeout(resolve, 500);
- });
- });
- });
-
- // The bug would introduce itself here: Client #2 would be allocated the
- // parser that previously belonged to Client #1. But we're not finished
- // with Client #1 yet!
- //
- // At this point, the bug would manifest itself and crash because the
- // internal state of the parser was no longer valid for use by Client #1
- const req2 = http.get({ port, path: "/2" });
- await new Promise(resolve => {
- req2.on("response", function (res2) {
- res2.setEncoding("utf8");
- res2.on("data", function (chunk) {
- body2 += chunk;
- });
- res2.on("end", resolve);
- });
- });
-
- // Just to be really sure we've covered all our bases, execute a
- // request using client2.
- const req3 = http.get({ port, path: "/3" });
- await new Promise(resolve => {
- req3.on("response", function (res3) {
- res3.setEncoding("utf8");
- res3.on("data", function (chunk) {
- body3 += chunk;
- });
- res3.on("end", resolve);
- });
- });
-
- expect(body1).toBe(body1_s);
- expect(body2).toBe(body2_s);
- expect(body3).toBe(body3_s);
-});
-
-//<#END_FILE: test-http-client-race-2.js
diff --git a/test/js/node/test/parallel/http-client-race.test.js b/test/js/node/test/parallel/http-client-race.test.js
deleted file mode 100644
index ab780f28d8..0000000000
--- a/test/js/node/test/parallel/http-client-race.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-//#FILE: test-http-client-race.js
-//#SHA1: 0ad515567d91a194670069b476e166d398543cc0
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-const body1_s = "1111111111111111";
-const body2_s = "22222";
-
-test("http client race condition", async () => {
- const server = http.createServer((req, res) => {
- const body = url.parse(req.url).pathname === "/1" ? body1_s : body2_s;
- res.writeHead(200, {
- "Content-Type": "text/plain",
- "Content-Length": body.length,
- });
- res.end(body);
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- let body1 = "";
- let body2 = "";
-
- const makeRequest = path => {
- return new Promise((resolve, reject) => {
- const req = http.request({ port: server.address().port, path });
- req.end();
- req.on("response", res => {
- res.setEncoding("utf8");
- let body = "";
- res.on("data", chunk => {
- body += chunk;
- });
- res.on("end", () => resolve(body));
- });
- req.on("error", reject);
- });
- };
-
- body1 = await makeRequest("/1");
- body2 = await makeRequest("/2");
-
- await new Promise(resolve => server.close(resolve));
-
- expect(body1).toBe(body1_s);
- expect(body2).toBe(body2_s);
-});
-
-//<#END_FILE: test-http-client-race.js
diff --git a/test/js/node/test/parallel/http-client-read-in-error.test.js b/test/js/node/test/parallel/http-client-read-in-error.test.js
deleted file mode 100644
index 2dd33c52de..0000000000
--- a/test/js/node/test/parallel/http-client-read-in-error.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-http-client-read-in-error.js
-//#SHA1: a7bd75283f46ff8f1246208c72bf0773a27f0fb0
-//-----------------
-"use strict";
-
-const net = require("net");
-const http = require("http");
-
-class Agent extends http.Agent {
- createConnection() {
- const socket = new net.Socket();
-
- socket.on("error", function () {
- socket.push("HTTP/1.1 200\r\n\r\n");
- });
-
- let onNewListener;
- socket.on(
- "newListener",
- (onNewListener = name => {
- if (name !== "error") return;
- socket.removeListener("newListener", onNewListener);
-
- // Let other listeners to be set up too
- process.nextTick(() => {
- this.breakSocket(socket);
- });
- }),
- );
-
- return socket;
- }
-
- breakSocket(socket) {
- socket.emit("error", new Error("Intentional error"));
- }
-}
-
-test("http client read in error", () => {
- const agent = new Agent();
- const dataHandler = jest.fn();
-
- const request = http.request({ agent });
-
- request.once("error", function () {
- console.log("ignore");
- this.on("data", dataHandler);
- });
-
- return new Promise(resolve => {
- // Give some time for the 'data' event to potentially be called
- setTimeout(() => {
- expect(dataHandler).not.toHaveBeenCalled();
- resolve();
- }, 100);
- });
-});
-
-//<#END_FILE: test-http-client-read-in-error.js
diff --git a/test/js/node/test/parallel/http-client-res-destroyed.test.js b/test/js/node/test/parallel/http-client-res-destroyed.test.js
deleted file mode 100644
index 7b7662ea52..0000000000
--- a/test/js/node/test/parallel/http-client-res-destroyed.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-http-client-res-destroyed.js
-//#SHA1: 9a7e890355cecb3eb88b6963b0c37df3f01bc8d7
-//-----------------
-"use strict";
-
-const http = require("http");
-
-describe("HTTP Client Response Destroyed", () => {
- test("Response destruction after manually calling destroy()", async () => {
- const server = http.createServer((req, res) => {
- res.end("asd");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get(
- {
- port: server.address().port,
- },
- res => {
- expect(res.destroyed).toBe(false);
- res.destroy();
- expect(res.destroyed).toBe(true);
- res.on("close", () => {
- server.close(resolve);
- });
- },
- );
- });
- });
- });
-
- test("Response destruction after end of response", async () => {
- const server = http.createServer((req, res) => {
- res.end("asd");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get(
- {
- port: server.address().port,
- },
- res => {
- expect(res.destroyed).toBe(false);
- res
- .on("close", () => {
- expect(res.destroyed).toBe(true);
- server.close(resolve);
- })
- .resume();
- },
- );
- });
- });
- });
-});
-
-//<#END_FILE: test-http-client-res-destroyed.js
diff --git a/test/js/node/test/parallel/http-client-timeout-connect-listener.test.js b/test/js/node/test/parallel/http-client-timeout-connect-listener.test.js
deleted file mode 100644
index a70f33512b..0000000000
--- a/test/js/node/test/parallel/http-client-timeout-connect-listener.test.js
+++ /dev/null
@@ -1,73 +0,0 @@
-//#FILE: test-http-client-timeout-connect-listener.js
-//#SHA1: 4311732db4ce9958ec0ed01be68786e522ed6ca8
-//-----------------
-"use strict";
-
-// This test ensures that `ClientRequest.prototype.setTimeout()` does
-// not add a listener for the `'connect'` event to the socket if the
-// socket is already connected.
-
-const http = require("http");
-
-// Maximum allowed value for timeouts.
-const timeout = 2 ** 31 - 1;
-
-let server;
-let agent;
-
-beforeAll(() => {
- return new Promise(resolve => {
- server = http.createServer((req, res) => {
- res.end();
- });
-
- server.listen(0, () => {
- agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
- resolve();
- });
- });
-});
-
-afterAll(() => {
- return new Promise(resolve => {
- agent.destroy();
- server.close(resolve);
- });
-});
-
-function doRequest(options) {
- return new Promise(resolve => {
- const req = http.get(options, res => {
- res.on("end", resolve);
- res.resume();
- });
-
- req.setTimeout(timeout);
- return req;
- });
-}
-
-test("ClientRequest.prototype.setTimeout() does not add connect listener to connected socket", async () => {
- const options = { port: server.address().port, agent: agent };
-
- await doRequest(options);
-
- const req = http.get(options);
- req.setTimeout(timeout);
-
- await new Promise(resolve => {
- req.on("socket", socket => {
- expect(socket.listenerCount("connect")).toBe(0);
- resolve();
- });
- });
-
- await new Promise(resolve => {
- req.on("response", res => {
- res.on("end", resolve);
- res.resume();
- });
- });
-});
-
-//<#END_FILE: test-http-client-timeout-connect-listener.js
diff --git a/test/js/node/test/parallel/http-client-timeout-event.test.js b/test/js/node/test/parallel/http-client-timeout-event.test.js
deleted file mode 100644
index bfff317e47..0000000000
--- a/test/js/node/test/parallel/http-client-timeout-event.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-http-client-timeout-event.js
-//#SHA1: b4aeb9d5d97b5ffa46c8c281fbc04d052857b08f
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const options = {
- method: "GET",
- port: undefined,
- host: "127.0.0.1",
- path: "/",
-};
-
-test("http client timeout event", async () => {
- const server = http.createServer();
-
- await new Promise(resolve => {
- server.listen(0, options.host, () => {
- options.port = server.address().port;
- const req = http.request(options);
-
- req.on("error", () => {
- // This space is intentionally left blank
- });
-
- req.on("close", () => {
- expect(req.destroyed).toBe(true);
- server.close();
- resolve();
- });
-
- req.setTimeout(1);
- req.on("timeout", () => {
- req.end(() => {
- setTimeout(() => {
- req.destroy();
- }, 100);
- });
- });
- });
- });
-});
-
-//<#END_FILE: test-http-client-timeout-event.js
diff --git a/test/js/node/test/parallel/http-client-timeout.test.js b/test/js/node/test/parallel/http-client-timeout.test.js
deleted file mode 100644
index 557b469490..0000000000
--- a/test/js/node/test/parallel/http-client-timeout.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-//#FILE: test-http-client-timeout.js
-//#SHA1: f99a3189acb9c566e378f9fa48c66dd503034d0d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const options = {
- method: "GET",
- port: undefined,
- host: "127.0.0.1",
- path: "/",
-};
-
-test("http client timeout", done => {
- const server = http.createServer((req, res) => {
- // This space intentionally left blank
- });
-
- server.listen(0, options.host, () => {
- options.port = server.address().port;
- const req = http.request(options, res => {
- // This space intentionally left blank
- });
- req.on("close", () => {
- expect(req.destroyed).toBe(true);
- server.close();
- done();
- });
- function destroy() {
- req.destroy();
- }
- const s = req.setTimeout(1, destroy);
- expect(s).toBeInstanceOf(http.ClientRequest);
- req.on("error", destroy);
- req.end();
- });
-});
-
-//<#END_FILE: test-http-client-timeout.js
diff --git a/test/js/node/test/parallel/http-client-upload-buf.test.js b/test/js/node/test/parallel/http-client-upload-buf.test.js
deleted file mode 100644
index 9891a442dc..0000000000
--- a/test/js/node/test/parallel/http-client-upload-buf.test.js
+++ /dev/null
@@ -1,77 +0,0 @@
-//#FILE: test-http-client-upload-buf.js
-//#SHA1: bbfd7c52e710f53683f5f9a4578f34e451db4eb0
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const assert = require("assert");
-const http = require("http");
-
-const N = 1024;
-
-test("HTTP client upload buffer", async () => {
- const server = http.createServer((req, res) => {
- expect(req.method).toBe("POST");
- let bytesReceived = 0;
-
- req.on("data", chunk => {
- bytesReceived += chunk.length;
- });
-
- req.on("end", () => {
- expect(bytesReceived).toBe(N);
- console.log("request complete from server");
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.write("hello\n");
- res.end();
- });
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const { port } = server.address();
-
- const responsePromise = new Promise(resolve => {
- const req = http.request(
- {
- port,
- method: "POST",
- path: "/",
- },
- res => {
- res.setEncoding("utf8");
- res.on("data", chunk => {
- console.log(chunk);
- });
- res.on("end", resolve);
- },
- );
-
- req.write(Buffer.allocUnsafe(N));
- req.end();
- });
-
- await responsePromise;
- await new Promise(resolve => server.close(resolve));
-});
-
-//<#END_FILE: test-http-client-upload-buf.js
diff --git a/test/js/node/test/parallel/http-client-upload.test.js b/test/js/node/test/parallel/http-client-upload.test.js
deleted file mode 100644
index 6adc480232..0000000000
--- a/test/js/node/test/parallel/http-client-upload.test.js
+++ /dev/null
@@ -1,84 +0,0 @@
-//#FILE: test-http-client-upload.js
-//#SHA1: 328a7e9989cc28daa5996c83fe9e3cfcb0893e01
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP client upload", async () => {
- const serverHandler = jest.fn((req, res) => {
- expect(req.method).toBe("POST");
- req.setEncoding("utf8");
-
- let sent_body = "";
-
- req.on("data", chunk => {
- console.log(`server got: ${JSON.stringify(chunk)}`);
- sent_body += chunk;
- });
-
- req.on("end", () => {
- expect(sent_body).toBe("1\n2\n3\n");
- console.log("request complete from server");
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.write("hello\n");
- res.end();
- });
- });
-
- const server = http.createServer(serverHandler);
- await new Promise(resolve => server.listen(0, resolve));
-
- const { port } = server.address();
-
- const clientHandler = jest.fn(res => {
- res.setEncoding("utf8");
- res.on("data", chunk => {
- console.log(chunk);
- });
- res.on("end", () => {
- server.close();
- });
- });
-
- const req = http.request(
- {
- port,
- method: "POST",
- path: "/",
- },
- clientHandler,
- );
-
- req.write("1\n");
- req.write("2\n");
- req.write("3\n");
- req.end();
-
- await new Promise(resolve => server.on("close", resolve));
-
- expect(serverHandler).toHaveBeenCalledTimes(1);
- expect(clientHandler).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-http-client-upload.js
diff --git a/test/js/node/test/parallel/http-contentlength0.test.js b/test/js/node/test/parallel/http-contentlength0.test.js
deleted file mode 100644
index 4a6a7fec72..0000000000
--- a/test/js/node/test/parallel/http-contentlength0.test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-//#FILE: test-http-contentLength0.js
-//#SHA1: d85b0cc3dcfcff522ffbeddacf89111897b80c02
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-// Simple test of Node's HTTP Client choking on a response
-// with a 'Content-Length: 0 ' response header.
-// I.E. a space character after the 'Content-Length' throws an `error` event.
-
-test("HTTP Client handles Content-Length: 0 with space", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, { "Content-Length": "0 " });
- res.end();
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const { port } = server.address();
-
- await new Promise(resolve => {
- const request = http.request({ port }, response => {
- expect(response.statusCode).toBe(200);
- server.close();
- response.resume();
- resolve();
- });
-
- request.end();
- });
-});
-
-//<#END_FILE: test-http-contentLength0.js
diff --git a/test/js/node/test/parallel/http-date-header.test.js b/test/js/node/test/parallel/http-date-header.test.js
deleted file mode 100644
index b47a7163d9..0000000000
--- a/test/js/node/test/parallel/http-date-header.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-http-date-header.js
-//#SHA1: e4d2a00dad7c6483d9ed328731bb04f5f431afb4
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const testResBody = "other stuff!\n";
-
-test("HTTP Date header", async () => {
- const server = http.createServer((req, res) => {
- expect(req.headers).not.toHaveProperty("date");
- res.writeHead(200, {
- "Content-Type": "text/plain",
- });
- res.end(testResBody);
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const { port } = server.address();
-
- const options = {
- port,
- path: "/",
- method: "GET",
- };
-
- const responsePromise = new Promise((resolve, reject) => {
- const req = http.request(options, res => {
- expect(res.headers).toHaveProperty("date");
- res.resume();
- res.on("end", resolve);
- });
- req.on("error", reject);
- req.end();
- });
-
- await responsePromise;
- await new Promise(resolve => server.close(resolve));
-});
-
-//<#END_FILE: test-http-date-header.js
diff --git a/test/js/node/test/parallel/http-decoded-auth.test.js b/test/js/node/test/parallel/http-decoded-auth.test.js
deleted file mode 100644
index ed117d1954..0000000000
--- a/test/js/node/test/parallel/http-decoded-auth.test.js
+++ /dev/null
@@ -1,57 +0,0 @@
-//#FILE: test-http-decoded-auth.js
-//#SHA1: 70ba85653c7479ce80cf528a07aa85f598f85ef8
-//-----------------
-"use strict";
-
-const http = require("http");
-
-const testCases = [
- {
- username: 'test@test"',
- password: "123456^",
- expected: "dGVzdEB0ZXN0IjoxMjM0NTZe",
- },
- {
- username: "test%40test",
- password: "123456",
- expected: "dGVzdEB0ZXN0OjEyMzQ1Ng==",
- },
- {
- username: "not%3Agood",
- password: "god",
- expected: "bm90Omdvb2Q6Z29k",
- },
- {
- username: "not%22good",
- password: "g%5Eod",
- expected: "bm90Imdvb2Q6Z15vZA==",
- },
- {
- username: "test1234::::",
- password: "mypass",
- expected: "dGVzdDEyMzQ6Ojo6Om15cGFzcw==",
- },
-];
-
-testCases.forEach((testCase, index) => {
- test(`HTTP decoded auth - case ${index + 1}`, async () => {
- const server = http.createServer((request, response) => {
- // The correct authorization header is be passed
- expect(request.headers.authorization).toBe(`Basic ${testCase.expected}`);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- // make the request
- const url = new URL(`http://${testCase.username}:${testCase.password}@localhost:${server.address().port}`);
- http.request(url).end();
- resolve();
- });
- });
- });
-});
-
-//<#END_FILE: test-http-decoded-auth.js
diff --git a/test/js/node/test/parallel/http-default-encoding.test.js b/test/js/node/test/parallel/http-default-encoding.test.js
deleted file mode 100644
index 30fc083b29..0000000000
--- a/test/js/node/test/parallel/http-default-encoding.test.js
+++ /dev/null
@@ -1,73 +0,0 @@
-//#FILE: test-http-default-encoding.js
-//#SHA1: f5dfdba00ec21efec894e5edf97583c77334a2c3
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const expected = "This is a unicode text: سلام";
-
-test("HTTP server with default encoding", async () => {
- let result = "";
-
- const server = http.Server((req, res) => {
- req.setEncoding("utf8");
- req
- .on("data", chunk => {
- result += chunk;
- })
- .on("end", () => {
- res.writeHead(200);
- res.end("hello world\n");
- server.close();
- });
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const req = http.request(
- {
- port: server.address().port,
- path: "/",
- method: "POST",
- },
- res => {
- expect(res.statusCode).toBe(200);
- res.resume();
- resolve();
- },
- );
-
- req.on("error", e => {
- console.log(e.message);
- process.exit(1);
- });
-
- req.end(expected);
- });
- });
-
- expect(result).toBe(expected);
-});
-
-//<#END_FILE: test-http-default-encoding.js
diff --git a/test/js/node/test/parallel/http-eof-on-connect.test.js b/test/js/node/test/parallel/http-eof-on-connect.test.js
deleted file mode 100644
index 1161c1f40c..0000000000
--- a/test/js/node/test/parallel/http-eof-on-connect.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http-eof-on-connect.js
-//#SHA1: c243d7ad215d84d88b20dfeea40976155f00a2bb
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const net = require("net");
-const http = require("http");
-
-// This is a regression test for https://github.com/joyent/node/issues/44
-// It is separate from test-http-malformed-request.js because it is only
-// reproducible on the first packet on the first connection to a server.
-
-test("EOF on connect", async () => {
- const server = http.createServer(jest.fn());
- server.listen(0);
-
- await new Promise(resolve => {
- server.on("listening", () => {
- const client = net.createConnection(server.address().port, "127.0.0.1");
-
- client.on("connect", () => {
- client.destroy();
- });
-
- client.on("close", () => {
- server.close(resolve);
- });
- });
- });
-
- expect(server.listeners("request")[0]).not.toHaveBeenCalled();
-});
-
-//<#END_FILE: test-http-eof-on-connect.js
diff --git a/test/js/node/test/parallel/http-extra-response.test.js b/test/js/node/test/parallel/http-extra-response.test.js
deleted file mode 100644
index b3e73a341a..0000000000
--- a/test/js/node/test/parallel/http-extra-response.test.js
+++ /dev/null
@@ -1,98 +0,0 @@
-//#FILE: test-http-extra-response.js
-//#SHA1: 0d2dfa2459e54fa9f1b90a609c328afd478f2793
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const net = require("net");
-
-// If an HTTP server is broken and sends data after the end of the response,
-// node should ignore it and drop the connection.
-// Demos this bug: https://github.com/joyent/node/issues/680
-
-const body = "hello world\r\n";
-const fullResponse =
- "HTTP/1.1 500 Internal Server Error\r\n" +
- `Content-Length: ${body.length}\r\n` +
- "Content-Type: text/plain\r\n" +
- "Date: Fri + 18 Feb 2011 06:22:45 GMT\r\n" +
- "Host: 10.20.149.2\r\n" +
- "Access-Control-Allow-Credentials: true\r\n" +
- "Server: badly broken/0.1 (OS NAME)\r\n" +
- "\r\n" +
- body;
-
-test("HTTP server sending data after response end", async () => {
- const server = net.createServer(socket => {
- let postBody = "";
-
- socket.setEncoding("utf8");
-
- socket.on("data", chunk => {
- postBody += chunk;
-
- if (postBody.includes("\r\n")) {
- socket.write(fullResponse);
- socket.end(fullResponse);
- }
- });
-
- socket.on("error", err => {
- expect(err.code).toBe("ECONNRESET");
- });
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const { port } = server.address();
-
- const consoleLogSpy = jest.spyOn(console, "log").mockImplementation();
-
- await new Promise(resolve => {
- http.get({ port }, res => {
- let buffer = "";
- console.log(`Got res code: ${res.statusCode}`);
-
- res.setEncoding("utf8");
- res.on("data", chunk => {
- buffer += chunk;
- });
-
- res.on("end", () => {
- console.log(`Response ended, read ${buffer.length} bytes`);
- expect(buffer).toBe(body);
- resolve();
- });
- });
- });
-
- expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringMatching(/Got res code: \d+/));
- expect(consoleLogSpy).toHaveBeenCalledWith(expect.stringMatching(/Response ended, read \d+ bytes/));
-
- consoleLogSpy.mockRestore();
- await new Promise(resolve => server.close(resolve));
-});
-
-//<#END_FILE: test-http-extra-response.js
diff --git a/test/js/node/test/parallel/http-full-response.test.js b/test/js/node/test/parallel/http-full-response.test.js
deleted file mode 100644
index 8e0a8fcc3b..0000000000
--- a/test/js/node/test/parallel/http-full-response.test.js
+++ /dev/null
@@ -1,104 +0,0 @@
-//#FILE: test-http-full-response.js
-//#SHA1: 3494c79026bf858a01bb497a50a8f2fd3166e62d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// This test requires the program 'ab'
-const http = require("http");
-const { exec } = require("child_process");
-
-const bodyLength = 12345;
-
-const body = "c".repeat(bodyLength);
-
-let server;
-
-beforeAll(() => {
- return new Promise(resolve => {
- server = http.createServer((req, res) => {
- res.writeHead(200, {
- "Content-Length": bodyLength,
- "Content-Type": "text/plain",
- });
- res.end(body);
- });
-
- server.listen(0, () => {
- resolve();
- });
- });
-});
-
-afterAll(() => {
- return new Promise(resolve => {
- server.close(() => {
- resolve();
- });
- });
-});
-
-function runAb(opts) {
- return new Promise((resolve, reject) => {
- const command = `ab ${opts} http://127.0.0.1:${server.address().port}/`;
- exec(command, (err, stdout, stderr) => {
- if (err) {
- if (/ab|apr/i.test(stderr)) {
- console.log(`Skipping: problem spawning \`ab\`.\n${stderr}`);
- return resolve();
- }
- return reject(err);
- }
-
- let m = /Document Length:\s*(\d+) bytes/i.exec(stdout);
- const documentLength = parseInt(m[1]);
-
- m = /Complete requests:\s*(\d+)/i.exec(stdout);
- const completeRequests = parseInt(m[1]);
-
- m = /HTML transferred:\s*(\d+) bytes/i.exec(stdout);
- const htmlTransferred = parseInt(m[1]);
-
- expect(documentLength).toBe(bodyLength);
- expect(htmlTransferred).toBe(completeRequests * documentLength);
-
- resolve();
- });
- });
-}
-
-test("-c 1 -n 10", async () => {
- await runAb("-c 1 -n 10");
- console.log("-c 1 -n 10 okay");
-});
-
-test("-c 1 -n 100", async () => {
- await runAb("-c 1 -n 100");
- console.log("-c 1 -n 100 okay");
-});
-
-test("-c 1 -n 1000", async () => {
- await runAb("-c 1 -n 1000");
- console.log("-c 1 -n 1000 okay");
-});
-
-//<#END_FILE: test-http-full-response.js
diff --git a/test/js/node/test/parallel/http-get-pipeline-problem.test.js b/test/js/node/test/parallel/http-get-pipeline-problem.test.js
deleted file mode 100644
index ec0750f018..0000000000
--- a/test/js/node/test/parallel/http-get-pipeline-problem.test.js
+++ /dev/null
@@ -1,98 +0,0 @@
-//#FILE: test-http-get-pipeline-problem.js
-//#SHA1: 422a6c8ae8350bb70627efee734652421322b1bd
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// In previous versions of Node.js (e.g., 0.6.0), this sort of thing would halt
-// after http.globalAgent.maxSockets number of files.
-// See https://groups.google.com/forum/#!topic/nodejs-dev/V5fB69hFa9o
-const fixtures = require("../common/fixtures");
-const http = require("http");
-const fs = require("fs");
-const tmpdir = require("../common/tmpdir");
-
-http.globalAgent.maxSockets = 1;
-
-tmpdir.refresh();
-
-const image = fixtures.readSync("/person.jpg");
-
-console.log(`image.length = ${image.length}`);
-
-const total = 10;
-
-test("HTTP GET pipeline problem", async () => {
- const server = http.createServer((req, res) => {
- setTimeout(() => {
- res.writeHead(200, {
- "content-type": "image/jpeg",
- connection: "close",
- "content-length": image.length,
- });
- res.end(image);
- }, 1);
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const serverAddress = server.address();
-
- const requests = Array.from({ length: total }, (_, i) => {
- return new Promise((resolve, reject) => {
- const opts = {
- port: serverAddress.port,
- headers: { connection: "close" },
- };
-
- http
- .get(opts, res => {
- console.error(`recv ${i}`);
- const s = fs.createWriteStream(`${tmpdir.path}/${i}.jpg`);
- res.pipe(s);
-
- s.on("finish", () => {
- console.error(`done ${i}`);
- resolve();
- });
- })
- .on("error", reject);
- });
- });
-
- await Promise.all(requests);
-
- // Check files
- const files = fs.readdirSync(tmpdir.path);
- expect(files.length).toBeGreaterThanOrEqual(total);
-
- for (let i = 0; i < total; i++) {
- const fn = `${i}.jpg`;
- expect(files).toContain(fn);
- const stat = fs.statSync(`${tmpdir.path}/${fn}`);
- expect(stat.size).toBe(image.length);
- }
-
- server.close();
-});
-
-//<#END_FILE: test-http-get-pipeline-problem.js
diff --git a/test/js/node/test/parallel/http-head-request.test.js b/test/js/node/test/parallel/http-head-request.test.js
deleted file mode 100644
index b2f86c5ac2..0000000000
--- a/test/js/node/test/parallel/http-head-request.test.js
+++ /dev/null
@@ -1,76 +0,0 @@
-//#FILE: test-http-head-request.js
-//#SHA1: ab54d1748aa92e4fa61cf4994e83ddf5e00bf874
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const body = "hello world\n";
-
-async function runTest(headers) {
- return new Promise((resolve, reject) => {
- const server = http.createServer((req, res) => {
- console.error("req: %s headers: %j", req.method, headers);
- res.writeHead(200, headers);
- res.end();
- server.close();
- });
-
- server.listen(0, () => {
- const request = http.request(
- {
- port: server.address().port,
- method: "HEAD",
- path: "/",
- },
- response => {
- console.error("response start");
- response.on("end", () => {
- console.error("response end");
- resolve();
- });
- response.resume();
- },
- );
- request.end();
- });
- });
-}
-
-test("HEAD request with Transfer-Encoding: chunked", async () => {
- await expect(
- runTest({
- "Transfer-Encoding": "chunked",
- }),
- ).resolves.toBeUndefined();
-});
-
-test("HEAD request with Content-Length", async () => {
- await expect(
- runTest({
- "Content-Length": body.length,
- }),
- ).resolves.toBeUndefined();
-});
-
-//<#END_FILE: test-http-head-request.js
diff --git a/test/js/node/test/parallel/http-head-response-has-no-body-end-implicit-headers.test.js b/test/js/node/test/parallel/http-head-response-has-no-body-end-implicit-headers.test.js
deleted file mode 100644
index 46f4f2269d..0000000000
--- a/test/js/node/test/parallel/http-head-response-has-no-body-end-implicit-headers.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-http-head-response-has-no-body-end-implicit-headers.js
-//#SHA1: e2f884b0a99ba30e0e8065596d00af1ed99b4791
-//-----------------
-"use strict";
-const http = require("http");
-
-// This test is to make sure that when the HTTP server
-// responds to a HEAD request with data to res.end,
-// it does not send any body but the response is sent
-// anyway.
-
-test("HTTP HEAD response has no body, end implicit headers", done => {
- const server = http.createServer((req, res) => {
- res.end("FAIL"); // broken: sends FAIL from hot path.
- });
-
- server.listen(0, () => {
- const req = http.request(
- {
- port: server.address().port,
- method: "HEAD",
- path: "/",
- },
- res => {
- res.on("end", () => {
- server.close();
- done();
- });
- res.resume();
- },
- );
- req.end();
- });
-});
-
-//<#END_FILE: test-http-head-response-has-no-body-end-implicit-headers.js
diff --git a/test/js/node/test/parallel/http-head-response-has-no-body-end.test.js b/test/js/node/test/parallel/http-head-response-has-no-body-end.test.js
deleted file mode 100644
index 5d18311eb5..0000000000
--- a/test/js/node/test/parallel/http-head-response-has-no-body-end.test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-//#FILE: test-http-head-response-has-no-body-end.js
-//#SHA1: 64091937f68588f23597f106fa906d27380be005
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-// This test is to make sure that when the HTTP server
-// responds to a HEAD request with data to res.end,
-// it does not send any body.
-
-test("HTTP server responds to HEAD request without sending body", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200);
- res.end("FAIL"); // broken: sends FAIL from hot path.
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const req = http.request(
- {
- port: server.address().port,
- method: "HEAD",
- path: "/",
- },
- res => {
- const onEnd = jest.fn();
- res.on("end", onEnd);
- res.resume();
-
- res.on("end", () => {
- expect(onEnd).toHaveBeenCalledTimes(1);
- server.close(resolve);
- });
- },
- );
- req.end();
- });
- });
-});
-
-//<#END_FILE: test-http-head-response-has-no-body-end.js
diff --git a/test/js/node/test/parallel/http-head-response-has-no-body.test.js b/test/js/node/test/parallel/http-head-response-has-no-body.test.js
deleted file mode 100644
index f87fece95a..0000000000
--- a/test/js/node/test/parallel/http-head-response-has-no-body.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-http-head-response-has-no-body.js
-//#SHA1: f7df6559885b0465d43994e773c961b525b195a9
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-// This test is to make sure that when the HTTP server
-// responds to a HEAD request, it does not send any body.
-// In this case it was sending '0\r\n\r\n'
-
-test("HTTP server responds to HEAD request without body", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200); // broken: defaults to TE chunked
- res.end();
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const { port } = server.address();
-
- await new Promise((resolve, reject) => {
- const req = http.request(
- {
- port,
- method: "HEAD",
- path: "/",
- },
- res => {
- res.on("end", () => {
- server.close(() => {
- resolve();
- });
- });
- res.resume();
- },
- );
- req.on("error", reject);
- req.end();
- });
-});
-
-//<#END_FILE: test-http-head-response-has-no-body.js
diff --git a/test/js/node/test/parallel/http-header-obstext.test.js b/test/js/node/test/parallel/http-header-obstext.test.js
deleted file mode 100644
index 55248d91c4..0000000000
--- a/test/js/node/test/parallel/http-header-obstext.test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-//#FILE: test-http-header-obstext.js
-//#SHA1: 031a5230bc91c831407772f2b8cbeba3559ed1d2
-//-----------------
-"use strict";
-
-// This test ensures that the http-parser can handle UTF-8 characters
-// in the http header.
-
-const http = require("http");
-
-test("http-parser can handle UTF-8 characters in http header", async () => {
- const server = http.createServer((req, res) => {
- res.end("ok");
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const { port } = server.address();
-
- const response = await new Promise(resolve => {
- http.get(
- {
- port,
- headers: { Test: "Düsseldorf" },
- },
- resolve,
- );
- });
-
- expect(response.statusCode).toBe(200);
-
- await new Promise(resolve => server.close(resolve));
-});
-
-//<#END_FILE: test-http-header-obstext.js
diff --git a/test/js/node/test/parallel/http-header-owstext.test.js b/test/js/node/test/parallel/http-header-owstext.test.js
deleted file mode 100644
index cfab935f17..0000000000
--- a/test/js/node/test/parallel/http-header-owstext.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http-header-owstext.js
-//#SHA1: 339bfcf13a4cc9caa39940de3854eeda01b4500c
-//-----------------
-"use strict";
-
-const http = require("http");
-const net = require("net");
-
-// This test ensures that the http-parser strips leading and trailing OWS from
-// header values. It sends the header values in chunks to force the parser to
-// build the string up through multiple calls to on_header_value().
-
-function check(hdr, snd, rcv) {
- return new Promise(resolve => {
- const server = http.createServer((req, res) => {
- expect(req.headers[hdr]).toBe(rcv);
- req.pipe(res);
- });
-
- server.listen(0, function () {
- const client = net.connect(this.address().port, start);
- function start() {
- client.write("GET / HTTP/1.1\r\n" + hdr + ":", drain);
- }
-
- function drain() {
- if (snd.length === 0) {
- return client.write("\r\nConnection: close\r\n\r\n");
- }
- client.write(snd.shift(), drain);
- }
-
- const bufs = [];
- client.on("data", function (chunk) {
- bufs.push(chunk);
- });
- client.on("end", function () {
- const head = Buffer.concat(bufs).toString("latin1").split("\r\n")[0];
- expect(head).toBe("HTTP/1.1 200 OK");
- server.close();
- resolve();
- });
- });
- });
-}
-
-test("http header OWS text parsing", async () => {
- await check("host", [" \t foo.com\t"], "foo.com");
- await check("host", [" \t foo\tcom\t"], "foo\tcom");
- await check("host", [" \t", " ", " foo.com\t", "\t "], "foo.com");
- await check("host", [" \t", " \t".repeat(100), "\t "], "");
- await check("host", [" \t", " - - - - ", "\t "], "- - - -");
-});
-
-//<#END_FILE: test-http-header-owstext.js
diff --git a/test/js/node/test/parallel/http-host-headers.test.js b/test/js/node/test/parallel/http-host-headers.test.js
deleted file mode 100644
index cb50ca9b04..0000000000
--- a/test/js/node/test/parallel/http-host-headers.test.js
+++ /dev/null
@@ -1,77 +0,0 @@
-//#FILE: test-http-host-headers.js
-//#SHA1: 256e8b55e2c545a9f9df89607600f18a93c1c67a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-function reqHandler(req, res) {
- if (req.url === "/setHostFalse5") {
- expect(req.headers.host).toBeUndefined();
- } else {
- expect(req.headers.host).toBe(`localhost:${this.address().port}`);
- }
- res.writeHead(200, {});
- res.end("ok");
-}
-
-const httpServer = http.createServer(reqHandler);
-
-test("HTTP host headers", async () => {
- await new Promise(resolve => {
- httpServer.listen(0, async () => {
- const port = httpServer.address().port;
- const makeRequest = (method, path) => {
- return new Promise(resolve => {
- const req = http.request(
- {
- method,
- path,
- host: "localhost",
- port,
- rejectUnauthorized: false,
- },
- res => {
- res.resume();
- resolve();
- },
- );
- req.on("error", () => {
- throw new Error("Request should not fail");
- });
- req.end();
- });
- };
-
- await makeRequest("GET", "/0");
- await makeRequest("GET", "/1");
- await makeRequest("POST", "/2");
- await makeRequest("PUT", "/3");
- await makeRequest("DELETE", "/4");
-
- httpServer.close(resolve);
- });
- });
-});
-
-//<#END_FILE: test-http-host-headers.js
diff --git a/test/js/node/test/parallel/http-keep-alive-timeout-custom.test.js b/test/js/node/test/parallel/http-keep-alive-timeout-custom.test.js
deleted file mode 100644
index 9d0e874e81..0000000000
--- a/test/js/node/test/parallel/http-keep-alive-timeout-custom.test.js
+++ /dev/null
@@ -1,43 +0,0 @@
-//#FILE: test-http-keep-alive-timeout-custom.js
-//#SHA1: 4f7c5a20da7b46bea9198b3854aed7c2042a8691
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("HTTP Keep-Alive timeout custom", async () => {
- const server = http.createServer((req, res) => {
- const body = "hello world\n";
-
- res.writeHead(200, {
- "Content-Length": body.length,
- "Keep-Alive": "timeout=50",
- });
- res.write(body);
- res.end();
- });
- server.keepAliveTimeout = 12010;
-
- const agent = new http.Agent({ maxSockets: 1, keepAlive: true });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get(
- {
- path: "/",
- port: server.address().port,
- agent: agent,
- },
- response => {
- response.resume();
- expect(response.headers["keep-alive"]).toBe("timeout=50");
- server.close();
- agent.destroy();
- resolve();
- },
- );
- });
- });
-});
-
-//<#END_FILE: test-http-keep-alive-timeout-custom.js
diff --git a/test/js/node/test/parallel/http-many-ended-pipelines.test.js b/test/js/node/test/parallel/http-many-ended-pipelines.test.js
deleted file mode 100644
index c142011e0d..0000000000
--- a/test/js/node/test/parallel/http-many-ended-pipelines.test.js
+++ /dev/null
@@ -1,82 +0,0 @@
-//#FILE: test-http-many-ended-pipelines.js
-//#SHA1: 930bb6dc614c68f965c7b31e9a1223386234e389
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const net = require("net");
-
-const numRequests = 20;
-let first = false;
-
-test("HTTP server handles many ended pipelines", async () => {
- const server = http.createServer((req, res) => {
- if (!first) {
- first = true;
- req.socket.on("close", () => {
- server.close();
- });
- }
-
- res.end("ok");
- // Oh no! The connection died!
- req.socket.destroy();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const client = net.connect({
- port: server.address().port,
- allowHalfOpen: true,
- });
-
- client.on("error", err => {
- // The socket might be destroyed by the other peer while data is still
- // being written. The `'EPIPE'` and `'ECONNABORTED'` codes might also be
- // valid but they have not been seen yet.
- expect(err.code).toBe("ECONNRESET");
- });
-
- for (let i = 0; i < numRequests; i++) {
- client.write("GET / HTTP/1.1\r\n" + "Host: some.host.name\r\n" + "\r\n\r\n");
- }
- client.end();
- client.pipe(process.stdout);
-
- resolve();
- });
- });
-});
-
-const mockWarning = jest.spyOn(process, "emit");
-mockWarning.mockImplementation((event, ...args) => {
- if (event === "warning") return;
- return process.emit.apply(process, [event, ...args]);
-});
-
-afterAll(() => {
- expect(mockWarning).not.toHaveBeenCalledWith("warning", expect.anything());
- mockWarning.mockRestore();
-});
-
-//<#END_FILE: test-http-many-ended-pipelines.js
diff --git a/test/js/node/test/parallel/http-missing-header-separator-cr.test.js b/test/js/node/test/parallel/http-missing-header-separator-cr.test.js
deleted file mode 100644
index 952d726eed..0000000000
--- a/test/js/node/test/parallel/http-missing-header-separator-cr.test.js
+++ /dev/null
@@ -1,89 +0,0 @@
-//#FILE: test-http-missing-header-separator-cr.js
-//#SHA1: 6e213764778e9edddd0fc6a43c9a3183507054c6
-//-----------------
-"use strict";
-
-const http = require("http");
-const net = require("net");
-
-function serverHandler(server, msg) {
- const client = net.connect(server.address().port, "localhost");
-
- let response = "";
-
- client.on("data", chunk => {
- response += chunk;
- });
-
- client.setEncoding("utf8");
- client.on("error", () => {
- throw new Error("Client error should not occur");
- });
- client.on("end", () => {
- expect(response).toBe("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
- server.close();
- });
- client.write(msg);
- client.resume();
-}
-
-test("GET request with invalid header", async () => {
- const msg = [
- "GET / HTTP/1.1",
- "Host: localhost",
- "Dummy: x\nContent-Length: 23",
- "",
- "GET / HTTP/1.1",
- "Dummy: GET /admin HTTP/1.1",
- "Host: localhost",
- "",
- "",
- ].join("\r\n");
-
- const server = http.createServer(() => {
- throw new Error("Server should not be called");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- serverHandler(server, msg);
- resolve();
- });
- });
-});
-
-test("POST request with invalid Transfer-Encoding header", async () => {
- const msg = ["POST / HTTP/1.1", "Host: localhost", "x:x\nTransfer-Encoding: chunked", "", "1", "A", "0", "", ""].join(
- "\r\n",
- );
-
- const server = http.createServer(() => {
- throw new Error("Server should not be called");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- serverHandler(server, msg);
- resolve();
- });
- });
-});
-
-test("POST request with invalid header and Transfer-Encoding", async () => {
- const msg = ["POST / HTTP/1.1", "Host: localhost", "x:\nTransfer-Encoding: chunked", "", "1", "A", "0", "", ""].join(
- "\r\n",
- );
-
- const server = http.createServer(() => {
- throw new Error("Server should not be called");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- serverHandler(server, msg);
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-missing-header-separator-cr.js
diff --git a/test/js/node/test/parallel/http-no-read-no-dump.test.js b/test/js/node/test/parallel/http-no-read-no-dump.test.js
deleted file mode 100644
index 2085ea1981..0000000000
--- a/test/js/node/test/parallel/http-no-read-no-dump.test.js
+++ /dev/null
@@ -1,86 +0,0 @@
-//#FILE: test-http-no-read-no-dump.js
-//#SHA1: 8548eb47a6eb8ec151b9c60e74b026d983145d26
-//-----------------
-"use strict";
-
-const http = require("http");
-
-let onPause = null;
-
-describe("HTTP no read no dump", () => {
- let server;
- let port;
-
- beforeAll(done => {
- server = http
- .createServer((req, res) => {
- if (req.method === "GET") return res.end();
-
- res.writeHead(200);
- res.flushHeaders();
-
- req.on("close", () => {
- expect(() => {
- req.on("end", () => {});
- }).not.toThrow();
- });
-
- req.connection.on("pause", () => {
- res.end();
- onPause();
- });
- })
- .listen(0, () => {
- port = server.address().port;
- done();
- });
- });
-
- afterAll(done => {
- server.close(done);
- });
-
- test("should handle POST and GET requests correctly", done => {
- const agent = new http.Agent({
- maxSockets: 1,
- keepAlive: true,
- });
-
- const post = http.request(
- {
- agent,
- method: "POST",
- port,
- },
- res => {
- res.resume();
-
- post.write(Buffer.alloc(64 * 1024).fill("X"));
- onPause = () => {
- post.end("something");
- };
- },
- );
-
- // What happens here is that the server `end`s the response before we send
- // `something`, and the client thought that this is a green light for sending
- // next GET request
- post.write("initial");
-
- http
- .request(
- {
- agent,
- method: "GET",
- port,
- },
- res => {
- res.connection.end();
- done();
- },
- )
- .end();
- });
-});
-
-//<#END_FILE: test-http-no-read-no-dump.js
diff --git a/test/js/node/test/parallel/http-outgoing-finish.test.js b/test/js/node/test/parallel/http-outgoing-finish.test.js
deleted file mode 100644
index fa7aab9a23..0000000000
--- a/test/js/node/test/parallel/http-outgoing-finish.test.js
+++ /dev/null
@@ -1,86 +0,0 @@
-//#FILE: test-http-outgoing-finish.js
-//#SHA1: cd9dbce2b1b26369349c30bcd94979b354316128
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const http = require("http");
-
-test("http outgoing finish", async () => {
- const server = http.createServer((req, res) => {
- req.resume();
- req.on("end", () => {
- write(res);
- });
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const req = http.request({
- port: server.address().port,
- method: "PUT",
- });
- write(req);
- req.on("response", res => {
- res.resume();
- });
- resolve();
- });
- });
-});
-
-const buf = Buffer.alloc(1024 * 16, "x");
-function write(out) {
- const name = out.constructor.name;
- let finishEvent = false;
- let endCb = false;
-
- // First, write until it gets some backpressure
- while (out.write(buf));
-
- // Now end, and make sure that we don't get the 'finish' event
- // before the tick where the cb gets called. We give it until
- // nextTick because this is added as a listener before the endcb
- // is registered. The order is not what we're testing here, just
- // that 'finish' isn't emitted until the stream is fully flushed.
- out.on("finish", () => {
- finishEvent = true;
- console.error(`${name} finish event`);
- process.nextTick(() => {
- expect(endCb).toBe(true);
- console.log(`ok - ${name} finishEvent`);
- });
- });
-
- out.end(buf, () => {
- endCb = true;
- console.error(`${name} endCb`);
- process.nextTick(() => {
- expect(finishEvent).toBe(true);
- console.log(`ok - ${name} endCb`);
- });
- });
-}
-
-//<#END_FILE: test-http-outgoing-finish.js
diff --git a/test/js/node/test/parallel/http-outgoing-finished.test.js b/test/js/node/test/parallel/http-outgoing-finished.test.js
deleted file mode 100644
index 96363b2382..0000000000
--- a/test/js/node/test/parallel/http-outgoing-finished.test.js
+++ /dev/null
@@ -1,68 +0,0 @@
-//#FILE: test-http-outgoing-finished.js
-//#SHA1: 9c1ce8205b113dbb5b4ddfd06c0c90017b344e15
-//-----------------
-"use strict";
-
-const http = require("http");
-const { finished } = require("stream");
-
-let server;
-
-beforeAll(() => {
- return new Promise(resolve => {
- server = http
- .createServer((req, res) => {
- let closed = false;
- res
- .on("close", () => {
- closed = true;
- finished(res, () => {
- server.close();
- });
- })
- .end();
- finished(res, () => {
- expect(closed).toBe(true);
- });
- })
- .listen(0, () => {
- resolve();
- });
- });
-});
-
-afterAll(() => {
- return new Promise(resolve => {
- server.close(() => {
- resolve();
- });
- });
-});
-
-test("HTTP outgoing finished", done => {
- const closeHandler = jest.fn();
- const finishedHandler = jest.fn();
-
- server.on("request", (req, res) => {
- res.on("close", closeHandler);
- finished(res, finishedHandler);
- });
-
- http
- .request({
- port: server.address().port,
- method: "GET",
- })
- .on("response", res => {
- res.resume();
- })
- .end();
-
- setTimeout(() => {
- expect(closeHandler).toHaveBeenCalledTimes(1);
- expect(finishedHandler).toHaveBeenCalledTimes(1);
- done();
- }, 1000);
-});
-
-//<#END_FILE: test-http-outgoing-finished.js
diff --git a/test/js/node/test/parallel/http-outgoing-writablefinished.test.js b/test/js/node/test/parallel/http-outgoing-writablefinished.test.js
deleted file mode 100644
index 2788589d87..0000000000
--- a/test/js/node/test/parallel/http-outgoing-writablefinished.test.js
+++ /dev/null
@@ -1,42 +0,0 @@
-//#FILE: test-http-outgoing-writableFinished.js
-//#SHA1: f3fbc0d89cd03168f3ee92ed586b62dd5e3b8edb
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("HTTP server response writableFinished", async () => {
- const server = http.createServer((req, res) => {
- expect(res.writableFinished).toBe(false);
- res.on("finish", () => {
- expect(res.writableFinished).toBe(true);
- server.close();
- });
- res.end();
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const port = server.address().port;
-
- const clientRequest = http.request({
- port,
- method: "GET",
- path: "/",
- });
-
- expect(clientRequest.writableFinished).toBe(false);
-
- await new Promise(resolve => {
- clientRequest.on("finish", () => {
- expect(clientRequest.writableFinished).toBe(true);
- resolve();
- });
- clientRequest.end();
- expect(clientRequest.writableFinished).toBe(false);
- });
-});
-
-//<#END_FILE: test-http-outgoing-writableFinished.js
diff --git a/test/js/node/test/parallel/http-outgoing-write-types.test.js b/test/js/node/test/parallel/http-outgoing-write-types.test.js
deleted file mode 100644
index 6870939a90..0000000000
--- a/test/js/node/test/parallel/http-outgoing-write-types.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-http-outgoing-write-types.js
-//#SHA1: bdeac2ab8008bea1c7e0b22f8744176dea0410e2
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("HTTP outgoing write types", async () => {
- const httpServer = http.createServer((req, res) => {
- httpServer.close();
-
- expect(() => {
- res.write(["Throws."]);
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- }),
- );
-
- // should not throw
- expect(() => res.write("1a2b3c")).not.toThrow();
-
- // should not throw
- expect(() => res.write(new Uint8Array(1024))).not.toThrow();
-
- // should not throw
- expect(() => res.write(Buffer.from("1".repeat(1024)))).not.toThrow();
-
- res.end();
- });
-
- await new Promise(resolve => {
- httpServer.listen(0, () => {
- http.get({ port: httpServer.address().port }, resolve);
- });
- });
-});
-
-//<#END_FILE: test-http-outgoing-write-types.js
diff --git a/test/js/node/test/parallel/http-pause-no-dump.test.js b/test/js/node/test/parallel/http-pause-no-dump.test.js
deleted file mode 100644
index 1f32f2b0a6..0000000000
--- a/test/js/node/test/parallel/http-pause-no-dump.test.js
+++ /dev/null
@@ -1,41 +0,0 @@
-//#FILE: test-http-pause-no-dump.js
-//#SHA1: 30c3bd27f5edd0ba060a0d6833061d1ce6379cd5
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("HTTP pause should not dump", done => {
- const server = http.createServer((req, res) => {
- req.once("data", () => {
- req.pause();
- res.writeHead(200);
- res.end();
- res.on("finish", () => {
- expect(req._dumped).toBeFalsy();
- });
- });
- });
-
- server.listen(0, () => {
- const req = http.request(
- {
- port: server.address().port,
- method: "POST",
- path: "/",
- },
- res => {
- expect(res.statusCode).toBe(200);
- res.resume();
- res.on("end", () => {
- server.close();
- done();
- });
- },
- );
-
- req.end(Buffer.allocUnsafe(1024));
- });
-});
-
-//<#END_FILE: test-http-pause-no-dump.js
diff --git a/test/js/node/test/parallel/http-pause-resume-one-end.test.js b/test/js/node/test/parallel/http-pause-resume-one-end.test.js
deleted file mode 100644
index 52198ee8a3..0000000000
--- a/test/js/node/test/parallel/http-pause-resume-one-end.test.js
+++ /dev/null
@@ -1,70 +0,0 @@
-//#FILE: test-http-pause-resume-one-end.js
-//#SHA1: 69f25ca624d470d640d6366b6df27eba31668e96
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP server pause and resume", async () => {
- const server = http.Server(function (req, res) {
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.end("Hello World\n");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, resolve);
- });
-
- const opts = {
- port: server.address().port,
- headers: { connection: "close" },
- };
-
- await new Promise(resolve => {
- http.get(opts, res => {
- res.on(
- "data",
- jest.fn().mockImplementation(() => {
- res.pause();
- setImmediate(() => {
- res.resume();
- });
- }),
- );
-
- res.on("end", () => {
- expect(res.destroyed).toBe(false);
- });
-
- expect(res.destroyed).toBe(false);
-
- res.on("close", () => {
- expect(res.destroyed).toBe(true);
- resolve();
- });
- });
- });
-});
-
-//<#END_FILE: test-http-pause-resume-one-end.js
diff --git a/test/js/node/test/parallel/http-pause.test.js b/test/js/node/test/parallel/http-pause.test.js
deleted file mode 100644
index 74bca8bc34..0000000000
--- a/test/js/node/test/parallel/http-pause.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-//#FILE: test-http-pause.js
-//#SHA1: d7712077ebe0493c27ffd7180e73fdd409041bf7
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const expectedServer = "Request Body from Client";
-let resultServer = "";
-const expectedClient = "Response Body from Server";
-let resultClient = "";
-
-test("HTTP pause and resume", async () => {
- const server = http.createServer((req, res) => {
- console.error("pause server request");
- req.pause();
- setTimeout(() => {
- console.error("resume server request");
- req.resume();
- req.setEncoding("utf8");
- req.on("data", chunk => {
- resultServer += chunk;
- });
- req.on("end", () => {
- console.error(resultServer);
- res.writeHead(200);
- res.end(expectedClient);
- });
- }, 100);
- });
-
- await new Promise(resolve => {
- server.listen(0, function () {
- // Anonymous function rather than arrow function to test `this` value.
- expect(this).toBe(server);
- const req = http.request(
- {
- port: this.address().port,
- path: "/",
- method: "POST",
- },
- res => {
- console.error("pause client response");
- res.pause();
- setTimeout(() => {
- console.error("resume client response");
- res.resume();
- res.on("data", chunk => {
- resultClient += chunk;
- });
- res.on("end", () => {
- console.error(resultClient);
- server.close();
- resolve();
- });
- }, 100);
- },
- );
- req.end(expectedServer);
- });
- });
-
- expect(resultServer).toBe(expectedServer);
- expect(resultClient).toBe(expectedClient);
-});
-
-//<#END_FILE: test-http-pause.js
diff --git a/test/js/node/test/parallel/http-pipe-fs.test.js b/test/js/node/test/parallel/http-pipe-fs.test.js
deleted file mode 100644
index 8db6bebdd3..0000000000
--- a/test/js/node/test/parallel/http-pipe-fs.test.js
+++ /dev/null
@@ -1,90 +0,0 @@
-//#FILE: test-http-pipe-fs.js
-//#SHA1: eb13abd37a9e18b0b28077247a7d336b92b79fbc
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-
-const NUMBER_OF_STREAMS = 2;
-
-const tmpdir = path.join(os.tmpdir(), "node-test-http-pipe-fs");
-fs.mkdirSync(tmpdir, { recursive: true });
-
-const file = path.join(tmpdir, "http-pipe-fs-test.txt");
-
-describe("HTTP pipe to fs", () => {
- let server;
-
- beforeAll(() => {
- server = http.createServer((req, res) => {
- const stream = fs.createWriteStream(file);
- req.pipe(stream);
- stream.on("close", () => {
- res.writeHead(200);
- res.end();
- });
- });
- });
-
- afterAll(() => {
- return new Promise(resolve => server.close(resolve));
- });
-
- it("should handle multiple concurrent requests", async () => {
- await new Promise(resolve => server.listen(0, resolve));
-
- const port = server.address().port;
- http.globalAgent.maxSockets = 1;
-
- const makeRequest = () => {
- return new Promise(resolve => {
- const req = http.request(
- {
- port: port,
- method: "POST",
- headers: {
- "Content-Length": 5,
- },
- },
- res => {
- res.on("end", resolve);
- res.resume();
- },
- );
-
- req.end("12345");
- });
- };
-
- const requests = Array(NUMBER_OF_STREAMS).fill().map(makeRequest);
- await Promise.all(requests);
-
- expect.assertions(1);
- expect(true).toBe(true); // Dummy assertion to ensure the test ran
- });
-});
-
-//<#END_FILE: test-http-pipe-fs.js
diff --git a/test/js/node/test/parallel/http-proxy.test.js b/test/js/node/test/parallel/http-proxy.test.js
deleted file mode 100644
index dbb116434c..0000000000
--- a/test/js/node/test/parallel/http-proxy.test.js
+++ /dev/null
@@ -1,118 +0,0 @@
-//#FILE: test-http-proxy.js
-//#SHA1: 7b000418a5941e059d64a57b2f0b4fdfb43eb71d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-const cookies = [
- "session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT",
- "prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT",
-];
-
-const headers = { "content-type": "text/plain", "set-cookie": cookies, hello: "world" };
-
-test("HTTP proxy server", async () => {
- const backend = http.createServer((req, res) => {
- console.error("backend request");
- res.writeHead(200, headers);
- res.write("hello world\n");
- res.end();
- });
-
- const proxy = http.createServer((req, res) => {
- console.error(`proxy req headers: ${JSON.stringify(req.headers)}`);
- http.get(
- {
- port: backend.address().port,
- path: url.parse(req.url).pathname,
- },
- proxy_res => {
- console.error(`proxy res headers: ${JSON.stringify(proxy_res.headers)}`);
-
- expect(proxy_res.headers.hello).toBe("world");
- expect(proxy_res.headers["content-type"]).toBe("text/plain");
- expect(proxy_res.headers["set-cookie"]).toEqual(cookies);
-
- res.writeHead(proxy_res.statusCode, proxy_res.headers);
-
- proxy_res.on("data", chunk => {
- res.write(chunk);
- });
-
- proxy_res.on("end", () => {
- res.end();
- console.error("proxy res");
- });
- },
- );
- });
-
- let body = "";
-
- await new Promise(resolve => {
- let nlistening = 0;
- function startReq() {
- nlistening++;
- if (nlistening < 2) return;
-
- http.get(
- {
- port: proxy.address().port,
- path: "/test",
- },
- res => {
- console.error("got res");
- expect(res.statusCode).toBe(200);
-
- expect(res.headers.hello).toBe("world");
- expect(res.headers["content-type"]).toBe("text/plain");
- expect(res.headers["set-cookie"]).toEqual(cookies);
-
- res.setEncoding("utf8");
- res.on("data", chunk => {
- body += chunk;
- });
- res.on("end", () => {
- proxy.close();
- backend.close();
- console.error("closed both");
- resolve();
- });
- },
- );
- console.error("client req");
- }
-
- console.error("listen proxy");
- proxy.listen(0, startReq);
-
- console.error("listen backend");
- backend.listen(0, startReq);
- });
-
- expect(body).toBe("hello world\n");
-});
-
-//<#END_FILE: test-http-proxy.js
diff --git a/test/js/node/test/parallel/http-request-arguments.test.js b/test/js/node/test/parallel/http-request-arguments.test.js
deleted file mode 100644
index d202ccc5af..0000000000
--- a/test/js/node/test/parallel/http-request-arguments.test.js
+++ /dev/null
@@ -1,26 +0,0 @@
-//#FILE: test-http-request-arguments.js
-//#SHA1: c02b492e2dbf5fa6ffcda8a80c3e4ad41bb0c9e5
-//-----------------
-"use strict";
-
-const http = require("http");
-
-// Test providing both a url and options, with the options partially
-// replacing address and port portions of the URL provided.
-test("http.get with url and options", done => {
- const server = http.createServer((req, res) => {
- expect(req.url).toBe("/testpath");
- res.end();
- server.close();
- });
-
- server.listen(0, () => {
- const port = server.address().port;
- http.get("http://example.com/testpath", { hostname: "localhost", port }, res => {
- res.resume();
- done();
- });
- });
-});
-
-//<#END_FILE: test-http-request-arguments.js
diff --git a/test/js/node/test/parallel/http-request-end-twice.test.js b/test/js/node/test/parallel/http-request-end-twice.test.js
deleted file mode 100644
index b1d2c8a209..0000000000
--- a/test/js/node/test/parallel/http-request-end-twice.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-http-request-end-twice.js
-//#SHA1: c8c502b3bf8a681a7acb9afa603a13cebaf1d00e
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("http request end twice", async () => {
- const server = http.Server((req, res) => {
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.end("hello world\n");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const req = http.get({ port: server.address().port }, res => {
- res.on("end", () => {
- expect(req.end()).toBe(req);
- server.close(resolve);
- });
- res.resume();
- });
- });
- });
-});
-
-//<#END_FILE: test-http-request-end-twice.js
diff --git a/test/js/node/test/parallel/http-request-end.test.js b/test/js/node/test/parallel/http-request-end.test.js
deleted file mode 100644
index 9ed911d1ad..0000000000
--- a/test/js/node/test/parallel/http-request-end.test.js
+++ /dev/null
@@ -1,74 +0,0 @@
-//#FILE: test-http-request-end.js
-//#SHA1: e86769441d8d182d32d60d4631e32fbcc2675ed9
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-const expected = "Post Body For Test";
-
-test("http request end", async () => {
- const server = http.Server((req, res) => {
- let result = "";
-
- req.setEncoding("utf8");
- req.on("data", chunk => {
- result += chunk;
- });
-
- req.on("end", () => {
- expect(result).toBe(expected);
- res.writeHead(200);
- res.end("hello world\n");
- server.close();
- });
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const req = http
- .request(
- {
- port: server.address().port,
- path: "/",
- method: "POST",
- },
- res => {
- expect(res.statusCode).toBe(200);
- res.resume();
- resolve();
- },
- )
- .on("error", e => {
- console.error(e.message);
- process.exit(1);
- });
-
- const result = req.end(expected);
-
- expect(req).toBe(result);
- });
- });
-});
-
-//<#END_FILE: test-http-request-end.js
diff --git a/test/js/node/test/parallel/http-request-large-payload.test.js b/test/js/node/test/parallel/http-request-large-payload.test.js
deleted file mode 100644
index ea69bdc95a..0000000000
--- a/test/js/node/test/parallel/http-request-large-payload.test.js
+++ /dev/null
@@ -1,33 +0,0 @@
-//#FILE: test-http-request-large-payload.js
-//#SHA1: 236870617a867c47c0767e351433c5deb7c87120
-//-----------------
-"use strict";
-
-// This test ensures Node.js doesn't throw an error when making requests with
-// the payload 16kb or more in size.
-// https://github.com/nodejs/node/issues/2821
-
-const http = require("http");
-
-test("HTTP request with large payload", done => {
- const server = http.createServer((req, res) => {
- res.writeHead(200);
- res.end();
-
- server.close();
- done();
- });
-
- server.listen(0, function () {
- const req = http.request({
- method: "POST",
- port: this.address().port,
- });
-
- const payload = Buffer.alloc(16390, "Й");
- req.write(payload);
- req.end();
- });
-});
-
-//<#END_FILE: test-http-request-large-payload.js
diff --git a/test/js/node/test/parallel/http-res-write-after-end.test.js b/test/js/node/test/parallel/http-res-write-after-end.test.js
deleted file mode 100644
index 45a17ed5e7..0000000000
--- a/test/js/node/test/parallel/http-res-write-after-end.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http-res-write-after-end.js
-//#SHA1: e579896871bf375190397b4f7e99f37cc156e7c9
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP response write after end", async () => {
- const server = http.Server((req, res) => {
- res.on("error", error => {
- expect(error).toMatchObject({
- code: "ERR_STREAM_WRITE_AFTER_END",
- name: "Error",
- message: expect.any(String),
- });
- });
-
- res.write("This should write.");
- res.end();
-
- const r = res.write("This should raise an error.");
- // Write after end should return false
- expect(r).toBe(false);
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- server.close(resolve);
- });
- });
- });
-});
-
-//<#END_FILE: test-http-res-write-after-end.js
diff --git a/test/js/node/test/parallel/http-response-readable.test.js b/test/js/node/test/parallel/http-response-readable.test.js
deleted file mode 100644
index 4af51a42e5..0000000000
--- a/test/js/node/test/parallel/http-response-readable.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-http-response-readable.js
-//#SHA1: bfdd12475c68879668c3019c685001244559fb20
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("HTTP response readable state", async () => {
- const testServer = new http.Server((req, res) => {
- res.writeHead(200);
- res.end("Hello world");
- });
-
- await new Promise(resolve => {
- testServer.listen(0, () => {
- const port = testServer.address().port;
- http.get({ port }, res => {
- expect(res.readable).toBe(true);
- res.on("end", () => {
- expect(res.readable).toBe(false);
- testServer.close(resolve);
- });
- res.resume();
- });
- });
- });
-});
-
-//<#END_FILE: test-http-response-readable.js
diff --git a/test/js/node/test/parallel/http-response-writehead-returns-this.test.js b/test/js/node/test/parallel/http-response-writehead-returns-this.test.js
deleted file mode 100644
index 9418c9e6b0..0000000000
--- a/test/js/node/test/parallel/http-response-writehead-returns-this.test.js
+++ /dev/null
@@ -1,29 +0,0 @@
-//#FILE: test-http-response-writehead-returns-this.js
-//#SHA1: 8a079a3635356290e98a1e7c4eb89b97680b3889
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("http.ServerResponse.writeHead() returns this", done => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, { "a-header": "a-header-value" }).end("abc");
- });
-
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- expect(res.headers["a-header"]).toBe("a-header-value");
-
- const chunks = [];
-
- res.on("data", chunk => chunks.push(chunk));
- res.on("end", () => {
- expect(Buffer.concat(chunks).toString()).toBe("abc");
- server.close();
- done();
- });
- });
- });
-});
-
-//<#END_FILE: test-http-response-writehead-returns-this.js
diff --git a/test/js/node/test/parallel/http-server-close-idle-wait-response.test.js b/test/js/node/test/parallel/http-server-close-idle-wait-response.test.js
deleted file mode 100644
index 415d32e729..0000000000
--- a/test/js/node/test/parallel/http-server-close-idle-wait-response.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-http-server-close-idle-wait-response.js
-//#SHA1: 04c4c10103faabfd084635c9280824668eb0ba18
-//-----------------
-"use strict";
-
-const { createServer, get } = require("http");
-
-test("HTTP server close idle connections after response", async () => {
- const server = createServer(
- jest.fn((req, res) => {
- req.resume();
-
- setTimeout(() => {
- res.writeHead(204, { Connection: "keep-alive", "Keep-Alive": "timeout=1" });
- res.end();
- }, 1000);
- }),
- );
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const port = server.address().port;
-
- get(`http://localhost:${port}`, res => {
- server.close();
- }).on("finish", () => {
- setTimeout(() => {
- server.closeIdleConnections();
- resolve();
- }, 500);
- });
- });
- });
-
- expect(server.listeners("request")[0]).toHaveBeenCalledTimes(1);
-});
-
-//<#END_FILE: test-http-server-close-idle-wait-response.js
diff --git a/test/js/node/test/parallel/http-server-delete-parser.test.js b/test/js/node/test/parallel/http-server-delete-parser.test.js
deleted file mode 100644
index f16d12c848..0000000000
--- a/test/js/node/test/parallel/http-server-delete-parser.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-http-server-delete-parser.js
-//#SHA1: 49465ae50d9dac34e834dcb19c02e75b284acdc2
-//-----------------
-"use strict";
-
-const http = require("http");
-
-test("HTTP server deletes parser after write", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.write("okay", () => {
- delete res.socket.parser;
- });
- res.end();
- });
-
- await new Promise(resolve => {
- server.listen(0, "127.0.0.1", resolve);
- });
-
- const { port } = server.address();
-
- const req = http.request({
- port,
- host: "127.0.0.1",
- method: "GET",
- });
-
- await new Promise(resolve => {
- req.end(resolve);
- });
-
- server.close();
-});
-
-//<#END_FILE: test-http-server-delete-parser.js
diff --git a/test/js/node/test/parallel/http-server-multiheaders.test.js b/test/js/node/test/parallel/http-server-multiheaders.test.js
deleted file mode 100644
index f0ba4b4d61..0000000000
--- a/test/js/node/test/parallel/http-server-multiheaders.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-//#FILE: test-http-server-multiheaders.js
-//#SHA1: 48e657fa74fb8aeeb2d04661ac760ff0cf5bf12a
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-// Verify that the HTTP server implementation handles multiple instances
-// of the same header as per RFC2616: joining the handful of fields by ', '
-// that support it, and dropping duplicates for other fields.
-
-const http = require("http");
-
-test("HTTP server handles multiple instances of the same header correctly", async () => {
- const server = http.createServer((req, res) => {
- expect(req.headers.accept).toBe("abc, def, ghijklmnopqrst");
- expect(req.headers.host).toBe("foo");
- expect(req.headers["www-authenticate"]).toBe("foo, bar, baz");
- expect(req.headers["proxy-authenticate"]).toBe("foo, bar, baz");
- expect(req.headers["x-foo"]).toBe("bingo");
- expect(req.headers["x-bar"]).toBe("banjo, bango");
- expect(req.headers["sec-websocket-protocol"]).toBe("chat, share");
- expect(req.headers["sec-websocket-extensions"]).toBe("foo; 1, bar; 2, baz");
- expect(req.headers.constructor).toBe("foo, bar, baz");
-
- res.writeHead(200, { "Content-Type": "text/plain" });
- res.end("EOF");
-
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({
- host: "localhost",
- port: server.address().port,
- path: "/",
- headers: [
- ["accept", "abc"],
- ["accept", "def"],
- ["Accept", "ghijklmnopqrst"],
- ["host", "foo"],
- ["Host", "bar"],
- ["hOst", "baz"],
- ["www-authenticate", "foo"],
- ["WWW-Authenticate", "bar"],
- ["WWW-AUTHENTICATE", "baz"],
- ["proxy-authenticate", "foo"],
- ["Proxy-Authenticate", "bar"],
- ["PROXY-AUTHENTICATE", "baz"],
- ["x-foo", "bingo"],
- ["x-bar", "banjo"],
- ["x-bar", "bango"],
- ["sec-websocket-protocol", "chat"],
- ["sec-websocket-protocol", "share"],
- ["sec-websocket-extensions", "foo; 1"],
- ["sec-websocket-extensions", "bar; 2"],
- ["sec-websocket-extensions", "baz"],
- ["constructor", "foo"],
- ["constructor", "bar"],
- ["constructor", "baz"],
- ],
- });
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-server-multiheaders.js
diff --git a/test/js/node/test/parallel/http-server-non-utf8-header.test.js b/test/js/node/test/parallel/http-server-non-utf8-header.test.js
deleted file mode 100644
index de10907234..0000000000
--- a/test/js/node/test/parallel/http-server-non-utf8-header.test.js
+++ /dev/null
@@ -1,67 +0,0 @@
-//#FILE: test-http-server-non-utf8-header.js
-//#SHA1: bc84accb29cf80323d0fb55455a596f36a7933b2
-//-----------------
-"use strict";
-const http = require("http");
-
-const nonUtf8Header = "bår";
-const nonUtf8ToLatin1 = Buffer.from(nonUtf8Header).toString("latin1");
-
-test("HTTP server with non-UTF8 header", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, ["content-disposition", Buffer.from(nonUtf8Header).toString("binary")]);
- res.end("hello");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- expect(res.statusCode).toBe(200);
- expect(res.headers["content-disposition"]).toBe(nonUtf8ToLatin1);
- res.resume().on("end", () => {
- server.close(resolve);
- });
- });
- });
- });
-});
-
-test("HTTP server with multi-value non-UTF8 header", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, ["content-disposition", [Buffer.from(nonUtf8Header).toString("binary")]]);
- res.end("hello");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- expect(res.statusCode).toBe(200);
- expect(res.headers["content-disposition"]).toBe(nonUtf8ToLatin1);
- res.resume().on("end", () => {
- server.close(resolve);
- });
- });
- });
- });
-});
-
-test("HTTP server with non-UTF8 header and Content-Length", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, ["Content-Length", "5", "content-disposition", Buffer.from(nonUtf8Header).toString("binary")]);
- res.end("hello");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- expect(res.statusCode).toBe(200);
- expect(res.headers["content-disposition"]).toBe(nonUtf8ToLatin1);
- res.resume().on("end", () => {
- server.close(resolve);
- });
- });
- });
- });
-});
-
-//<#END_FILE: test-http-server-non-utf8-header.js
diff --git a/test/js/node/test/parallel/http-server-options-incoming-message.test.js b/test/js/node/test/parallel/http-server-options-incoming-message.test.js
deleted file mode 100644
index e8c595a1aa..0000000000
--- a/test/js/node/test/parallel/http-server-options-incoming-message.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-http-server-options-incoming-message.js
-//#SHA1: 5d553fff4a2a29f67836269914e5f33b7e91b64e
-//-----------------
-"use strict";
-
-/**
- * This test covers http.Server({ IncomingMessage }) option:
- * With IncomingMessage option the server should use
- * the new class for creating req Object instead of the default
- * http.IncomingMessage.
- */
-const http = require("http");
-
-class MyIncomingMessage extends http.IncomingMessage {
- getUserAgent() {
- return this.headers["user-agent"] || "unknown";
- }
-}
-
-test("http.Server with custom IncomingMessage", done => {
- const server = http.createServer(
- {
- IncomingMessage: MyIncomingMessage,
- },
- (req, res) => {
- expect(req.getUserAgent()).toBe("node-test");
- res.statusCode = 200;
- res.end();
- },
- );
-
- server.listen(() => {
- const { port } = server.address();
-
- http.get(
- {
- port,
- headers: {
- "User-Agent": "node-test",
- },
- },
- res => {
- expect(res.statusCode).toBe(200);
- res.on("end", () => {
- server.close();
- done();
- });
- res.resume();
- },
- );
- });
-});
-
-//<#END_FILE: test-http-server-options-incoming-message.js
diff --git a/test/js/node/test/parallel/http-server-options-server-response.test.js b/test/js/node/test/parallel/http-server-options-server-response.test.js
deleted file mode 100644
index 67155a18ac..0000000000
--- a/test/js/node/test/parallel/http-server-options-server-response.test.js
+++ /dev/null
@@ -1,49 +0,0 @@
-//#FILE: test-http-server-options-server-response.js
-//#SHA1: ae3128a67e671596c2470bb973747640620b807a
-//-----------------
-"use strict";
-
-/**
- * This test covers http.Server({ ServerResponse }) option:
- * With ServerResponse option the server should use
- * the new class for creating res Object instead of the default
- * http.ServerResponse.
- */
-const http = require("http");
-
-class MyServerResponse extends http.ServerResponse {
- status(code) {
- return this.writeHead(code, { "Content-Type": "text/plain" });
- }
-}
-
-test("http.Server with custom ServerResponse", done => {
- const server = http.Server(
- {
- ServerResponse: MyServerResponse,
- },
- jest.fn((req, res) => {
- res.status(200);
- res.end();
- }),
- );
-
- server.listen(() => {
- const port = server.address().port;
-
- http.get({ port }, res => {
- expect(res.statusCode).toBe(200);
- res.on("end", () => {
- server.close();
- done();
- });
- res.resume();
- });
- });
-
- server.on("close", () => {
- expect(server.listeners("request")[0]).toHaveBeenCalledTimes(1);
- });
-});
-
-//<#END_FILE: test-http-server-options-server-response.js
diff --git a/test/js/node/test/parallel/http-server-reject-chunked-with-content-length.test.js b/test/js/node/test/parallel/http-server-reject-chunked-with-content-length.test.js
deleted file mode 100644
index 9bd2f8b82b..0000000000
--- a/test/js/node/test/parallel/http-server-reject-chunked-with-content-length.test.js
+++ /dev/null
@@ -1,38 +0,0 @@
-//#FILE: test-http-server-reject-chunked-with-content-length.js
-//#SHA1: e94d6c381c99ba72c2cc2bcbc4c6474a7c63819a
-//-----------------
-"use strict";
-
-const http = require("http");
-const net = require("net");
-
-const reqstr = "POST / HTTP/1.1\r\n" + "Content-Length: 1\r\n" + "Transfer-Encoding: chunked\r\n\r\n";
-
-test("HTTP server rejects chunked with content length", done => {
- const server = http.createServer(expect.any(Function));
-
- server.on("clientError", err => {
- expect(err.message).toMatch(/^Parse Error/);
- expect(err.code).toBe("HPE_INVALID_TRANSFER_ENCODING");
- server.close();
- });
-
- server.listen(0, () => {
- const client = net.connect({ port: server.address().port }, () => {
- client.write(reqstr);
- client.end();
- });
-
- client.on("data", () => {
- // Should not get to this point because the server should simply
- // close the connection without returning any data.
- throw new Error("no data should be returned by the server");
- });
-
- client.on("end", () => {
- done();
- });
- });
-});
-
-//<#END_FILE: test-http-server-reject-chunked-with-content-length.js
diff --git a/test/js/node/test/parallel/http-server-stale-close.test.js b/test/js/node/test/parallel/http-server-stale-close.test.js
deleted file mode 100644
index ea0f99dcf0..0000000000
--- a/test/js/node/test/parallel/http-server-stale-close.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-http-server-stale-close.js
-//#SHA1: 5c246ffb442bd9ff61779bc300db12d2f3394be4
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const fork = require("child_process").fork;
-
-if (process.env.NODE_TEST_FORK_PORT) {
- const req = http.request(
- {
- headers: { "Content-Length": "42" },
- method: "POST",
- host: "127.0.0.1",
- port: +process.env.NODE_TEST_FORK_PORT,
- },
- process.exit,
- );
- req.write("BAM");
- req.end();
-} else {
- test("HTTP server stale close", async () => {
- const server = http.createServer((req, res) => {
- res.writeHead(200, { "Content-Length": "42" });
- req.pipe(res);
- expect(req.destroyed).toBe(false);
- req.on("close", () => {
- expect(req.destroyed).toBe(true);
- server.close();
- res.end();
- });
- });
-
- await new Promise(resolve => {
- server.listen(0, function () {
- fork(__filename, {
- env: { ...process.env, NODE_TEST_FORK_PORT: this.address().port },
- });
- resolve();
- });
- });
- });
-}
-
-//<#END_FILE: test-http-server-stale-close.js
diff --git a/test/js/node/test/parallel/http-server-write-after-end.test.js b/test/js/node/test/parallel/http-server-write-after-end.test.js
deleted file mode 100644
index c842524c4b..0000000000
--- a/test/js/node/test/parallel/http-server-write-after-end.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-http-server-write-after-end.js
-//#SHA1: cacf983393f707ddefc829a25ce16a5bf6f41c19
-//-----------------
-"use strict";
-
-const http = require("http");
-
-// Fix for https://github.com/nodejs/node/issues/14368
-
-test("HTTP server write after end", done => {
- const server = http.createServer(handle);
-
- function handle(req, res) {
- res.on("error", jest.fn());
-
- res.write("hello");
- res.end();
-
- setImmediate(() => {
- res.write("world", err => {
- expect(err).toEqual(
- expect.objectContaining({
- code: "ERR_STREAM_WRITE_AFTER_END",
- name: "Error",
- message: expect.any(String),
- }),
- );
- server.close();
- done();
- });
- });
- }
-
- server.listen(0, () => {
- http.get(`http://localhost:${server.address().port}`);
- });
-});
-
-//<#END_FILE: test-http-server-write-after-end.js
diff --git a/test/js/node/test/parallel/http-server-write-end-after-end.test.js b/test/js/node/test/parallel/http-server-write-end-after-end.test.js
deleted file mode 100644
index 836b835e1f..0000000000
--- a/test/js/node/test/parallel/http-server-write-end-after-end.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-http-server-write-end-after-end.js
-//#SHA1: 5b7550b3241cd6b99e607419c3b81d2df519b641
-//-----------------
-"use strict";
-
-const http = require("http");
-
-let server;
-
-beforeAll(() => {
- server = http.createServer(handle);
-});
-
-afterAll(() => {
- server.close();
-});
-
-function handle(req, res) {
- res.on("error", jest.fn());
-
- res.write("hello");
- res.end();
-
- setImmediate(() => {
- res.end("world");
- process.nextTick(() => {
- server.close();
- });
- res.write("world", err => {
- expect(err).toMatchObject({
- code: "ERR_STREAM_WRITE_AFTER_END",
- name: "Error",
- message: expect.any(String),
- });
- server.close();
- });
- });
-}
-
-test("http server write end after end", done => {
- server.listen(0, () => {
- http.get(`http://localhost:${server.address().port}`);
- done();
- });
-});
-
-//<#END_FILE: test-http-server-write-end-after-end.js
diff --git a/test/js/node/test/parallel/http-set-header-chain.test.js b/test/js/node/test/parallel/http-set-header-chain.test.js
deleted file mode 100644
index 85aac8f9e1..0000000000
--- a/test/js/node/test/parallel/http-set-header-chain.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-//#FILE: test-http-set-header-chain.js
-//#SHA1: e009f5ffdce12a659bd2d3402449cd0095d79aa2
-//-----------------
-"use strict";
-
-const http = require("http");
-
-const expected = {
- __proto__: null,
- testheader1: "foo",
- testheader2: "bar",
- testheader3: "xyz",
-};
-
-test("HTTP setHeader chaining", async () => {
- const server = http.createServer((req, res) => {
- let retval = res.setHeader("testheader1", "foo");
-
- // Test that the setHeader returns the same response object.
- expect(retval).toBe(res);
-
- retval = res.setHeader("testheader2", "bar").setHeader("testheader3", "xyz");
- // Test that chaining works for setHeader.
- expect(res.getHeaders()).toEqual(expected);
- res.end("ok");
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- res.on("data", () => {});
- res.on("end", () => {
- server.close(resolve);
- });
- });
- });
- });
-});
-
-//<#END_FILE: test-http-set-header-chain.js
diff --git a/test/js/node/test/parallel/http-upgrade-reconsume-stream.test.js b/test/js/node/test/parallel/http-upgrade-reconsume-stream.test.js
deleted file mode 100644
index 57d72bf41d..0000000000
--- a/test/js/node/test/parallel/http-upgrade-reconsume-stream.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-//#FILE: test-http-upgrade-reconsume-stream.js
-//#SHA1: 4117d0b2212d192173b5bd6bf2ef7fe82f627079
-//-----------------
-"use strict";
-
-const tls = require("tls");
-const http = require("http");
-
-// Tests that, after the HTTP parser stopped owning a socket that emits an
-// 'upgrade' event, another C++ stream can start owning it (e.g. a TLSSocket).
-
-test("HTTP upgrade and TLSSocket creation", done => {
- const server = http.createServer(expect.any(Function));
-
- server.on("upgrade", (request, socket, head) => {
- // This should not crash.
- new tls.TLSSocket(socket);
- server.close();
- socket.destroy();
- done();
- });
-
- server.listen(0, () => {
- http
- .get({
- port: server.address().port,
- headers: {
- "Connection": "Upgrade",
- "Upgrade": "websocket",
- },
- })
- .on("error", () => {});
- });
-});
-
-//<#END_FILE: test-http-upgrade-reconsume-stream.js
diff --git a/test/js/node/test/parallel/http-url.parse-auth-with-header-in-request.test.js b/test/js/node/test/parallel/http-url.parse-auth-with-header-in-request.test.js
deleted file mode 100644
index a87bfbd3ac..0000000000
--- a/test/js/node/test/parallel/http-url.parse-auth-with-header-in-request.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-http-url.parse-auth-with-header-in-request.js
-//#SHA1: 396adc5e441a57d24b11a42513c834b6b11ea7ff
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-test("HTTP request with authorization header in request", async () => {
- function check(request) {
- // The correct authorization header is be passed
- expect(request.headers.authorization).toBe("NoAuthForYOU");
- }
-
- const server = http.createServer((request, response) => {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const testURL = url.parse(`http://asdf:qwer@localhost:${server.address().port}`);
- // The test here is if you set a specific authorization header in the
- // request we should not override that with basic auth
- testURL.headers = {
- Authorization: "NoAuthForYOU",
- };
-
- // make the request
- http.request(testURL).end();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-url.parse-auth-with-header-in-request.js
diff --git a/test/js/node/test/parallel/http-url.parse-auth.test.js b/test/js/node/test/parallel/http-url.parse-auth.test.js
deleted file mode 100644
index 439d699393..0000000000
--- a/test/js/node/test/parallel/http-url.parse-auth.test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-//#FILE: test-http-url.parse-auth.js
-//#SHA1: 97f9b1c737c705489b2d6402750034291a9f6f63
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-test("http url parse auth", async () => {
- function check(request) {
- // The correct authorization header is be passed
- expect(request.headers.authorization).toBe("Basic dXNlcjpwYXNzOg==");
- }
-
- const server = http.createServer((request, response) => {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const port = server.address().port;
- // username = "user", password = "pass:"
- const testURL = url.parse(`http://user:pass%3A@localhost:${port}`);
-
- // make the request
- http.request(testURL).end();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-url.parse-auth.js
diff --git a/test/js/node/test/parallel/http-url.parse-basic.test.js b/test/js/node/test/parallel/http-url.parse-basic.test.js
deleted file mode 100644
index 9d2d329d3f..0000000000
--- a/test/js/node/test/parallel/http-url.parse-basic.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-http-url.parse-basic.js
-//#SHA1: f2f2841de1c82e38067e73196926090f350d89c6
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-let testURL;
-
-// Make sure the basics work
-function check(request) {
- // Default method should still be 'GET'
- expect(request.method).toBe("GET");
- // There are no URL params, so you should not see any
- expect(request.url).toBe("/");
- // The host header should use the url.parse.hostname
- expect(request.headers.host).toBe(`${testURL.hostname}:${testURL.port}`);
-}
-
-test("HTTP URL parsing basics", async () => {
- const server = http.createServer((request, response) => {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- testURL = url.parse(`http://localhost:${server.address().port}`);
-
- // make the request
- const clientRequest = http.request(testURL);
- // Since there is a little magic with the agent
- // make sure that an http request uses the http.Agent
- expect(clientRequest.agent).toBeInstanceOf(http.Agent);
- clientRequest.end();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-url.parse-basic.js
diff --git a/test/js/node/test/parallel/http-url.parse-https.request.test.js b/test/js/node/test/parallel/http-url.parse-https.request.test.js
deleted file mode 100644
index 6b8a992569..0000000000
--- a/test/js/node/test/parallel/http-url.parse-https.request.test.js
+++ /dev/null
@@ -1,81 +0,0 @@
-//#FILE: test-http-url.parse-https.request.js
-//#SHA1: e9b9e39f28d5d2633f9444150977b748bc8995cb
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-
-const https = require("https");
-const url = require("url");
-const { readKey } = require("../common/fixtures");
-
-let common;
-try {
- common = require("../common");
-} catch (e) {
- // For Bun compatibility
- common = {
- hasCrypto: true,
- skip: console.log,
- };
-}
-
-if (!common.hasCrypto) {
- common.skip("missing crypto");
- process.exit(0);
-}
-
-// https options
-const httpsOptions = {
- key: readKey("agent1-key.pem"),
- cert: readKey("agent1-cert.pem"),
-};
-
-function check(request) {
- // Assert that I'm https
- expect(request.socket._secureEstablished).toBeTruthy();
-}
-
-test("HTTPS request with URL object", done => {
- const server = https.createServer(httpsOptions, function (request, response) {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- server.listen(0, function () {
- const testURL = url.parse(`https://localhost:${this.address().port}`);
- testURL.rejectUnauthorized = false;
-
- // make the request
- const clientRequest = https.request(testURL);
- // Since there is a little magic with the agent
- // make sure that the request uses the https.Agent
- expect(clientRequest.agent).toBeInstanceOf(https.Agent);
- clientRequest.end();
- done();
- });
-});
-
-//<#END_FILE: test-http-url.parse-https.request.js
diff --git a/test/js/node/test/parallel/http-url.parse-only-support-http-https-protocol.test.js b/test/js/node/test/parallel/http-url.parse-only-support-http-https-protocol.test.js
deleted file mode 100644
index 4f3c5dd20a..0000000000
--- a/test/js/node/test/parallel/http-url.parse-only-support-http-https-protocol.test.js
+++ /dev/null
@@ -1,52 +0,0 @@
-//#FILE: test-http-url.parse-only-support-http-https-protocol.js
-//#SHA1: 924c029f73164388b765c128401affa763af7b56
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-const invalidUrls = [
- "file:///whatever",
- "mailto:asdf@asdf.com",
- "ftp://www.example.com",
- "javascript:alert('hello');",
- "xmpp:foo@bar.com",
- "f://some.host/path",
-];
-
-describe("http.request with invalid protocols", () => {
- test.each(invalidUrls)("throws for invalid URL: %s", invalid => {
- expect(() => {
- http.request(url.parse(invalid));
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_PROTOCOL",
- name: "TypeError",
- message: expect.any(String),
- }),
- );
- });
-});
-
-//<#END_FILE: test-http-url.parse-only-support-http-https-protocol.js
diff --git a/test/js/node/test/parallel/http-url.parse-path.test.js b/test/js/node/test/parallel/http-url.parse-path.test.js
deleted file mode 100644
index 21b456b66f..0000000000
--- a/test/js/node/test/parallel/http-url.parse-path.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-http-url.parse-path.js
-//#SHA1: 9eb246a6c09b70b76260a83bec4bb25452d38b7d
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-test("http request url parsing", async () => {
- function check(request) {
- // A path should come over
- expect(request.url).toBe("/asdf");
- }
-
- const server = http.createServer((request, response) => {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const testURL = url.parse(`http://localhost:${server.address().port}/asdf`);
-
- // make the request
- http.request(testURL).end();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-url.parse-path.js
diff --git a/test/js/node/test/parallel/http-url.parse-post.test.js b/test/js/node/test/parallel/http-url.parse-post.test.js
deleted file mode 100644
index 800cde5e39..0000000000
--- a/test/js/node/test/parallel/http-url.parse-post.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-http-url.parse-post.js
-//#SHA1: e0e7f97c725fb9eaa6058365bef5021e9710e857
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-let testURL;
-
-function check(request) {
- // url.parse should not mess with the method
- expect(request.method).toBe("POST");
- // Everything else should be right
- expect(request.url).toBe("/asdf?qwer=zxcv");
- // The host header should use the url.parse.hostname
- expect(request.headers.host).toBe(`${testURL.hostname}:${testURL.port}`);
-}
-
-test("http url parse post", async () => {
- const server = http.createServer((request, response) => {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- testURL = url.parse(`http://localhost:${server.address().port}/asdf?qwer=zxcv`);
- testURL.method = "POST";
-
- // make the request
- http.request(testURL).end();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-url.parse-post.js
diff --git a/test/js/node/test/parallel/http-url.parse-search.test.js b/test/js/node/test/parallel/http-url.parse-search.test.js
deleted file mode 100644
index fe07df2f63..0000000000
--- a/test/js/node/test/parallel/http-url.parse-search.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http-url.parse-search.js
-//#SHA1: 11d08b9c62625b7b554d5fb46d63c4aaa77c1a7c
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-const url = require("url");
-
-test("HTTP request URL parsing with search params", async () => {
- function check(request) {
- // A path should come over with params
- expect(request.url).toBe("/asdf?qwer=zxcv");
- }
-
- const server = http.createServer((request, response) => {
- // Run the check function
- check(request);
- response.writeHead(200, {});
- response.end("ok");
- server.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- const port = server.address().port;
- const testURL = url.parse(`http://localhost:${port}/asdf?qwer=zxcv`);
-
- // make the request
- http.request(testURL).end();
- resolve();
- });
- });
-});
-
-//<#END_FILE: test-http-url.parse-search.js
diff --git a/test/js/node/test/parallel/http-write-empty-string.test.js b/test/js/node/test/parallel/http-write-empty-string.test.js
deleted file mode 100644
index 16e1b0def3..0000000000
--- a/test/js/node/test/parallel/http-write-empty-string.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-http-write-empty-string.js
-//#SHA1: 779199784d3142e353324041eeb30924c7e4d5b1
-//-----------------
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-"use strict";
-const http = require("http");
-
-test("http write empty string", async () => {
- const server = http.createServer(function (request, response) {
- console.log(`responding to ${request.url}`);
-
- response.writeHead(200, { "Content-Type": "text/plain" });
- response.write("1\n");
- response.write("");
- response.write("2\n");
- response.write("");
- response.end("3\n");
-
- this.close();
- });
-
- await new Promise(resolve => {
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- let response = "";
-
- expect(res.statusCode).toBe(200);
- res.setEncoding("ascii");
- res.on("data", chunk => {
- response += chunk;
- });
- res.on("end", () => {
- expect(response).toBe("1\n2\n3\n");
- resolve();
- });
- });
- });
- });
-});
-
-//<#END_FILE: test-http-write-empty-string.js
diff --git a/test/js/node/test/parallel/http-zerolengthbuffer.test.js b/test/js/node/test/parallel/http-zerolengthbuffer.test.js
deleted file mode 100644
index 8c82c7a82f..0000000000
--- a/test/js/node/test/parallel/http-zerolengthbuffer.test.js
+++ /dev/null
@@ -1,30 +0,0 @@
-//#FILE: test-http-zerolengthbuffer.js
-//#SHA1: 28fff143238744f829f63936c8902047ad2c2fc5
-//-----------------
-"use strict";
-// Serving up a zero-length buffer should work.
-
-const http = require("http");
-
-test("Serve zero-length buffer", done => {
- const server = http.createServer((req, res) => {
- const buffer = Buffer.alloc(0);
- res.writeHead(200, { "Content-Type": "text/html", "Content-Length": buffer.length });
- res.end(buffer);
- });
-
- server.listen(0, () => {
- http.get({ port: server.address().port }, res => {
- const dataHandler = jest.fn();
- res.on("data", dataHandler);
-
- res.on("end", () => {
- expect(dataHandler).not.toHaveBeenCalled();
- server.close();
- done();
- });
- });
- });
-});
-
-//<#END_FILE: test-http-zerolengthbuffer.js
diff --git a/test/js/node/test/parallel/http2-binding.test.js b/test/js/node/test/parallel/http2-binding.test.js
deleted file mode 100644
index a7ea7fb939..0000000000
--- a/test/js/node/test/parallel/http2-binding.test.js
+++ /dev/null
@@ -1,18 +0,0 @@
-//#FILE: test-http2-binding.js
-//#SHA1: 73c6e6b3c2f9b4c9c06183713dbf28454185a1a0
-//-----------------
-const http2 = require('http2');
-
-describe('HTTP/2 Binding', () => {
- beforeAll(() => {
- // Skip all tests in this file
- jest.spyOn(console, 'log').mockImplementation(() => {});
- console.log('Skipping HTTP/2 binding tests - internal bindings not available');
- });
-
- test('SKIP: HTTP/2 binding tests', () => {
- expect(true).toBe(true);
- });
-});
-
-//<#END_FILE: test-http2-binding.test.js
diff --git a/test/js/node/test/parallel/http2-client-priority-before-connect.test.js b/test/js/node/test/parallel/http2-client-priority-before-connect.test.js
deleted file mode 100644
index 273aa7bf44..0000000000
--- a/test/js/node/test/parallel/http2-client-priority-before-connect.test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-//#FILE: test-http2-client-priority-before-connect.js
-//#SHA1: bc94924856dc82c18ccf699d467d63c28fed0d13
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-let server;
-let port;
-
-beforeAll(async () => {
- // Check if crypto is available
- try {
- require('crypto');
- } catch (err) {
- return test.skip('missing crypto');
- }
-});
-
-afterAll(() => {
- if (server) {
- server.close();
- }
-});
-
-test('HTTP2 client priority before connect', (done) => {
- server = h2.createServer();
-
- // We use the lower-level API here
- server.on('stream', (stream) => {
- stream.respond();
- stream.end('ok');
- });
-
- server.listen(0, () => {
- port = server.address().port;
- const client = h2.connect(`http://localhost:${port}`);
- const req = client.request();
- req.priority({});
-
- req.on('response', () => {
- // Response received
- });
-
- req.resume();
-
- req.on('end', () => {
- // Request ended
- });
-
- req.on('close', () => {
- client.close();
- done();
- });
- });
-});
-
-//<#END_FILE: test-http2-client-priority-before-connect.js
diff --git a/test/js/node/test/parallel/http2-client-request-listeners-warning.test.js b/test/js/node/test/parallel/http2-client-request-listeners-warning.test.js
deleted file mode 100644
index a560ec53ad..0000000000
--- a/test/js/node/test/parallel/http2-client-request-listeners-warning.test.js
+++ /dev/null
@@ -1,70 +0,0 @@
-//#FILE: test-http2-client-request-listeners-warning.js
-//#SHA1: cb4f9a71d1f670a78f989caed948e88fa5dbd681
-//-----------------
-"use strict";
-const http2 = require("http2");
-const EventEmitter = require("events");
-
-// Skip the test if crypto is not available
-let hasCrypto;
-try {
- require("crypto");
- hasCrypto = true;
-} catch (err) {
- hasCrypto = false;
-}
-
-(hasCrypto ? describe : describe.skip)("HTTP2 client request listeners warning", () => {
- let server;
- let port;
-
- beforeAll(done => {
- server = http2.createServer();
- server.on("stream", stream => {
- stream.respond();
- stream.end();
- });
-
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- test("should not emit MaxListenersExceededWarning", done => {
- const warningListener = jest.fn();
- process.on("warning", warningListener);
-
- const client = http2.connect(`http://localhost:${port}`);
-
- function request() {
- return new Promise((resolve, reject) => {
- const stream = client.request();
- stream.on("error", reject);
- stream.on("response", resolve);
- stream.end();
- });
- }
-
- const requests = [];
- for (let i = 0; i < EventEmitter.defaultMaxListeners + 1; i++) {
- requests.push(request());
- }
-
- Promise.all(requests)
- .then(() => {
- expect(warningListener).not.toHaveBeenCalled();
- })
- .finally(() => {
- process.removeListener("warning", warningListener);
- client.close();
- done();
- });
- });
-});
-
-//<#END_FILE: test-http2-client-request-listeners-warning.js
diff --git a/test/js/node/test/parallel/http2-client-shutdown-before-connect.test.js b/test/js/node/test/parallel/http2-client-shutdown-before-connect.test.js
deleted file mode 100644
index 18091d3a31..0000000000
--- a/test/js/node/test/parallel/http2-client-shutdown-before-connect.test.js
+++ /dev/null
@@ -1,40 +0,0 @@
-//#FILE: test-http2-client-shutdown-before-connect.js
-//#SHA1: 75a343e9d8b577911242f867708310346fe9ddce
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-// Skip test if crypto is not available
-const hasCrypto = (() => {
- try {
- require('crypto');
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-if (!hasCrypto) {
- test.skip('missing crypto', () => {});
-} else {
- test('HTTP/2 client shutdown before connect', (done) => {
- const server = h2.createServer();
-
- // We use the lower-level API here
- server.on('stream', () => {
- throw new Error('Stream should not be created');
- });
-
- server.listen(0, () => {
- const client = h2.connect(`http://localhost:${server.address().port}`);
- client.close(() => {
- server.close(() => {
- done();
- });
- });
- });
- });
-}
-
-//<#END_FILE: test-http2-client-shutdown-before-connect.js
diff --git a/test/js/node/test/parallel/http2-client-write-before-connect.test.js b/test/js/node/test/parallel/http2-client-write-before-connect.test.js
deleted file mode 100644
index b245680da9..0000000000
--- a/test/js/node/test/parallel/http2-client-write-before-connect.test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-//#FILE: test-http2-client-write-before-connect.js
-//#SHA1: f38213aa6b5fb615d5b80f0213022ea06e2705cc
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-let server;
-let client;
-
-beforeAll(() => {
- if (!process.versions.openssl) {
- test.skip('missing crypto');
- return;
- }
-});
-
-afterEach(() => {
- if (client) {
- client.close();
- }
- if (server) {
- server.close();
- }
-});
-
-test('HTTP/2 client write before connect', (done) => {
- server = h2.createServer();
-
- server.on('stream', (stream, headers, flags) => {
- let data = '';
- stream.setEncoding('utf8');
- stream.on('data', (chunk) => data += chunk);
- stream.on('end', () => {
- expect(data).toBe('some data more data');
- });
- stream.respond();
- stream.end('ok');
- });
-
- server.listen(0, () => {
- const port = server.address().port;
- client = h2.connect(`http://localhost:${port}`);
-
- const req = client.request({ ':method': 'POST' });
- req.write('some data ');
- req.end('more data');
-
- req.on('response', () => {});
- req.resume();
- req.on('end', () => {});
- req.on('close', () => {
- done();
- });
- });
-});
-
-//<#END_FILE: test-http2-client-write-before-connect.js
diff --git a/test/js/node/test/parallel/http2-client-write-empty-string.test.js b/test/js/node/test/parallel/http2-client-write-empty-string.test.js
deleted file mode 100644
index daf8182df6..0000000000
--- a/test/js/node/test/parallel/http2-client-write-empty-string.test.js
+++ /dev/null
@@ -1,74 +0,0 @@
-//#FILE: test-http2-client-write-empty-string.js
-//#SHA1: d4371ceba660942fe3c398bbb3144ce691054cec
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-const runTest = async (chunkSequence) => {
- return new Promise((resolve, reject) => {
- const server = http2.createServer();
- server.on('stream', (stream, headers, flags) => {
- stream.respond({ 'content-type': 'text/html' });
-
- let data = '';
- stream.on('data', (chunk) => {
- data += chunk.toString();
- });
- stream.on('end', () => {
- stream.end(`"${data}"`);
- });
- });
-
- server.listen(0, async () => {
- const port = server.address().port;
- const client = http2.connect(`http://localhost:${port}`);
-
- const req = client.request({
- ':method': 'POST',
- ':path': '/'
- });
-
- req.on('response', (headers) => {
- expect(headers[':status']).toBe(200);
- expect(headers['content-type']).toBe('text/html');
- });
-
- let data = '';
- req.setEncoding('utf8');
- req.on('data', (d) => data += d);
- req.on('end', () => {
- expect(data).toBe('""');
- server.close();
- client.close();
- resolve();
- });
-
- for (const chunk of chunkSequence) {
- req.write(chunk);
- }
- req.end();
- });
- });
-};
-
-const testCases = [
- [''],
- ['', '']
-];
-
-describe('http2 client write empty string', () => {
- beforeAll(() => {
- if (typeof http2 === 'undefined') {
- return test.skip('http2 module not available');
- }
- });
-
- testCases.forEach((chunkSequence, index) => {
- it(`should handle chunk sequence ${index + 1}`, async () => {
- await runTest(chunkSequence);
- });
- });
-});
-
-//<#END_FILE: test-http2-client-write-empty-string.js
diff --git a/test/js/node/test/parallel/http2-compat-aborted.test.js b/test/js/node/test/parallel/http2-compat-aborted.test.js
deleted file mode 100644
index b304d69e16..0000000000
--- a/test/js/node/test/parallel/http2-compat-aborted.test.js
+++ /dev/null
@@ -1,55 +0,0 @@
-//#FILE: test-http2-compat-aborted.js
-//#SHA1: 2aaf11840d98c2b8f4387473180ec86626ac48d1
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-
-let server;
-let port;
-
-beforeAll(done => {
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
- server = h2.createServer((req, res) => {
- req.on("aborted", () => {
- expect(req.aborted).toBe(true);
- expect(req.complete).toBe(true);
- });
- expect(req.aborted).toBe(false);
- expect(req.complete).toBe(false);
- res.write("hello");
- server.close();
- });
-
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
-});
-
-afterAll(() => {
- if (server) {
- server.close();
- }
-});
-
-test("HTTP/2 compat aborted", done => {
- const url = `http://localhost:${port}`;
- const client = h2.connect(url, () => {
- const request = client.request();
- request.on("data", chunk => {
- client.destroy();
- });
- request.on("end", () => {
- done();
- });
- });
-
- client.on("error", err => {
- // Ignore client errors as we're forcibly destroying the connection
- });
-});
-
-//<#END_FILE: test-http2-compat-aborted.js
diff --git a/test/js/node/test/parallel/http2-compat-client-upload-reject.test.js b/test/js/node/test/parallel/http2-compat-client-upload-reject.test.js
deleted file mode 100644
index a9e085022b..0000000000
--- a/test/js/node/test/parallel/http2-compat-client-upload-reject.test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-//#FILE: test-http2-compat-client-upload-reject.js
-//#SHA1: 4dff98612ac613af951070f79f07f5c1750045da
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-const fs = require('fs');
-const path = require('path');
-
-const fixturesPath = path.resolve(__dirname, '..', 'fixtures');
-const loc = path.join(fixturesPath, 'person-large.jpg');
-
-let server;
-let client;
-
-beforeAll(() => {
- if (!process.versions.openssl) {
- return test.skip('missing crypto');
- }
-});
-
-afterEach(() => {
- if (server) server.close();
- if (client) client.close();
-});
-
-test('HTTP/2 client upload reject', (done) => {
- expect(fs.existsSync(loc)).toBe(true);
-
- fs.readFile(loc, (err, data) => {
- expect(err).toBeNull();
-
- server = http2.createServer((req, res) => {
- setImmediate(() => {
- res.writeHead(400);
- res.end();
- });
- });
-
- server.listen(0, () => {
- const port = server.address().port;
- client = http2.connect(`http://localhost:${port}`);
-
- const req = client.request({ ':method': 'POST' });
- req.on('response', (headers) => {
- expect(headers[':status']).toBe(400);
- });
-
- req.resume();
- req.on('end', () => {
- server.close();
- client.close();
- done();
- });
-
- const str = fs.createReadStream(loc);
- str.pipe(req);
- });
- });
-});
-
-//<#END_FILE: test-http2-compat-client-upload-reject.js
diff --git a/test/js/node/test/parallel/http2-compat-errors.test.js b/test/js/node/test/parallel/http2-compat-errors.test.js
deleted file mode 100644
index e326447865..0000000000
--- a/test/js/node/test/parallel/http2-compat-errors.test.js
+++ /dev/null
@@ -1,67 +0,0 @@
-//#FILE: test-http2-compat-errors.js
-//#SHA1: 3a958d2216c02d05272fbc89bd09a532419876a4
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-// Simulate crypto check
-const hasCrypto = true;
-if (!hasCrypto) {
- test.skip('missing crypto', () => {});
-} else {
- let expected = null;
-
- describe('http2 compat errors', () => {
- let server;
- let url;
-
- beforeAll((done) => {
- server = h2.createServer((req, res) => {
- const resStreamErrorHandler = jest.fn();
- const reqErrorHandler = jest.fn();
- const resErrorHandler = jest.fn();
- const reqAbortedHandler = jest.fn();
- const resAbortedHandler = jest.fn();
-
- res.stream.on('error', resStreamErrorHandler);
- req.on('error', reqErrorHandler);
- res.on('error', resErrorHandler);
- req.on('aborted', reqAbortedHandler);
- res.on('aborted', resAbortedHandler);
-
- res.write('hello');
-
- expected = new Error('kaboom');
- res.stream.destroy(expected);
-
- // Use setImmediate to allow event handlers to be called
- setImmediate(() => {
- expect(resStreamErrorHandler).toHaveBeenCalled();
- expect(reqErrorHandler).not.toHaveBeenCalled();
- expect(resErrorHandler).not.toHaveBeenCalled();
- expect(reqAbortedHandler).toHaveBeenCalled();
- expect(resAbortedHandler).not.toHaveBeenCalled();
- server.close(done);
- });
- });
-
- server.listen(0, () => {
- url = `http://localhost:${server.address().port}`;
- done();
- });
- });
-
- test('should handle errors correctly', (done) => {
- const client = h2.connect(url, () => {
- const request = client.request();
- request.on('data', (chunk) => {
- client.destroy();
- done();
- });
- });
- });
- });
-}
-
-//<#END_FILE: test-http2-compat-errors.js
diff --git a/test/js/node/test/parallel/http2-compat-expect-continue-check.test.js b/test/js/node/test/parallel/http2-compat-expect-continue-check.test.js
deleted file mode 100644
index 8ee10f45fd..0000000000
--- a/test/js/node/test/parallel/http2-compat-expect-continue-check.test.js
+++ /dev/null
@@ -1,77 +0,0 @@
-//#FILE: test-http2-compat-expect-continue-check.js
-//#SHA1: cfaba2929ccb61aa085572010d7730ceef07859e
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-const testResBody = 'other stuff!\n';
-
-describe('HTTP/2 100-continue flow', () => {
- let server;
-
- beforeAll(() => {
- if (!process.versions.openssl) {
- return test.skip('missing crypto');
- }
- });
-
- afterEach(() => {
- if (server) {
- server.close();
- }
- });
-
- test('Full 100-continue flow', (done) => {
- server = http2.createServer();
- const fullRequestHandler = jest.fn();
- server.on('request', fullRequestHandler);
-
- server.on('checkContinue', (req, res) => {
- res.writeContinue();
- res.writeHead(200, {});
- res.end(testResBody);
-
- expect(res.writeContinue()).toBe(false);
-
- res.on('finish', () => {
- process.nextTick(() => {
- expect(res.writeContinue()).toBe(false);
- });
- });
- });
-
- server.listen(0, () => {
- let body = '';
-
- const client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request({
- ':method': 'POST',
- 'expect': '100-continue'
- });
-
- let gotContinue = false;
- req.on('continue', () => {
- gotContinue = true;
- });
-
- req.on('response', (headers) => {
- expect(gotContinue).toBe(true);
- expect(headers[':status']).toBe(200);
- req.end();
- });
-
- req.setEncoding('utf-8');
- req.on('data', (chunk) => { body += chunk; });
-
- req.on('end', () => {
- expect(body).toBe(testResBody);
- expect(fullRequestHandler).not.toHaveBeenCalled();
- client.close();
- done();
- });
- });
- });
-});
-
-//<#END_FILE: test-http2-compat-expect-continue-check.js
diff --git a/test/js/node/test/parallel/http2-compat-expect-continue.test.js b/test/js/node/test/parallel/http2-compat-expect-continue.test.js
deleted file mode 100644
index b2e98efb5d..0000000000
--- a/test/js/node/test/parallel/http2-compat-expect-continue.test.js
+++ /dev/null
@@ -1,98 +0,0 @@
-//#FILE: test-http2-compat-expect-continue.js
-//#SHA1: 3c95de1bb9a0bf620945ec5fc39ba3a515dfe5fd
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-// Skip the test if crypto is not available
-const hasCrypto = (() => {
- try {
- require('crypto');
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-if (!hasCrypto) {
- test.skip('missing crypto', () => {});
-} else {
- describe('HTTP/2 100-continue flow', () => {
- test('full 100-continue flow with response', (done) => {
- const testResBody = 'other stuff!\n';
- const server = http2.createServer();
- let sentResponse = false;
-
- server.on('request', (req, res) => {
- res.end(testResBody);
- sentResponse = true;
- });
-
- server.listen(0, () => {
- let body = '';
- const client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request({
- ':method': 'POST',
- 'expect': '100-continue'
- });
-
- let gotContinue = false;
- req.on('continue', () => {
- gotContinue = true;
- });
-
- req.on('response', (headers) => {
- expect(gotContinue).toBe(true);
- expect(sentResponse).toBe(true);
- expect(headers[':status']).toBe(200);
- req.end();
- });
-
- req.setEncoding('utf8');
- req.on('data', (chunk) => { body += chunk; });
- req.on('end', () => {
- expect(body).toBe(testResBody);
- client.close();
- server.close(done);
- });
- });
- });
-
- test('100-continue flow with immediate response', (done) => {
- const server = http2.createServer();
-
- server.on('request', (req, res) => {
- res.end();
- });
-
- server.listen(0, () => {
- const client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request({
- ':path': '/',
- 'expect': '100-continue'
- });
-
- let gotContinue = false;
- req.on('continue', () => {
- gotContinue = true;
- });
-
- let gotResponse = false;
- req.on('response', () => {
- gotResponse = true;
- });
-
- req.setEncoding('utf8');
- req.on('end', () => {
- expect(gotContinue).toBe(true);
- expect(gotResponse).toBe(true);
- client.close();
- server.close(done);
- });
- });
- });
- });
-}
-
-//<#END_FILE: test-http2-compat-expect-continue.js
diff --git a/test/js/node/test/parallel/http2-compat-expect-handling.test.js b/test/js/node/test/parallel/http2-compat-expect-handling.test.js
deleted file mode 100644
index 2a1940ae23..0000000000
--- a/test/js/node/test/parallel/http2-compat-expect-handling.test.js
+++ /dev/null
@@ -1,96 +0,0 @@
-//#FILE: test-http2-compat-expect-handling.js
-//#SHA1: 015a7b40547c969f4d631e7e743f5293d9e8f843
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-const hasCrypto = (() => {
- try {
- require("crypto");
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-const expectValue = "meoww";
-
-describe("HTTP/2 Expect Header Handling", () => {
- let server;
- let port;
-
- beforeAll(done => {
- server = http2.createServer();
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- test("server should not call request handler", () => {
- const requestHandler = jest.fn();
- server.on("request", requestHandler);
-
- return new Promise(resolve => {
- server.once("checkExpectation", (req, res) => {
- expect(req.headers.expect).toBe(expectValue);
- res.statusCode = 417;
- res.end();
- expect(requestHandler).not.toHaveBeenCalled();
- resolve();
- });
-
- const client = http2.connect(`http://localhost:${port}`);
- const req = client.request({
- ":path": "/",
- ":method": "GET",
- ":scheme": "http",
- ":authority": `localhost:${port}`,
- "expect": expectValue,
- });
-
- req.on("response", headers => {
- expect(headers[":status"]).toBe(417);
- req.resume();
- });
-
- req.on("end", () => {
- client.close();
- });
- });
- });
-
- test("client should receive 417 status", () => {
- return new Promise(resolve => {
- const client = http2.connect(`http://localhost:${port}`);
- const req = client.request({
- ":path": "/",
- ":method": "GET",
- ":scheme": "http",
- ":authority": `localhost:${port}`,
- "expect": expectValue,
- });
-
- req.on("response", headers => {
- expect(headers[":status"]).toBe(417);
- req.resume();
- });
-
- req.on("end", () => {
- client.close();
- resolve();
- });
- });
- });
-});
-
-if (!hasCrypto) {
- test.skip("skipping HTTP/2 tests due to missing crypto support", () => {});
-}
-
-//<#END_FILE: test-http2-compat-expect-handling.js
diff --git a/test/js/node/test/parallel/http2-compat-serverrequest-pause.test.js b/test/js/node/test/parallel/http2-compat-serverrequest-pause.test.js
deleted file mode 100644
index a42d021210..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverrequest-pause.test.js
+++ /dev/null
@@ -1,75 +0,0 @@
-//#FILE: test-http2-compat-serverrequest-pause.js
-//#SHA1: 3f3eff95f840e6321b0d25211ef5116304049dc7
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-const hasCrypto = (() => {
- try {
- require('crypto');
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-if (!hasCrypto) {
- test.skip('missing crypto', () => {});
-} else {
- const testStr = 'Request Body from Client';
- let server;
- let client;
-
- beforeAll(() => {
- server = h2.createServer();
- });
-
- afterAll(() => {
- if (client) client.close();
- if (server) server.close();
- });
-
- test('pause & resume work as expected with Http2ServerRequest', (done) => {
- const requestHandler = jest.fn((req, res) => {
- let data = '';
- req.pause();
- req.setEncoding('utf8');
- req.on('data', jest.fn((chunk) => (data += chunk)));
- setTimeout(() => {
- expect(data).toBe('');
- req.resume();
- }, 100);
- req.on('end', () => {
- expect(data).toBe(testStr);
- res.end();
- });
-
- res.on('finish', () => process.nextTick(() => {
- req.pause();
- req.resume();
- }));
- });
-
- server.on('request', requestHandler);
-
- server.listen(0, () => {
- const port = server.address().port;
-
- client = h2.connect(`http://localhost:${port}`);
- const request = client.request({
- ':path': '/foobar',
- ':method': 'POST',
- ':scheme': 'http',
- ':authority': `localhost:${port}`
- });
- request.resume();
- request.end(testStr);
- request.on('end', () => {
- expect(requestHandler).toHaveBeenCalled();
- done();
- });
- });
- });
-}
-//<#END_FILE: test-http2-compat-serverrequest-pause.js
diff --git a/test/js/node/test/parallel/http2-compat-serverrequest-pipe.test.js b/test/js/node/test/parallel/http2-compat-serverrequest-pipe.test.js
deleted file mode 100644
index 47ed561685..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverrequest-pipe.test.js
+++ /dev/null
@@ -1,69 +0,0 @@
-//#FILE: test-http2-compat-serverrequest-pipe.js
-//#SHA1: c4254ac88df3334dccc8adb4b60856193a6e644e
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-const fs = require("fs");
-const path = require("path");
-const os = require("os");
-const { isWindows } = require("harness");
-
-const fixtures = path.join(__dirname, "..", "fixtures");
-const tmpdir = os.tmpdir();
-
-let server;
-let client;
-let port;
-
-beforeAll(async () => {
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
-
- await fs.promises.mkdir(tmpdir, { recursive: true });
-});
-
-afterAll(async () => {
- if (server) server.close();
- if (client) client.close();
-});
-
-test.todoIf(isWindows)("HTTP/2 server request pipe", done => {
- const loc = path.join(fixtures, "person-large.jpg");
- const fn = path.join(tmpdir, "http2-url-tests.js");
-
- server = http2.createServer();
-
- server.on("request", (req, res) => {
- const dest = req.pipe(fs.createWriteStream(fn));
- dest.on("finish", () => {
- expect(req.complete).toBe(true);
- expect(fs.readFileSync(loc).length).toBe(fs.readFileSync(fn).length);
- fs.unlinkSync(fn);
- res.end();
- });
- });
-
- server.listen(0, () => {
- port = server.address().port;
- client = http2.connect(`http://localhost:${port}`);
-
- let remaining = 2;
- function maybeClose() {
- if (--remaining === 0) {
- done();
- }
- }
-
- const req = client.request({ ":method": "POST" });
- req.on("response", () => {});
- req.resume();
- req.on("end", maybeClose);
- const str = fs.createReadStream(loc);
- str.on("end", maybeClose);
- str.pipe(req);
- });
-});
-
-//<#END_FILE: test-http2-compat-serverrequest-pipe.js
diff --git a/test/js/node/test/parallel/http2-compat-serverrequest.test.js b/test/js/node/test/parallel/http2-compat-serverrequest.test.js
deleted file mode 100644
index 2349965420..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverrequest.test.js
+++ /dev/null
@@ -1,69 +0,0 @@
-//#FILE: test-http2-compat-serverrequest.js
-//#SHA1: f661c6c9249c0cdc770439f7498943fc5edbf86b
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-const net = require("net");
-
-let server;
-let port;
-
-beforeAll(done => {
- server = h2.createServer();
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
-});
-
-afterAll(done => {
- server.close(done);
-});
-
-// today we deatch the socket earlier
-test.todo("Http2ServerRequest should expose convenience properties", done => {
- expect.assertions(7);
-
- server.once("request", (request, response) => {
- const expected = {
- version: "2.0",
- httpVersionMajor: 2,
- httpVersionMinor: 0,
- };
-
- expect(request.httpVersion).toBe(expected.version);
- expect(request.httpVersionMajor).toBe(expected.httpVersionMajor);
- expect(request.httpVersionMinor).toBe(expected.httpVersionMinor);
-
- expect(request.socket).toBeInstanceOf(net.Socket);
- expect(request.connection).toBeInstanceOf(net.Socket);
- expect(request.socket).toBe(request.connection);
-
- response.on("finish", () => {
- process.nextTick(() => {
- expect(request.socket).toBeTruthy();
- done();
- });
- });
- response.end();
- });
-
- const url = `http://localhost:${port}`;
- const client = h2.connect(url, () => {
- const headers = {
- ":path": "/foobar",
- ":method": "GET",
- ":scheme": "http",
- ":authority": `localhost:${port}`,
- };
- const request = client.request(headers);
- request.on("end", () => {
- client.close();
- });
- request.end();
- request.resume();
- });
-});
-
-//<#END_FILE: test-http2-compat-serverrequest.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-close.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-close.test.js
deleted file mode 100644
index 6ae966fc55..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-close.test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-close.js
-//#SHA1: 6b61a9cea948447ae33843472678ffbed0b47c9a
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-
-// Skip the test if crypto is not available
-let hasCrypto;
-try {
- require("crypto");
- hasCrypto = true;
-} catch (err) {
- hasCrypto = false;
-}
-
-(hasCrypto ? describe : describe.skip)("HTTP/2 server response close", () => {
- let server;
- let url;
-
- beforeAll(done => {
- server = h2.createServer((req, res) => {
- res.writeHead(200);
- res.write("a");
-
- const reqCloseMock = jest.fn();
- const resCloseMock = jest.fn();
- const reqErrorMock = jest.fn();
-
- req.on("close", reqCloseMock);
- res.on("close", resCloseMock);
- req.on("error", reqErrorMock);
-
- // Use Jest's fake timers to ensure the test doesn't hang
- setTimeout(() => {
- expect(reqCloseMock).toHaveBeenCalled();
- expect(resCloseMock).toHaveBeenCalled();
- expect(reqErrorMock).not.toHaveBeenCalled();
- done();
- }, 1000);
- });
-
- server.listen(0, () => {
- url = `http://localhost:${server.address().port}`;
- done();
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- test("Server request and response should receive close event if connection terminated before response.end", done => {
- const client = h2.connect(url, () => {
- const request = client.request();
- request.on("data", chunk => {
- client.destroy();
- done();
- });
- });
- });
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-close.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-drain.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-drain.test.js
deleted file mode 100644
index 4976ad2284..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-drain.test.js
+++ /dev/null
@@ -1,61 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-drain.js
-//#SHA1: 4ec55745f622a31b4729fcb9daf9bfd707a3bdb3
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-const hasCrypto = (() => {
- try {
- require('crypto');
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-const testString = 'tests';
-
-test('HTTP/2 server response drain event', async () => {
- if (!hasCrypto) {
- test.skip('missing crypto');
- return;
- }
-
- const server = h2.createServer();
-
- const requestHandler = jest.fn((req, res) => {
- res.stream._writableState.highWaterMark = testString.length;
- expect(res.write(testString)).toBe(false);
- res.on('drain', jest.fn(() => res.end(testString)));
- });
-
- server.on('request', requestHandler);
-
- await new Promise(resolve => server.listen(0, resolve));
- const port = server.address().port;
-
- const client = h2.connect(`http://localhost:${port}`);
- const request = client.request({
- ':path': '/foobar',
- ':method': 'POST',
- ':scheme': 'http',
- ':authority': `localhost:${port}`
- });
- request.resume();
- request.end();
-
- let data = '';
- request.setEncoding('utf8');
- request.on('data', (chunk) => (data += chunk));
-
- await new Promise(resolve => request.on('end', resolve));
-
- expect(data).toBe(testString.repeat(2));
- expect(requestHandler).toHaveBeenCalled();
-
- client.close();
- await new Promise(resolve => server.close(resolve));
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-drain.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-end-after-statuses-without-body.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-end-after-statuses-without-body.test.js
deleted file mode 100644
index 2dd0f00dd3..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-end-after-statuses-without-body.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-end-after-statuses-without-body.js
-//#SHA1: c4a4b76e1b04b7e6779f80f7077758dfab0e8b80
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-
-const { HTTP_STATUS_NO_CONTENT, HTTP_STATUS_RESET_CONTENT, HTTP_STATUS_NOT_MODIFIED } = h2.constants;
-
-const statusWithoutBody = [HTTP_STATUS_NO_CONTENT, HTTP_STATUS_RESET_CONTENT, HTTP_STATUS_NOT_MODIFIED];
-const STATUS_CODES_COUNT = statusWithoutBody.length;
-
-describe("HTTP/2 server response end after statuses without body", () => {
- let server;
- let url;
-
- beforeAll(done => {
- server = h2.createServer((req, res) => {
- res.writeHead(statusWithoutBody.pop());
- res.end();
- });
-
- server.listen(0, () => {
- url = `http://localhost:${server.address().port}`;
- done();
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- it("should handle end() after sending statuses without body", done => {
- const client = h2.connect(url, () => {
- let responseCount = 0;
- const closeAfterResponse = () => {
- if (STATUS_CODES_COUNT === ++responseCount) {
- client.destroy();
- done();
- }
- };
-
- for (let i = 0; i < STATUS_CODES_COUNT; i++) {
- const request = client.request();
- request.on("response", closeAfterResponse);
- }
- });
- });
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-end-after-statuses-without-body.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-end.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-end.test.js
deleted file mode 100644
index 27b1f393db..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-end.test.js
+++ /dev/null
@@ -1,80 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-end.js
-//#SHA1: 672da69abcb0b86d5234556e692949ac36ef6395
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-const { promisify } = require('util');
-
-// Mock the common module functions
-const mustCall = (fn) => jest.fn(fn);
-const mustNotCall = () => jest.fn().mockImplementation(() => {
- throw new Error('This function should not have been called');
-});
-
-const {
- HTTP2_HEADER_STATUS,
- HTTP_STATUS_OK
-} = http2.constants;
-
-// Helper function to create a server and get its port
-const createServerAndGetPort = async (requestListener) => {
- const server = http2.createServer(requestListener);
- await promisify(server.listen.bind(server))(0);
- const { port } = server.address();
- return { server, port };
-};
-
-// Helper function to create a client
-const createClient = (port) => {
- const url = `http://localhost:${port}`;
- return http2.connect(url);
-};
-
-describe('Http2ServerResponse.end', () => {
- test('accepts chunk, encoding, cb as args and can be called multiple times', async () => {
- const { server, port } = await createServerAndGetPort((request, response) => {
- const endCallback = jest.fn(() => {
- response.end(jest.fn());
- process.nextTick(() => {
- response.end(jest.fn());
- server.close();
- });
- });
-
- response.end('end', 'utf8', endCallback);
- response.on('finish', () => {
- response.end(jest.fn());
- });
- response.end(jest.fn());
- });
-
- const client = createClient(port);
- const headers = {
- ':path': '/',
- ':method': 'GET',
- ':scheme': 'http',
- ':authority': `localhost:${port}`
- };
-
- let data = '';
- const request = client.request(headers);
- request.setEncoding('utf8');
- request.on('data', (chunk) => (data += chunk));
- await new Promise(resolve => {
- request.on('end', () => {
- expect(data).toBe('end');
- client.close();
- resolve();
- });
- request.end();
- request.resume();
- });
- });
-
- // Add more tests here...
-});
-
-// More test blocks for other scenarios...
-
-//<#END_FILE: test-http2-compat-serverresponse-end.test.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-finished.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-finished.test.js
deleted file mode 100644
index fb6f9c2b52..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-finished.test.js
+++ /dev/null
@@ -1,68 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-finished.js
-//#SHA1: 6ef7a05f30923975d7a267cee54aafae1bfdbc7d
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-const net = require('net');
-
-let server;
-
-beforeAll(() => {
- // Skip the test if crypto is not available
- if (!process.versions.openssl) {
- return test.skip('missing crypto');
- }
-});
-
-afterEach(() => {
- if (server) {
- server.close();
- }
-});
-
-test('Http2ServerResponse.finished', (done) => {
- server = h2.createServer();
- server.listen(0, () => {
- const port = server.address().port;
-
- server.once('request', (request, response) => {
- expect(response.socket).toBeInstanceOf(net.Socket);
- expect(response.connection).toBeInstanceOf(net.Socket);
- expect(response.socket).toBe(response.connection);
-
- response.on('finish', () => {
- expect(response.socket).toBeUndefined();
- expect(response.connection).toBeUndefined();
- process.nextTick(() => {
- expect(response.stream).toBeDefined();
- done();
- });
- });
-
- expect(response.finished).toBe(false);
- expect(response.writableEnded).toBe(false);
- response.end();
- expect(response.finished).toBe(true);
- expect(response.writableEnded).toBe(true);
- });
-
- const url = `http://localhost:${port}`;
- const client = h2.connect(url, () => {
- const headers = {
- ':path': '/',
- ':method': 'GET',
- ':scheme': 'http',
- ':authority': `localhost:${port}`
- };
- const request = client.request(headers);
- request.on('end', () => {
- client.close();
- });
- request.end();
- request.resume();
- });
- });
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-finished.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-flushheaders.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-flushheaders.test.js
deleted file mode 100644
index 6d0864b507..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-flushheaders.test.js
+++ /dev/null
@@ -1,71 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-flushheaders.js
-//#SHA1: ea772e05a29f43bd7b61e4d70f24b94c1e1e201c
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-
-let server;
-let serverResponse;
-
-beforeAll(done => {
- server = h2.createServer();
- server.listen(0, () => {
- done();
- });
-});
-
-afterAll(() => {
- server.close();
-});
-
-test("Http2ServerResponse.flushHeaders", done => {
- const port = server.address().port;
-
- server.once("request", (request, response) => {
- expect(response.headersSent).toBe(false);
- expect(response._header).toBe(false); // Alias for headersSent
- response.flushHeaders();
- expect(response.headersSent).toBe(true);
- expect(response._header).toBe(true);
- response.flushHeaders(); // Idempotent
-
- expect(() => {
- response.writeHead(400, { "foo-bar": "abc123" });
- }).toThrow(
- expect.objectContaining({
- code: "ERR_HTTP2_HEADERS_SENT",
- }),
- );
- response.on("finish", () => {
- process.nextTick(() => {
- response.flushHeaders(); // Idempotent
- done();
- });
- });
- serverResponse = response;
- });
-
- const url = `http://localhost:${port}`;
- const client = h2.connect(url, () => {
- const headers = {
- ":path": "/",
- ":method": "GET",
- ":scheme": "http",
- ":authority": `localhost:${port}`,
- };
- const request = client.request(headers);
- request.on("response", (headers, flags) => {
- expect(headers["foo-bar"]).toBeUndefined();
- expect(headers[":status"]).toBe(200);
- serverResponse.end();
- });
- request.on("end", () => {
- client.close();
- });
- request.end();
- request.resume();
- });
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-flushheaders.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-headers-send-date.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-headers-send-date.test.js
deleted file mode 100644
index 6f410d12f1..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-headers-send-date.test.js
+++ /dev/null
@@ -1,48 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-headers-send-date.js
-//#SHA1: 1ed6319986a3bb9bf58709d9577d03407fdde3f2
-//-----------------
-"use strict";
-const http2 = require("http2");
-
-let server;
-let port;
-
-beforeAll(done => {
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
-
- server = http2.createServer((request, response) => {
- response.sendDate = false;
- response.writeHead(200);
- response.end();
- });
-
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
-});
-
-afterAll(() => {
- server.close();
-});
-
-test("HTTP/2 server response should not send Date header when sendDate is false", done => {
- const session = http2.connect(`http://localhost:${port}`);
- const req = session.request();
-
- req.on("response", (headers, flags) => {
- expect(headers).not.toHaveProperty("Date");
- expect(headers).not.toHaveProperty("date");
- });
-
- req.on("end", () => {
- session.close();
- done();
- });
-
- req.end();
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-headers-send-date.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-settimeout.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-settimeout.test.js
deleted file mode 100644
index 305f398176..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-settimeout.test.js
+++ /dev/null
@@ -1,78 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-settimeout.js
-//#SHA1: fe2e0371e885463968a268362464724494b758a6
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-const msecs = 1000; // Assuming a reasonable timeout for all platforms
-
-let server;
-let client;
-
-beforeAll(done => {
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
- server = http2.createServer();
- server.listen(0, () => {
- done();
- });
-});
-
-afterAll(() => {
- if (client) {
- client.close();
- }
- if (server) {
- server.close();
- }
-});
-
-test("HTTP2 ServerResponse setTimeout", done => {
- const timeoutCallback = jest.fn();
- const onTimeout = jest.fn();
- const onFinish = jest.fn();
-
- server.on("request", (req, res) => {
- res.setTimeout(msecs, timeoutCallback);
- res.on("timeout", onTimeout);
- res.on("finish", () => {
- onFinish();
- res.setTimeout(msecs, jest.fn());
- process.nextTick(() => {
- res.setTimeout(msecs, jest.fn());
- });
- });
-
- // Explicitly end the response after a short delay
- setTimeout(() => {
- res.end();
- }, 100);
- });
-
- const port = server.address().port;
- client = http2.connect(`http://localhost:${port}`);
- const req = client.request({
- ":path": "/",
- ":method": "GET",
- ":scheme": "http",
- ":authority": `localhost:${port}`,
- });
-
- req.on("end", () => {
- client.close();
-
- // Move assertions here to ensure they run after the response has finished
- expect(timeoutCallback).not.toHaveBeenCalled();
- expect(onTimeout).not.toHaveBeenCalled();
- expect(onFinish).toHaveBeenCalledTimes(1);
-
- done();
- });
-
- req.resume();
- req.end();
-}, 10000); // Increase the timeout to 10 seconds
-
-//<#END_FILE: test-http2-compat-serverresponse-settimeout.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-statuscode.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-statuscode.test.js
deleted file mode 100644
index 8845f6c532..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-statuscode.test.js
+++ /dev/null
@@ -1,95 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-statuscode.js
-//#SHA1: 10cb487c1fd9e256f807319b84c426b356be443f
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-
-let server;
-let port;
-
-beforeAll(async () => {
- server = h2.createServer();
- await new Promise(resolve => server.listen(0, resolve));
- port = server.address().port;
-});
-
-afterAll(async () => {
- server.close();
-});
-
-test("Http2ServerResponse should have a statusCode property", async () => {
- const responsePromise = new Promise(resolve => {
- server.once("request", (request, response) => {
- const expectedDefaultStatusCode = 200;
- const realStatusCodes = {
- continue: 100,
- ok: 200,
- multipleChoices: 300,
- badRequest: 400,
- internalServerError: 500,
- };
- const fakeStatusCodes = {
- tooLow: 99,
- tooHigh: 600,
- };
-
- expect(response.statusCode).toBe(expectedDefaultStatusCode);
-
- // Setting the response.statusCode should not throw.
- response.statusCode = realStatusCodes.ok;
- response.statusCode = realStatusCodes.multipleChoices;
- response.statusCode = realStatusCodes.badRequest;
- response.statusCode = realStatusCodes.internalServerError;
-
- expect(() => {
- response.statusCode = realStatusCodes.continue;
- }).toThrow(
- expect.objectContaining({
- code: "ERR_HTTP2_INFO_STATUS_NOT_ALLOWED",
- name: "RangeError",
- }),
- );
-
- expect(() => {
- response.statusCode = fakeStatusCodes.tooLow;
- }).toThrow(
- expect.objectContaining({
- code: "ERR_HTTP2_STATUS_INVALID",
- name: "RangeError",
- }),
- );
-
- expect(() => {
- response.statusCode = fakeStatusCodes.tooHigh;
- }).toThrow(
- expect.objectContaining({
- code: "ERR_HTTP2_STATUS_INVALID",
- name: "RangeError",
- }),
- );
-
- response.on("finish", resolve);
- response.end();
- });
- });
-
- const url = `http://localhost:${port}`;
- const client = h2.connect(url);
-
- const headers = {
- ":path": "/",
- ":method": "GET",
- ":scheme": "http",
- ":authority": `localhost:${port}`,
- };
-
- const request = client.request(headers);
- request.end();
- await new Promise(resolve => request.resume().on("end", resolve));
-
- await responsePromise;
- client.close();
-});
-
-//<#END_FILE: test-http2-compat-serverresponse-statuscode.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-writehead-array.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-writehead-array.test.js
deleted file mode 100644
index 2b1ca358a9..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-writehead-array.test.js
+++ /dev/null
@@ -1,114 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-writehead-array.js
-//#SHA1: e43a5a9f99ddad68b313e15fbb69839cca6d0775
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-// Skip the test if crypto is not available
-const hasCrypto = (() => {
- try {
- require('crypto');
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-if (!hasCrypto) {
- test.skip('missing crypto', () => {});
-} else {
- describe('Http2ServerResponse.writeHead with arrays', () => {
- test('should support nested arrays', (done) => {
- const server = http2.createServer();
- server.listen(0, () => {
- const port = server.address().port;
-
- server.once('request', (request, response) => {
- const returnVal = response.writeHead(200, [
- ['foo', 'bar'],
- ['foo', 'baz'],
- ['ABC', 123],
- ]);
- expect(returnVal).toBe(response);
- response.end(() => { server.close(); });
- });
-
- const client = http2.connect(`http://localhost:${port}`, () => {
- const request = client.request();
-
- request.on('response', (headers) => {
- expect(headers.foo).toBe('bar, baz');
- expect(headers.abc).toBe('123');
- expect(headers[':status']).toBe(200);
- });
- request.on('end', () => {
- client.close();
- done();
- });
- request.end();
- request.resume();
- });
- });
- });
-
- test('should support flat arrays', (done) => {
- const server = http2.createServer();
- server.listen(0, () => {
- const port = server.address().port;
-
- server.once('request', (request, response) => {
- const returnVal = response.writeHead(200, ['foo', 'bar', 'foo', 'baz', 'ABC', 123]);
- expect(returnVal).toBe(response);
- response.end(() => { server.close(); });
- });
-
- const client = http2.connect(`http://localhost:${port}`, () => {
- const request = client.request();
-
- request.on('response', (headers) => {
- expect(headers.foo).toBe('bar, baz');
- expect(headers.abc).toBe('123');
- expect(headers[':status']).toBe(200);
- });
- request.on('end', () => {
- client.close();
- done();
- });
- request.end();
- request.resume();
- });
- });
- });
-
- test('should throw ERR_INVALID_ARG_VALUE for invalid array', (done) => {
- const server = http2.createServer();
- server.listen(0, () => {
- const port = server.address().port;
-
- server.once('request', (request, response) => {
- expect(() => {
- response.writeHead(200, ['foo', 'bar', 'ABC', 123, 'extra']);
- }).toThrow(expect.objectContaining({
- code: 'ERR_INVALID_ARG_VALUE'
- }));
-
- response.end(() => { server.close(); });
- });
-
- const client = http2.connect(`http://localhost:${port}`, () => {
- const request = client.request();
-
- request.on('end', () => {
- client.close();
- done();
- });
- request.end();
- request.resume();
- });
- });
- });
- });
-}
-
-//<#END_FILE: test-http2-compat-serverresponse-writehead-array.js
diff --git a/test/js/node/test/parallel/http2-compat-serverresponse-writehead.test.js b/test/js/node/test/parallel/http2-compat-serverresponse-writehead.test.js
deleted file mode 100644
index 296a1e1a73..0000000000
--- a/test/js/node/test/parallel/http2-compat-serverresponse-writehead.test.js
+++ /dev/null
@@ -1,65 +0,0 @@
-//#FILE: test-http2-compat-serverresponse-writehead.js
-//#SHA1: fa267d5108f95ba69583bc709a82185ee9d18e76
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-// Http2ServerResponse.writeHead should override previous headers
-
-test('Http2ServerResponse.writeHead overrides previous headers', (done) => {
- const server = h2.createServer();
- server.listen(0, () => {
- const port = server.address().port;
- server.once('request', (request, response) => {
- response.setHeader('foo-bar', 'def456');
-
- // Override
- const returnVal = response.writeHead(418, { 'foo-bar': 'abc123' });
-
- expect(returnVal).toBe(response);
-
- expect(() => { response.writeHead(300); }).toThrow(expect.objectContaining({
- code: 'ERR_HTTP2_HEADERS_SENT'
- }));
-
- response.on('finish', () => {
- server.close();
- process.nextTick(() => {
- // The stream is invalid at this point,
- // and this line verifies this does not throw.
- response.writeHead(300);
- done();
- });
- });
- response.end();
- });
-
- const url = `http://localhost:${port}`;
- const client = h2.connect(url, () => {
- const headers = {
- ':path': '/',
- ':method': 'GET',
- ':scheme': 'http',
- ':authority': `localhost:${port}`
- };
- const request = client.request(headers);
- request.on('response', (headers) => {
- expect(headers['foo-bar']).toBe('abc123');
- expect(headers[':status']).toBe(418);
- });
- request.on('end', () => {
- client.close();
- });
- request.end();
- request.resume();
- });
- });
-});
-
-// Skip the test if crypto is not available
-if (!process.versions.openssl) {
- test.skip('missing crypto', () => {});
-}
-
-//<#END_FILE: test-http2-compat-serverresponse-writehead.js
diff --git a/test/js/node/test/parallel/http2-compat-socket-destroy-delayed.test.js b/test/js/node/test/parallel/http2-compat-socket-destroy-delayed.test.js
deleted file mode 100644
index 10e6afe2bc..0000000000
--- a/test/js/node/test/parallel/http2-compat-socket-destroy-delayed.test.js
+++ /dev/null
@@ -1,47 +0,0 @@
-//#FILE: test-http2-compat-socket-destroy-delayed.js
-//#SHA1: c7b5b8b5de4667a89e0e261e36098f617d411ed2
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-const { HTTP2_HEADER_PATH, HTTP2_HEADER_METHOD } = http2.constants;
-
-// Skip the test if crypto is not available
-if (!process.versions.openssl) {
- test.skip("missing crypto", () => {});
-} else {
- test("HTTP/2 socket destroy delayed", done => {
- const app = http2.createServer((req, res) => {
- res.end("hello");
- setImmediate(() => req.socket?.destroy());
- });
-
- app.listen(0, () => {
- const session = http2.connect(`http://localhost:${app.address().port}`);
- const request = session.request({
- [HTTP2_HEADER_PATH]: "/",
- [HTTP2_HEADER_METHOD]: "get",
- });
- request.once("response", (headers, flags) => {
- let data = "";
- request.on("data", chunk => {
- data += chunk;
- });
- request.on("end", () => {
- expect(data).toBe("hello");
- session.close();
- app.close();
- done();
- });
- });
- request.end();
- });
- });
-}
-
-// This tests verifies that calling `req.socket.destroy()` via
-// setImmediate does not crash.
-// Fixes https://github.com/nodejs/node/issues/22855.
-
-//<#END_FILE: test-http2-compat-socket-destroy-delayed.js
diff --git a/test/js/node/test/parallel/http2-compat-write-early-hints-invalid-argument-type.test.js b/test/js/node/test/parallel/http2-compat-write-early-hints-invalid-argument-type.test.js
deleted file mode 100644
index 0ab3a588a3..0000000000
--- a/test/js/node/test/parallel/http2-compat-write-early-hints-invalid-argument-type.test.js
+++ /dev/null
@@ -1,72 +0,0 @@
-//#FILE: test-http2-compat-write-early-hints-invalid-argument-type.js
-//#SHA1: 8ae2eba59668a38b039a100d3ad26f88e54be806
-//-----------------
-"use strict";
-
-const http2 = require("node:http2");
-const util = require("node:util");
-const debug = util.debuglog("test");
-
-const testResBody = "response content";
-
-// Check if crypto is available
-let hasCrypto = false;
-try {
- require("crypto");
- hasCrypto = true;
-} catch (err) {
- // crypto not available
-}
-
-(hasCrypto ? describe : describe.skip)("HTTP2 compat writeEarlyHints invalid argument type", () => {
- let server;
- let client;
-
- beforeAll(done => {
- server = http2.createServer();
- server.listen(0, () => {
- done();
- });
- });
-
- afterAll(() => {
- if (client) {
- client.close();
- }
- server.close();
- });
-
- test("should throw ERR_INVALID_ARG_TYPE for invalid object value", done => {
- server.on("request", (req, res) => {
- debug("Server sending early hints...");
- expect(() => {
- res.writeEarlyHints("this should not be here");
- }).toThrow(
- expect.objectContaining({
- code: "ERR_INVALID_ARG_TYPE",
- name: "TypeError",
- }),
- );
-
- debug("Server sending full response...");
- res.end(testResBody);
- });
-
- client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request();
-
- debug("Client sending request...");
-
- req.on("headers", () => {
- done(new Error("Should not receive headers"));
- });
-
- req.on("response", () => {
- done();
- });
-
- req.end();
- });
-});
-
-//<#END_FILE: test-http2-compat-write-early-hints-invalid-argument-type.js
diff --git a/test/js/node/test/parallel/http2-compat-write-early-hints.test.js b/test/js/node/test/parallel/http2-compat-write-early-hints.test.js
deleted file mode 100644
index c3d8fb4e15..0000000000
--- a/test/js/node/test/parallel/http2-compat-write-early-hints.test.js
+++ /dev/null
@@ -1,146 +0,0 @@
-//#FILE: test-http2-compat-write-early-hints.js
-//#SHA1: 0ed18263958421cde07c37b8ec353005b7477499
-//-----------------
-'use strict';
-
-const http2 = require('node:http2');
-const util = require('node:util');
-const debug = util.debuglog('test');
-
-const testResBody = 'response content';
-
-describe('HTTP/2 Early Hints', () => {
- test('Happy flow - string argument', async () => {
- const server = http2.createServer();
-
- server.on('request', (req, res) => {
- debug('Server sending early hints...');
- res.writeEarlyHints({
- link: '; rel=preload; as=style'
- });
-
- debug('Server sending full response...');
- res.end(testResBody);
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request();
-
- debug('Client sending request...');
-
- await new Promise(resolve => {
- req.on('headers', (headers) => {
- expect(headers).toBeDefined();
- expect(headers[':status']).toBe(103);
- expect(headers.link).toBe('; rel=preload; as=style');
- });
-
- req.on('response', (headers) => {
- expect(headers[':status']).toBe(200);
- });
-
- let data = '';
- req.on('data', (d) => data += d);
-
- req.on('end', () => {
- debug('Got full response.');
- expect(data).toBe(testResBody);
- client.close();
- server.close(resolve);
- });
- });
- });
-
- test('Happy flow - array argument', async () => {
- const server = http2.createServer();
-
- server.on('request', (req, res) => {
- debug('Server sending early hints...');
- res.writeEarlyHints({
- link: [
- '; rel=preload; as=style',
- '; rel=preload; as=script',
- ]
- });
-
- debug('Server sending full response...');
- res.end(testResBody);
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request();
-
- debug('Client sending request...');
-
- await new Promise(resolve => {
- req.on('headers', (headers) => {
- expect(headers).toBeDefined();
- expect(headers[':status']).toBe(103);
- expect(headers.link).toBe(
- '; rel=preload; as=style, ; rel=preload; as=script'
- );
- });
-
- req.on('response', (headers) => {
- expect(headers[':status']).toBe(200);
- });
-
- let data = '';
- req.on('data', (d) => data += d);
-
- req.on('end', () => {
- debug('Got full response.');
- expect(data).toBe(testResBody);
- client.close();
- server.close(resolve);
- });
- });
- });
-
- test('Happy flow - empty array', async () => {
- const server = http2.createServer();
-
- server.on('request', (req, res) => {
- debug('Server sending early hints...');
- res.writeEarlyHints({
- link: []
- });
-
- debug('Server sending full response...');
- res.end(testResBody);
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const client = http2.connect(`http://localhost:${server.address().port}`);
- const req = client.request();
-
- debug('Client sending request...');
-
- await new Promise(resolve => {
- const headersListener = jest.fn();
- req.on('headers', headersListener);
-
- req.on('response', (headers) => {
- expect(headers[':status']).toBe(200);
- expect(headersListener).not.toHaveBeenCalled();
- });
-
- let data = '';
- req.on('data', (d) => data += d);
-
- req.on('end', () => {
- debug('Got full response.');
- expect(data).toBe(testResBody);
- client.close();
- server.close(resolve);
- });
- });
- });
-});
-
-//<#END_FILE: test-http2-compat-write-early-hints.js
diff --git a/test/js/node/test/parallel/http2-compat-write-head-destroyed.test.js b/test/js/node/test/parallel/http2-compat-write-head-destroyed.test.js
deleted file mode 100644
index 601f47928e..0000000000
--- a/test/js/node/test/parallel/http2-compat-write-head-destroyed.test.js
+++ /dev/null
@@ -1,59 +0,0 @@
-//#FILE: test-http2-compat-write-head-destroyed.js
-//#SHA1: 29f693f49912d4621c1a19ab7412b1b318d55d8e
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-let server;
-let port;
-
-beforeAll(done => {
- if (!process.versions.openssl) {
- done();
- return;
- }
-
- server = http2.createServer((req, res) => {
- // Destroy the stream first
- req.stream.destroy();
-
- res.writeHead(200);
- res.write("hello ");
- res.end("world");
- });
-
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
-});
-
-afterAll(() => {
- if (server) {
- server.close();
- }
-});
-
-test("writeHead, write and end do not crash in compatibility mode", done => {
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
-
- const client = http2.connect(`http://localhost:${port}`);
-
- const req = client.request();
-
- req.on("response", () => {
- done.fail("Should not receive response");
- });
-
- req.on("close", () => {
- client.close();
- done();
- });
-
- req.resume();
-});
-
-//<#END_FILE: test-http2-compat-write-head-destroyed.js
diff --git a/test/js/node/test/parallel/http2-connect-tls-with-delay.test.js b/test/js/node/test/parallel/http2-connect-tls-with-delay.test.js
deleted file mode 100644
index 1161272cab..0000000000
--- a/test/js/node/test/parallel/http2-connect-tls-with-delay.test.js
+++ /dev/null
@@ -1,62 +0,0 @@
-//#FILE: test-http2-connect-tls-with-delay.js
-//#SHA1: 8c5489e025ec14c2cc53788b27fde11a11990e42
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-const tls = require("tls");
-const fs = require("fs");
-const path = require("path");
-
-const serverOptions = {
- key: fs.readFileSync(path.join(__dirname, "..", "fixtures", "keys", "agent1-key.pem")),
- cert: fs.readFileSync(path.join(__dirname, "..", "fixtures", "keys", "agent1-cert.pem")),
-};
-
-let server;
-
-beforeAll(done => {
- server = http2.createSecureServer(serverOptions, (req, res) => {
- res.end();
- });
-
- server.listen(0, "127.0.0.1", done);
-});
-
-afterAll(() => {
- server.close();
-});
-
-test("HTTP/2 connect with TLS and delay", done => {
- const options = {
- ALPNProtocols: ["h2"],
- host: "127.0.0.1",
- servername: "localhost",
- port: server.address().port,
- rejectUnauthorized: false,
- };
-
- const socket = tls.connect(options, async () => {
- socket.once("readable", () => {
- const client = http2.connect("https://localhost:" + server.address().port, {
- ...options,
- createConnection: () => socket,
- });
-
- client.once("remoteSettings", () => {
- const req = client.request({
- ":path": "/",
- });
- req.on("data", () => req.resume());
- req.on("end", () => {
- client.close();
- req.close();
- done();
- });
- req.end();
- });
- });
- });
-});
-
-//<#END_FILE: test-http2-connect-tls-with-delay.js
diff --git a/test/js/node/test/parallel/http2-cookies.test.js b/test/js/node/test/parallel/http2-cookies.test.js
deleted file mode 100644
index c906992d71..0000000000
--- a/test/js/node/test/parallel/http2-cookies.test.js
+++ /dev/null
@@ -1,71 +0,0 @@
-//#FILE: test-http2-cookies.js
-//#SHA1: 91bdbacba9eb8ebd9dddd43327aa2271dc00c271
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-const hasCrypto = (() => {
- try {
- require('crypto');
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-if (!hasCrypto) {
- test.skip('missing crypto', () => {});
-} else {
- test('HTTP/2 cookies', async () => {
- const server = h2.createServer();
-
- const setCookie = [
- 'a=b',
- 'c=d; Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly',
- 'e=f',
- ];
-
- server.on('stream', (stream, headers) => {
- expect(typeof headers.abc).toBe('string');
- expect(headers.abc).toBe('1, 2, 3');
- expect(typeof headers.cookie).toBe('string');
- expect(headers.cookie).toBe('a=b; c=d; e=f');
-
- stream.respond({
- 'content-type': 'text/html',
- ':status': 200,
- 'set-cookie': setCookie
- });
-
- stream.end('hello world');
- });
-
- await new Promise(resolve => server.listen(0, resolve));
-
- const client = h2.connect(`http://localhost:${server.address().port}`);
-
- const req = client.request({
- ':path': '/',
- 'abc': [1, 2, 3],
- 'cookie': ['a=b', 'c=d', 'e=f'],
- });
-
- await new Promise((resolve, reject) => {
- req.on('response', (headers) => {
- expect(Array.isArray(headers['set-cookie'])).toBe(true);
- expect(headers['set-cookie']).toEqual(setCookie);
- });
-
- req.on('end', resolve);
- req.on('error', reject);
- req.end();
- req.resume();
- });
-
- server.close();
- client.close();
- });
-}
-
-//<#END_FILE: test-http2-cookies.js
diff --git a/test/js/node/test/parallel/http2-createwritereq.test.js b/test/js/node/test/parallel/http2-createwritereq.test.js
deleted file mode 100644
index 2c768f880a..0000000000
--- a/test/js/node/test/parallel/http2-createwritereq.test.js
+++ /dev/null
@@ -1,88 +0,0 @@
-//#FILE: test-http2-createwritereq.js
-//#SHA1: 8b0d2399fb8a26ce6cc76b9f338be37a7ff08ca5
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-// Mock the gc function
-global.gc = jest.fn();
-
-const testString = "a\u00A1\u0100\uD83D\uDE00";
-
-const encodings = {
- // "buffer": "utf8",
- "ascii": "ascii",
- // "latin1": "latin1",
- // "binary": "latin1",
- // "utf8": "utf8",
- // "utf-8": "utf8",
- // "ucs2": "ucs2",
- // "ucs-2": "ucs2",
- // "utf16le": "ucs2",
- // "utf-16le": "ucs2",
- // "UTF8": "utf8",
-};
-
-describe("http2 createWriteReq", () => {
- let server;
- let serverAddress;
-
- beforeAll(done => {
- server = http2.createServer((req, res) => {
- const testEncoding = encodings[req.url.slice(1)];
-
- req.on("data", chunk => {
- // console.error(testEncoding, chunk, Buffer.from(testString, testEncoding));
- expect(Buffer.from(testString, testEncoding).equals(chunk)).toBe(true);
- });
-
- req.on("end", () => res.end());
- });
-
- server.listen(0, () => {
- serverAddress = `http://localhost:${server.address().port}`;
- done();
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- Object.keys(encodings).forEach(writeEncoding => {
- test(`should handle ${writeEncoding} encoding`, done => {
- const client = http2.connect(serverAddress);
- const req = client.request({
- ":path": `/${writeEncoding}`,
- ":method": "POST",
- });
-
- expect(req._writableState.decodeStrings).toBe(false);
-
- req.write(
- writeEncoding !== "buffer" ? testString : Buffer.from(testString),
- writeEncoding !== "buffer" ? writeEncoding : undefined,
- );
- req.resume();
-
- req.on("end", () => {
- client.close();
- done();
- });
-
- // Ref: https://github.com/nodejs/node/issues/17840
- const origDestroy = req.destroy;
- req.destroy = function (...args) {
- // Schedule a garbage collection event at the end of the current
- // MakeCallback() run.
- process.nextTick(global.gc);
- return origDestroy.call(this, ...args);
- };
-
- req.end();
- });
- });
-});
-
-//<#END_FILE: test-http2-createwritereq.test.js
diff --git a/test/js/node/test/parallel/http2-destroy-after-write.test.js b/test/js/node/test/parallel/http2-destroy-after-write.test.js
deleted file mode 100644
index c3303887ac..0000000000
--- a/test/js/node/test/parallel/http2-destroy-after-write.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-http2-destroy-after-write.js
-//#SHA1: 193688397df0b891b9286ff825ca873935d30e04
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-let server;
-let port;
-
-beforeAll(done => {
- server = http2.createServer();
-
- server.on("session", session => {
- session.on("stream", stream => {
- stream.on("end", function () {
- this.respond({
- ":status": 200,
- });
- this.write("foo");
- this.destroy();
- });
- stream.resume();
- });
- });
-
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
-});
-
-afterAll(() => {
- server.close();
-});
-
-test("http2 destroy after write", done => {
- const client = http2.connect(`http://localhost:${port}`);
- const stream = client.request({ ":method": "POST" });
-
- stream.on("response", headers => {
- expect(headers[":status"]).toBe(200);
- });
-
- stream.on("close", () => {
- client.close();
- done();
- });
-
- stream.resume();
- stream.end();
-});
-
-//<#END_FILE: test-http2-destroy-after-write.js
diff --git a/test/js/node/test/parallel/http2-dont-override.test.js b/test/js/node/test/parallel/http2-dont-override.test.js
deleted file mode 100644
index ea465da5a3..0000000000
--- a/test/js/node/test/parallel/http2-dont-override.test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-//#FILE: test-http2-dont-override.js
-//#SHA1: d295b8c4823cc34c03773eb08bf0393fca541694
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-// Skip test if crypto is not available
-if (!process.versions.openssl) {
- test.skip('missing crypto', () => {});
-} else {
- test('http2 should not override options', (done) => {
- const options = {};
-
- const server = http2.createServer(options);
-
- // Options are defaulted but the options are not modified
- expect(Object.keys(options)).toEqual([]);
-
- server.on('stream', (stream) => {
- const headers = {};
- const options = {};
- stream.respond(headers, options);
-
- // The headers are defaulted but the original object is not modified
- expect(Object.keys(headers)).toEqual([]);
-
- // Options are defaulted but the original object is not modified
- expect(Object.keys(options)).toEqual([]);
-
- stream.end();
- });
-
- server.listen(0, () => {
- const client = http2.connect(`http://localhost:${server.address().port}`);
-
- const headers = {};
- const options = {};
-
- const req = client.request(headers, options);
-
- // The headers are defaulted but the original object is not modified
- expect(Object.keys(headers)).toEqual([]);
-
- // Options are defaulted but the original object is not modified
- expect(Object.keys(options)).toEqual([]);
-
- req.resume();
- req.on('end', () => {
- server.close();
- client.close();
- done();
- });
- });
- });
-}
-
-//<#END_FILE: test-http2-dont-override.js
diff --git a/test/js/node/test/parallel/http2-forget-closed-streams.test.js b/test/js/node/test/parallel/http2-forget-closed-streams.test.js
deleted file mode 100644
index b21280b343..0000000000
--- a/test/js/node/test/parallel/http2-forget-closed-streams.test.js
+++ /dev/null
@@ -1,85 +0,0 @@
-//#FILE: test-http2-forget-closed-streams.js
-//#SHA1: 2f917924c763cc220e68ce2b829c63dc03a836ab
-//-----------------
-"use strict";
-const http2 = require("http2");
-
-// Skip test if crypto is not available
-const hasCrypto = (() => {
- try {
- require("crypto");
- return true;
- } catch (err) {
- return false;
- }
-})();
-
-(hasCrypto ? describe : describe.skip)("http2 forget closed streams", () => {
- let server;
-
- beforeAll(() => {
- server = http2.createServer({ maxSessionMemory: 1 });
-
- server.on("session", session => {
- session.on("stream", stream => {
- stream.on("end", () => {
- stream.respond(
- {
- ":status": 200,
- },
- {
- endStream: true,
- },
- );
- });
- stream.resume();
- });
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- test("should handle 10000 requests without memory issues", done => {
- const listenPromise = new Promise(resolve => {
- server.listen(0, () => {
- resolve(server.address().port);
- });
- });
-
- listenPromise.then(port => {
- const client = http2.connect(`http://localhost:${port}`);
-
- function makeRequest(i) {
- return new Promise(resolve => {
- const stream = client.request({ ":method": "POST" });
- stream.on("response", headers => {
- expect(headers[":status"]).toBe(200);
- stream.on("close", resolve);
- });
- stream.end();
- });
- }
-
- async function runRequests() {
- for (let i = 0; i < 10000; i++) {
- await makeRequest(i);
- }
- client.close();
- }
-
- runRequests()
- .then(() => {
- // If we've reached here without errors, the test has passed
- expect(true).toBe(true);
- done();
- })
- .catch(err => {
- done(err);
- });
- });
- }, 30000); // Increase timeout to 30 seconds
-});
-
-//<#END_FILE: test-http2-forget-closed-streams.js
diff --git a/test/js/node/test/parallel/http2-goaway-opaquedata.test.js b/test/js/node/test/parallel/http2-goaway-opaquedata.test.js
deleted file mode 100644
index 7de3263266..0000000000
--- a/test/js/node/test/parallel/http2-goaway-opaquedata.test.js
+++ /dev/null
@@ -1,58 +0,0 @@
-//#FILE: test-http2-goaway-opaquedata.js
-//#SHA1: 5ad5b6a64cb0e7419753dcd88d59692eb97973ed
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-let server;
-let serverPort;
-
-beforeAll((done) => {
- server = http2.createServer();
- server.listen(0, () => {
- serverPort = server.address().port;
- done();
- });
-});
-
-afterAll((done) => {
- server.close(done);
-});
-
-test('HTTP/2 GOAWAY with opaque data', (done) => {
- const data = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
- let session;
-
- server.once('stream', (stream) => {
- session = stream.session;
- session.on('close', () => {
- expect(true).toBe(true); // Session closed
- });
- session.goaway(0, 0, data);
- stream.respond();
- stream.end();
- });
-
- const client = http2.connect(`http://localhost:${serverPort}`);
- client.once('goaway', (code, lastStreamID, buf) => {
- expect(code).toBe(0);
- expect(lastStreamID).toBe(1);
- expect(buf).toEqual(data);
- session.close();
- client.close();
- done();
- });
-
- const req = client.request();
- req.resume();
- req.on('end', () => {
- expect(true).toBe(true); // Request ended
- });
- req.on('close', () => {
- expect(true).toBe(true); // Request closed
- });
- req.end();
-});
-
-//<#END_FILE: test-http2-goaway-opaquedata.js
diff --git a/test/js/node/test/parallel/http2-large-write-close.test.js b/test/js/node/test/parallel/http2-large-write-close.test.js
deleted file mode 100644
index f50a3b581f..0000000000
--- a/test/js/node/test/parallel/http2-large-write-close.test.js
+++ /dev/null
@@ -1,70 +0,0 @@
-//#FILE: test-http2-large-write-close.js
-//#SHA1: 66ad4345c0888700887c23af455fdd9ff49721d9
-//-----------------
-"use strict";
-const fixtures = require("../common/fixtures");
-const http2 = require("http2");
-
-const { beforeEach, afterEach, test, expect } = require("bun:test");
-const { isWindows } = require("harness");
-const content = Buffer.alloc(1e5, 0x44);
-
-let server;
-let port;
-
-beforeEach(done => {
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
-
- server = http2.createSecureServer({
- key: fixtures.readKey("agent1-key.pem"),
- cert: fixtures.readKey("agent1-cert.pem"),
- });
-
- server.on("stream", stream => {
- stream.respond({
- "Content-Type": "application/octet-stream",
- "Content-Length": content.byteLength.toString() * 2,
- "Vary": "Accept-Encoding",
- });
-
- stream.write(content);
- stream.write(content);
- stream.end();
- stream.close();
- });
-
- server.listen(0, () => {
- port = server.address().port;
- done();
- });
-});
-
-afterEach(() => {
- server.close();
-});
-
-test.todoIf(isWindows)(
- "HTTP/2 large write and close",
- done => {
- const client = http2.connect(`https://localhost:${port}`, { rejectUnauthorized: false });
-
- const req = client.request({ ":path": "/" });
- req.end();
-
- let receivedBufferLength = 0;
- req.on("data", buf => {
- receivedBufferLength += buf.byteLength;
- });
-
- req.on("close", () => {
- expect(receivedBufferLength).toBe(content.byteLength * 2);
- client.close();
- done();
- });
- },
- 5000,
-);
-
-//<#END_FILE: test-http2-large-write-close.js
diff --git a/test/js/node/test/parallel/http2-large-write-destroy.test.js b/test/js/node/test/parallel/http2-large-write-destroy.test.js
deleted file mode 100644
index b9d7679961..0000000000
--- a/test/js/node/test/parallel/http2-large-write-destroy.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-//#FILE: test-http2-large-write-destroy.js
-//#SHA1: 0c76344570b21b6ed78f12185ddefde59a9b2914
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-const content = Buffer.alloc(60000, 0x44);
-
-let server;
-
-afterEach(() => {
- if (server) {
- server.close();
- }
-});
-
-test('HTTP/2 large write and destroy', (done) => {
- server = http2.createServer();
-
- server.on('stream', (stream) => {
- stream.respond({
- 'Content-Type': 'application/octet-stream',
- 'Content-Length': (content.length.toString() * 2),
- 'Vary': 'Accept-Encoding'
- }, { waitForTrailers: true });
-
- stream.write(content);
- stream.destroy();
- });
-
- server.listen(0, () => {
- const client = http2.connect(`http://localhost:${server.address().port}`);
-
- const req = client.request({ ':path': '/' });
- req.end();
- req.resume(); // Otherwise close won't be emitted if there's pending data.
-
- req.on('close', () => {
- client.close();
- done();
- });
-
- req.on('error', (err) => {
- // We expect an error due to the stream being destroyed
- expect(err.code).toBe('ECONNRESET');
- client.close();
- done();
- });
- });
-});
-
-//<#END_FILE: test-http2-large-write-destroy.js
diff --git a/test/js/node/test/parallel/http2-large-writes-session-memory-leak.test.js b/test/js/node/test/parallel/http2-large-writes-session-memory-leak.test.js
deleted file mode 100644
index e718f292ff..0000000000
--- a/test/js/node/test/parallel/http2-large-writes-session-memory-leak.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-//#FILE: test-http2-large-writes-session-memory-leak.js
-//#SHA1: 8f39b92e38fac58143b4d50534b2f6a171fb1a1b
-//-----------------
-'use strict';
-
-const http2 = require('http2');
-
-test.skip('HTTP/2 large writes should not cause session memory leak', () => {
- console.log('This test is skipped because it requires specific Node.js internals and fixtures.');
- console.log('Original test description:');
- console.log('Regression test for https://github.com/nodejs/node/issues/29223.');
- console.log('There was a "leak" in the accounting of session memory leading');
- console.log('to streams eventually failing with NGHTTP2_ENHANCE_YOUR_CALM.');
-
- // Original test logic preserved for reference:
- /*
- const server = http2.createSecureServer({
- key: fixtures.readKey('agent2-key.pem'),
- cert: fixtures.readKey('agent2-cert.pem'),
- });
-
- const data200k = 'a'.repeat(200 * 1024);
- server.on('stream', (stream) => {
- stream.write(data200k);
- stream.end();
- });
-
- server.listen(0, () => {
- const client = http2.connect(`https://localhost:${server.address().port}`, {
- ca: fixtures.readKey('agent2-cert.pem'),
- servername: 'agent2',
- maxSessionMemory: 1
- });
-
- let streamsLeft = 50;
- function newStream() {
- const stream = client.request({ ':path': '/' });
- stream.on('data', () => { });
- stream.on('close', () => {
- if (streamsLeft-- > 0) {
- newStream();
- } else {
- client.destroy();
- server.close();
- }
- });
- }
- newStream();
- });
- */
-});
-
-//<#END_FILE: test-http2-large-writes-session-memory-leak.js
diff --git a/test/js/node/test/parallel/http2-many-writes-and-destroy.test.js b/test/js/node/test/parallel/http2-many-writes-and-destroy.test.js
deleted file mode 100644
index 503419d879..0000000000
--- a/test/js/node/test/parallel/http2-many-writes-and-destroy.test.js
+++ /dev/null
@@ -1,56 +0,0 @@
-//#FILE: test-http2-many-writes-and-destroy.js
-//#SHA1: b4a66fa27d761038f79e0eb3562f521724887db4
-//-----------------
-"use strict";
-
-const http2 = require("http2");
-
-// Skip the test if crypto is not available
-let hasCrypto;
-try {
- require("crypto");
- hasCrypto = true;
-} catch (err) {
- hasCrypto = false;
-}
-
-(hasCrypto ? describe : describe.skip)("HTTP/2 many writes and destroy", () => {
- let server;
- let url;
-
- beforeAll(done => {
- server = http2.createServer((req, res) => {
- req.pipe(res);
- });
-
- server.listen(0, () => {
- url = `http://localhost:${server.address().port}`;
- done();
- });
- });
-
- afterAll(() => {
- server.close();
- });
-
- test("should handle many writes and destroy", done => {
- const client = http2.connect(url);
- const req = client.request({ ":method": "POST" });
-
- for (let i = 0; i < 4000; i++) {
- req.write(Buffer.alloc(6));
- }
-
- req.on("close", () => {
- console.log("(req onclose)");
- client.close();
- done();
- });
-
- req.once("data", () => {
- req.destroy();
- });
- });
-});
-
-//<#END_FILE: test-http2-many-writes-and-destroy.js
diff --git a/test/js/node/test/parallel/http2-misc-util.test.js b/test/js/node/test/parallel/http2-misc-util.test.js
deleted file mode 100644
index 0af25ec564..0000000000
--- a/test/js/node/test/parallel/http2-misc-util.test.js
+++ /dev/null
@@ -1,39 +0,0 @@
-//#FILE: test-http2-misc-util.js
-//#SHA1: 0fa21e185faeff6ee5b1d703d9a998bf98d6b229
-//-----------------
-const http2 = require("http2");
-
-describe("HTTP/2 Misc Util", () => {
- test("HTTP2 constants are defined", () => {
- expect(http2.constants).toBeDefined();
- expect(http2.constants.NGHTTP2_SESSION_SERVER).toBe(0);
- expect(http2.constants.NGHTTP2_SESSION_CLIENT).toBe(1);
- });
- // make it not fail after re-enabling push
- test.todo("HTTP2 default settings are within valid ranges", () => {
- const defaultSettings = http2.getDefaultSettings();
- expect(defaultSettings).toBeDefined();
- expect(defaultSettings.headerTableSize).toBeGreaterThanOrEqual(0);
- expect(defaultSettings.enablePush).toBe(true); // push is disabled because is not implemented yet
- expect(defaultSettings.initialWindowSize).toBeGreaterThanOrEqual(0);
- expect(defaultSettings.maxFrameSize).toBeGreaterThanOrEqual(16384);
- expect(defaultSettings.maxConcurrentStreams).toBeGreaterThanOrEqual(0);
- expect(defaultSettings.maxHeaderListSize).toBeGreaterThanOrEqual(0);
- });
-
- test("HTTP2 getPackedSettings and getUnpackedSettings", () => {
- const settings = {
- headerTableSize: 4096,
- enablePush: true,
- initialWindowSize: 65535,
- maxFrameSize: 16384,
- };
- const packed = http2.getPackedSettings(settings);
- expect(packed).toBeInstanceOf(Buffer);
-
- const unpacked = http2.getUnpackedSettings(packed);
- expect(unpacked).toEqual(expect.objectContaining(settings));
- });
-});
-
-//<#END_FILE: test-http2-misc-util.js
diff --git a/test/js/node/test/parallel/http2-multistream-destroy-on-read-tls.test.js b/test/js/node/test/parallel/http2-multistream-destroy-on-read-tls.test.js
deleted file mode 100644
index 5e27b6472c..0000000000
--- a/test/js/node/test/parallel/http2-multistream-destroy-on-read-tls.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-//#FILE: test-http2-multistream-destroy-on-read-tls.js
-//#SHA1: bf3869a9f8884210710d41c0fb1f54d2112e9af5
-//-----------------
-"use strict";
-const http2 = require("http2");
-
-describe("HTTP2 multistream destroy on read", () => {
- let server;
- const filenames = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
-
- beforeAll(done => {
- server = http2.createServer();
-
- server.on("stream", stream => {
- function write() {
- stream.write("a".repeat(10240));
- stream.once("drain", write);
- }
- write();
- });
-
- server.listen(0, done);
- });
-
- afterAll(() => {
- if (server) {
- server.close();
- } else {
- done();
- }
- });
-
- test("should handle multiple stream destructions", done => {
- const client = http2.connect(`http://localhost:${server.address().port}`);
-
- let destroyed = 0;
- for (const entry of filenames) {
- const stream = client.request({
- ":path": `/${entry}`,
- });
- stream.once("data", () => {
- stream.destroy();
-
- if (++destroyed === filenames.length) {
- client.close();
- done();
- }
- });
- }
- });
-});
-
-//<#END_FILE: test-http2-multistream-destroy-on-read-tls.js
diff --git a/test/js/node/test/parallel/http2-no-wanttrailers-listener.test.js b/test/js/node/test/parallel/http2-no-wanttrailers-listener.test.js
deleted file mode 100644
index b7aa239af9..0000000000
--- a/test/js/node/test/parallel/http2-no-wanttrailers-listener.test.js
+++ /dev/null
@@ -1,51 +0,0 @@
-//#FILE: test-http2-no-wanttrailers-listener.js
-//#SHA1: a5297c0a1ed58f7d2d0a13bc4eaaa198a7ab160e
-//-----------------
-"use strict";
-
-const h2 = require("http2");
-
-let server;
-let client;
-
-beforeAll(() => {
- // Check if crypto is available
- if (!process.versions.openssl) {
- return test.skip("missing crypto");
- }
-});
-
-afterEach(() => {
- if (client) {
- client.close();
- }
- if (server) {
- server.close();
- }
-});
-
-test("HTTP/2 server should not hang without wantTrailers listener", done => {
- server = h2.createServer();
-
- server.on("stream", (stream, headers, flags) => {
- stream.respond(undefined, { waitForTrailers: true });
- stream.end("ok");
- });
-
- server.listen(0, () => {
- const port = server.address().port;
- client = h2.connect(`http://localhost:${port}`);
- const req = client.request();
- req.resume();
-
- req.on("trailers", () => {
- throw new Error("Unexpected trailers event");
- });
-
- req.on("close", () => {
- done();
- });
- });
-});
-
-//<#END_FILE: test-http2-no-wanttrailers-listener.js
diff --git a/test/js/node/test/parallel/http2-options-server-response.test.js b/test/js/node/test/parallel/http2-options-server-response.test.js
deleted file mode 100644
index 4ad8e33898..0000000000
--- a/test/js/node/test/parallel/http2-options-server-response.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-//#FILE: test-http2-options-server-response.js
-//#SHA1: 66736f340efdbdf2e20a79a3dffe75f499e65d89
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-
-class MyServerResponse extends h2.Http2ServerResponse {
- status(code) {
- return this.writeHead(code, { 'Content-Type': 'text/plain' });
- }
-}
-
-let server;
-let client;
-
-beforeAll(() => {
- if (!process.versions.openssl) {
- return test.skip('missing crypto');
- }
-});
-
-afterAll(() => {
- if (server) server.close();
- if (client) client.destroy();
-});
-
-test('http2 server with custom ServerResponse', (done) => {
- server = h2.createServer({
- Http2ServerResponse: MyServerResponse
- }, (req, res) => {
- res.status(200);
- res.end();
- });
-
- server.listen(0, () => {
- const port = server.address().port;
- client = h2.connect(`http://localhost:${port}`);
- const req = client.request({ ':path': '/' });
-
- const responseHandler = jest.fn();
- req.on('response', responseHandler);
-
- const endHandler = jest.fn(() => {
- expect(responseHandler).toHaveBeenCalled();
- done();
- });
-
- req.resume();
- req.on('end', endHandler);
- });
-});
-
-//<#END_FILE: test-http2-options-server-response.js
diff --git a/test/js/node/test/parallel/http2-perf_hooks.test.js b/test/js/node/test/parallel/http2-perf_hooks.test.js
deleted file mode 100644
index b45b8d48c7..0000000000
--- a/test/js/node/test/parallel/http2-perf_hooks.test.js
+++ /dev/null
@@ -1,124 +0,0 @@
-//#FILE: test-http2-perf_hooks.js
-//#SHA1: a759a55527c8587bdf272da00c6597d93aa36da0
-//-----------------
-'use strict';
-
-const h2 = require('http2');
-const { PerformanceObserver } = require('perf_hooks');
-
-let server;
-let client;
-
-beforeAll(() => {
- if (!process.versions.openssl) {
- return test.skip('missing crypto');
- }
-});
-
-afterEach(() => {
- if (client) client.close();
- if (server) server.close();
-});
-
-test('HTTP/2 performance hooks', (done) => {
- const obs = new PerformanceObserver((items) => {
- const entry = items.getEntries()[0];
- expect(entry.entryType).toBe('http2');
- expect(typeof entry.startTime).toBe('number');
- expect(typeof entry.duration).toBe('number');
-
- switch (entry.name) {
- case 'Http2Session':
- expect(typeof entry.pingRTT).toBe('number');
- expect(typeof entry.streamAverageDuration).toBe('number');
- expect(typeof entry.streamCount).toBe('number');
- expect(typeof entry.framesReceived).toBe('number');
- expect(typeof entry.framesSent).toBe('number');
- expect(typeof entry.bytesWritten).toBe('number');
- expect(typeof entry.bytesRead).toBe('number');
- expect(typeof entry.maxConcurrentStreams).toBe('number');
- expect(typeof entry.detail.pingRTT).toBe('number');
- expect(typeof entry.detail.streamAverageDuration).toBe('number');
- expect(typeof entry.detail.streamCount).toBe('number');
- expect(typeof entry.detail.framesReceived).toBe('number');
- expect(typeof entry.detail.framesSent).toBe('number');
- expect(typeof entry.detail.bytesWritten).toBe('number');
- expect(typeof entry.detail.bytesRead).toBe('number');
- expect(typeof entry.detail.maxConcurrentStreams).toBe('number');
- switch (entry.type) {
- case 'server':
- expect(entry.detail.streamCount).toBe(1);
- expect(entry.detail.framesReceived).toBeGreaterThanOrEqual(3);
- break;
- case 'client':
- expect(entry.detail.streamCount).toBe(1);
- expect(entry.detail.framesReceived).toBe(7);
- break;
- default:
- fail('invalid Http2Session type');
- }
- break;
- case 'Http2Stream':
- expect(typeof entry.timeToFirstByte).toBe('number');
- expect(typeof entry.timeToFirstByteSent).toBe('number');
- expect(typeof entry.timeToFirstHeader).toBe('number');
- expect(typeof entry.bytesWritten).toBe('number');
- expect(typeof entry.bytesRead).toBe('number');
- expect(typeof entry.detail.timeToFirstByte).toBe('number');
- expect(typeof entry.detail.timeToFirstByteSent).toBe('number');
- expect(typeof entry.detail.timeToFirstHeader).toBe('number');
- expect(typeof entry.detail.bytesWritten).toBe('number');
- expect(typeof entry.detail.bytesRead).toBe('number');
- break;
- default:
- fail('invalid entry name');
- }
- });
-
- obs.observe({ type: 'http2' });
-
- const body = '