Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

feat(common): data-driven collection runs with datasets (#6513)

Prajjwol755d622bf3b9
diff --git a/packages/hoppscotch-common/locales/en.json b/packages/hoppscotch-common/locales/en.json
index b928b959d..4dd9e2988 100644
--- a/packages/hoppscotch-common/locales/en.json
+++ b/packages/hoppscotch-common/locales/en.json
@@ -1998,6 +1998,39 @@
"cli_comming_soon_for_personal_collection": "Collection Runner for personal collections in CLI is coming soon.",
"delay": "Delay",
"negative_delay": "Delay cannot be negative",
+ "iterations": "Iterations",
+ "time": "time",
+ "times": "times",
+ "invalid_iterations": "Iterations must be at least 1",
+ "data_feed": "Data Feed",
+ "data_feed_help": "Import a CSV or JSON file to run one iteration per row.",
+ "select_data_file": "Select CSV / JSON File",
+ "data_preview": "Data Preview",
+ "dataset_row": "{count} row",
+ "dataset_rows": "{count} rows",
+ "dataset_preview_truncated": "Showing the first {count} rows of the dataset.",
+ "dataset_iterations_info": "Dataset contains {rows} rows, running {total} iterations as per your configuration.",
+ "iterations_locked_to_dataset": "Iterations match the dataset row count. Remove the data file to set this manually.",
+ "jump_to_iteration": "Jump to iteration",
+ "previous_iteration": "Previous iteration",
+ "next_iteration": "Next iteration",
+ "invalid_data_file": "Invalid data file",
+ "empty_data_file": "Data file is empty",
+ "data_file_size_limit_exceeded": "The data file exceeds the {sizeLimit} MB limit",
+ "collection_load_failed": "Could not load this collection.",
+ "filter_requests": "Filter requests",
+ "no_requests_match_filter": "No requests match the filter",
+ "selection_reset": "The collection changed, so all requests will run.",
+ "selection_partially_reset": "Some selected requests no longer exist and were removed from the selection.",
+ "remove_file": "Remove file",
+ "run_sequence": "Run Sequence",
+ "reset_run_order": "Reset",
+ "export_results": "Export results",
+ "select_all": "Select all",
+ "deselect_all": "Deselect all",
+ "selected_requests_count": "{selected} of {total} selected",
+ "no_requests_selected": "Select at least one request to run",
+ "iteration": "Iteration {count}",
"ui": "Runner",
"running_collection": "Running collection",
"run_config": "Run Configuration",
@@ -2014,6 +2047,7 @@
"cli_command_generation_description_sh": "Copy the below command and run it from the CLI. Please specify a personal access token and verify the generated SH instance server URL.",
"cli_command_generation_description_sh_with_server_url_placeholder": "Copy the below command and run it from the CLI. Please specify a personal access token and the SH instance server URL.",
"run_collection": "Run collection",
+ "results_not_restored": "Run results aren't kept after a reload. Run the collection again to see them.",
"no_passed_tests": "No tests passed",
"no_failed_tests": "No tests failed"
},
diff --git a/packages/hoppscotch-common/package.json b/packages/hoppscotch-common/package.json
index ea9006adb..664c5b05b 100644
--- a/packages/hoppscotch-common/package.json
+++ b/packages/hoppscotch-common/package.json
@@ -87,6 +87,7 @@
"monaco-editor": "0.55.1",
"nprogress": "0.2.0",
"paho-mqtt": "1.1.0",
+ "papaparse": "5.5.4",
"path": "0.12.7",
"postman-collection": "5.3.1",
"process": "0.11.10",
@@ -147,6 +148,7 @@
"@types/lodash-es": "4.17.12",
"@types/nprogress": "0.2.3",
"@types/paho-mqtt": "1.0.10",
+ "@types/papaparse": "5.5.2",
"@types/postman-collection": "3.5.11",
"@types/qs": "6.15.1",
"@types/splitpanes": "2.2.6",
diff --git a/packages/hoppscotch-common/src/components.d.ts b/packages/hoppscotch-common/src/components.d.ts
index 46b4f3976..05bb83ac4 100644
--- a/packages/hoppscotch-common/src/components.d.ts
+++ b/packages/hoppscotch-common/src/components.d.ts
@@ -233,6 +233,7 @@ declare module 'vue' {
HttpTestRunner: typeof import('./components/http/test/Runner.vue')['default']
HttpTestRunnerMeta: typeof import('./components/http/test/RunnerMeta.vue')['default']
HttpTestRunnerModal: typeof import('./components/http/test/RunnerModal.vue')['default']
+ HttpTestRunnerRequestSelector: typeof import('./components/http/test/RunnerRequestSelector.vue')['default']
HttpTestRunnerResult: typeof import('./components/http/test/RunnerResult.vue')['default']
HttpTests: typeof import('./components/http/Tests.vue')['default']
HttpTestTestResult: typeof import('./components/http/test/TestResult.vue')['default']
diff --git a/packages/hoppscotch-common/src/components/http/test/Response.vue b/packages/hoppscotch-common/src/components/http/test/Response.vue
index b8cb8f0b8..dc7a7ece0 100644
--- a/packages/hoppscotch-common/src/components/http/test/Response.vue
+++ b/packages/hoppscotch-common/src/components/http/test/Response.vue
@@ -29,6 +29,7 @@
:is-editable="false"
:is-test-runner="true"
:show-response="showResponse"
+ :tab-id="tabId"
/>
<HoppSmartPlaceholder
v-else
@@ -54,6 +55,8 @@ const colorMode = useColorMode()
const props = defineProps<{
showResponse: boolean
document: TestRunnerRequest
+ /** Owning runner tab — the lens renderers key their state by tab. */
+ tabId: string
}>()
const emit = defineEmits<{
diff --git a/packages/hoppscotch-common/src/components/http/test/ResultFolder.vue b/packages/hoppscotch-common/src/components/http/test/ResultFolder.vue
index 180f62ba7..5c448d56e 100644
--- a/packages/hoppscotch-common/src/components/http/test/ResultFolder.vue
+++ b/packages/hoppscotch-common/src/components/http/test/ResultFolder.vue
@@ -12,11 +12,6 @@
<span
class="flex items-center justify-center px-4 pointer-events-none"
>
- <HoppSmartCheckbox
- v-if="showSelection"
- :on="isSelected"
- class="mr-2"
- />
<component :is="IconFolderOpen" class="svg-icons" />
</span>
<span
@@ -52,23 +47,19 @@ const props = withDefaults(
*/
folderType: FolderType
isOpen: boolean
- isSelected?: boolean
exportLoading?: boolean
hasNoTeamAccess?: boolean
collectionMoveLoading?: string[]
isLastItem?: boolean
- showSelection?: boolean
}>(),
{
id: "",
parentID: null,
folderType: "collection",
isOpen: false,
- isSelected: false,
exportLoading: false,
hasNoTeamAccess: false,
isLastItem: false,
- showSelection: false,
}
)
diff --git a/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue b/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue
index 24803789b..9ddb69762 100644
--- a/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue
+++ b/packages/hoppscotch-common/src/components/http/test/ResultRequest.vue
@@ -6,6 +6,18 @@
@click="selectRequest()"
>
<div class="flex gap-4 mb-1 items-center">
+ <!-- Results are flat, so the folder shows here instead of by nesting. -->
+ <span
+ v-if="request.folderPath?.length"
+ v-tippy="{ theme: 'tooltip' }"
+ :title="request.folderPath.join(' / ')"
+ class="flex items-center flex-shrink-0 text-secondaryLight"
+ >
+ <template v-for="(folder, depth) in request.folderPath" :key="depth">
+ <component :is="IconFolder" class="svg-icons" />
+ <component :is="IconChevronRight" class="svg-icons opacity-60" />
+ </template>
+ </span>
<span
class="flex items-center justify-center truncate pointer-events-none"
:style="{ color: requestLabelColor }"
@@ -17,18 +29,35 @@
<span class="truncate text-sm text-secondaryDark">
{{ request.name }}
</span>
- <span
- v-if="request.response?.statusCode"
- :class="[
- statusCategory.className,
- 'outlined text-[10px] rounded px-2 flex items-center',
- ]"
- >
- {{ `${request.response?.statusCode}` }}
- </span>
- <span v-if="isLoading" class="flex flex-col items-center">
- <HoppSmartSpinner />
- </span>
+
+ <span class="flex-1" />
+
+ <div class="flex flex-shrink-0 items-center gap-2">
+ <span
+ v-if="request.response?.statusCode"
+ v-tippy="{ theme: 'tooltip' }"
+ :title="statusTooltip"
+ :class="statusCategory.className"
+ class="outlined rounded px-1.5 py-0.5 text-tiny font-semibold tabular-nums leading-none flex items-center"
+ >
+ {{ request.response.statusCode }}
+ </span>
+ <span
+ v-if="responseDuration !== null"
+ class="text-tiny text-secondaryLight tabular-nums"
+ >
+ {{ `${responseDuration} ms` }}
+ </span>
+ <span
+ v-if="responseSize !== null"
+ class="text-tiny text-secondaryLight tabular-nums"
+ >
+ {{ responseSize }}
+ </span>
+ <span v-if="isLoading" class="flex items-center">
+ <HoppSmartSpinner />
+ </span>
+ </div>
</div>
<p class="text-left text-secondaryLight text-sm">
@@ -38,7 +67,11 @@
<div
v-if="request.error"
- class="py-2 pl-4 ml-4 mb-2 border-l text-red-500 border-red-500"
+ class="py-2 pl-4 ml-4 mb-2 border-l"
+ :style="{
+ color: 'var(--status-critical-error-color)',
+ borderColor: 'var(--status-critical-error-color)',
+ }"
>
<span> {{ request.error }} </span>
</div>
@@ -54,7 +87,10 @@
import { computed } from "vue"
import findStatusGroup from "~/helpers/findStatusGroup"
import { getMethodLabelColorClassOf } from "~/helpers/rest/labelColoring"
+import { getStatusCodePhrase } from "~/helpers/utils/statusCodes"
import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"
+import IconChevronRight from "~icons/lucide/chevron-right"
+import IconFolder from "~icons/lucide/folder"
const props = withDefaults(
defineProps<{
@@ -63,14 +99,12 @@ const props = withDefaults(
parentID: string | null
isActive?: boolean
isSelected?: boolean
- showSelection?: boolean
showTestType: "all" | "passed" | "failed"
}>(),
{
parentID: null,
isActive: false,
isSelected: false,
- showSelection: false,
requestID: "",
}
)
@@ -89,11 +123,39 @@ const statusCategory = computed(() => {
)
return {
name: "error",
- className: "text-red-500",
+ className: "critical-error-response",
}
return findStatusGroup(props.request?.response.statusCode)
})
+// Only success/fail responses carry meta (duration + size).
+const responseMeta = computed(() => {
+ const response = props.request?.response
+ if (response?.type === "success" || response?.type === "fail")
+ return response.meta
+ return null
+})
+
+const responseDuration = computed(
+ () => responseMeta.value?.responseDuration ?? null
+)
+
+// The badge stays a bare code; the reason phrase rides along on hover.
+const statusTooltip = computed(() => {
+ const response = props.request?.response
+ if (response?.type !== "success" && response?.type !== "fail") return ""
+
+ return getStatusCodePhrase(response.statusCode, response.statusText)
+})
+
+const responseSize = computed(() => {
+ const size = responseMeta.value?.responseSize
+ if (size === undefined) return null
+ if (size >= 100000) return `${(size / 1000000).toFixed(2)} MB`
+ if (size >= 1000) return `${(size / 1000).toFixed(2)} KB`
+ return `${size} B`
+})
+
const emit = defineEmits<{
(event: "select-request"): void
}>()
diff --git a/packages/hoppscotch-common/src/components/http/test/Runner.vue b/packages/hoppscotch-common/src/components/http/test/Runner.vue
index 9290cae13..65ff47407 100644
--- a/packages/hoppscotch-common/src/components/http/test/Runner.vue
+++ b/packages/hoppscotch-common/src/components/http/test/Runner.vue
@@ -2,63 +2,153 @@
<AppPaneLayout layout-id="test-runner-primary">
<template #primary>
<div
- class="flex flex-shrink-0 p-4 overflow-x-auto space-x-2 bg-primary sticky top-0 z-20"
+ class="flex flex-col"
+ :style="
+ headerHeight
+ ? { '--upper-runner-sticky-fold': `${headerHeight}px` }
+ : undefined
+ "
>
- <div class="inline-flex flex-1 gap-8">
- <HttpTestRunnerMeta
- :heading="t('collection.title')"
- :text="collectionName"
- />
-
- <template v-if="showResult">
- <HttpTestRunnerMeta :heading="t('environment.heading')">
- <HttpTestEnv />
- </HttpTestRunnerMeta>
- <!-- <HttpTestRunnerMeta :heading="t('test.iterations')" :text="'1'" /> -->
+ <div
+ ref="headerEl"
+ class="flex flex-col flex-shrink-0 bg-primary sticky top-0 z-20"
+ >
+ <div class="flex items-center gap-4 px-4 pt-4">
<HttpTestRunnerMeta
+ class="min-w-0 flex-1"
+ :heading="t('collection.title')"
+ :text="collectionName"
+ />
+ <div class="flex items-center gap-2 flex-shrink-0">
+ <HoppButtonPrimary
+ v-if="showResult && tab.document.status === 'running'"
+ :label="t('test.stop')"
+ @click="stopTests()"
+ />
+ <HoppButtonPrimary
+ v-else
+ :label="t('test.run_again')"
+ @click="runAgain()"
+ />
+ <HoppButtonSecondary
+ v-if="showResult && tab.document.status !== 'running'"
+ :icon="IconPlus"
+ :label="t('test.new_run')"
+ filled
+ outline
+ @click="newRun()"
+ />
+ <HoppButtonSecondary
+ v-if="canExport"
+ :icon="IconDownload"
+ :label="t('collection_runner.export_results')"
+ filled
+ outline
+ @click="exportResults('all')"
+ />
+ </div>
+ </div>
+
+ <!-- Hidden on a restored tab: a row of zeroes would crowd out the
+ empty placeholder. -->
+ <div
+ v-if="
+ showResult && (hasResults || tab.document.status === 'running')
+ "
+ class="flex gap-8 px-4 py-4 overflow-x-auto"
+ >
+ <HttpTestRunnerMeta
+ :heading="t('environment.heading')"
+ :text="runEnvironmentName"
+ />
+ <HttpTestRunnerMeta
+ :heading="t('test.iterations')"
+ :text="iterationResults.length.toString()"
+ />
+ <!-- The values tick while a run is live; reserve width so the
+ rest of the meta row doesn't shift with every request. -->
+ <HttpTestRunnerMeta
+ class="min-w-24 tabular-nums"
:heading="t('test.duration')"
:text="duration ? msToHumanReadable(duration) : '...'"
/>
<HttpTestRunnerMeta
+ class="min-w-24 tabular-nums"
:heading="t('test.avg_resp')"
:text="
avgResponseTime ? msToHumanReadable(avgResponseTime) : '...'
"
/>
- </template>
- </div>
- <div class="flex items-center gap-2">
- <HoppButtonPrimary
- v-if="showResult && tab.document.status === 'running'"
- :label="t('test.stop')"
- @click="stopTests()"
- />
- <HoppButtonPrimary
- v-else
- :label="t('test.run_again')"
- @click="runAgain()"
- />
- <HoppButtonSecondary
- v-if="showResult && tab.document.status !== 'running'"
- :icon="IconPlus"
- :label="t('test.new_run')"
- filled
- outline
- @click="newRun()"
- />
+ <HttpTestRunnerMeta
+ v-if="iterationResults.length > 1"
+ class="ml-auto"
+ :heading="t('collection_runner.jump_to_iteration')"
+ >
+ <div class="flex items-center -ml-2">
+ <HoppButtonSecondary
+ v-tippy="{ theme: 'tooltip' }"
+ :title="t('collection_runner.previous_iteration')"
+ :icon="IconChevronLeft"
+ :disabled="viewedIteration <= 1"
+ class="!p-1"
+ @click="jumpTo(viewedIteration - 1)"
+ />
+ <!-- The visible face is the counter; the transparent select on
+ top of it provides direct jumps without a second control. -->
+ <span
+ class="relative flex items-center rounded focus-within:ring-1 focus-within:ring-accent"
+ >
+ <span
+ class="whitespace-nowrap px-1 text-sm font-bold tabular-nums text-secondaryDark"
+ >
+ {{ viewedIteration }} / {{ iterationResults.length }}
+ </span>
+ <select
+ v-tippy="{ theme: 'tooltip' }"
+ :title="t('collection_runner.jump_to_iteration')"
+ :aria-label="t('collection_runner.jump_to_iteration')"
+ class="absolute inset-0 cursor-pointer opacity-0"
+ :value="viewedIteration"
+ @change="onIterationSelect"
+ >
+ <option
+ v-for="{ iteration } in iterationAdapters"
+ :key="iteration"
+ :value="iteration"
+ >
+ {{
+ t("collection_runner.iteration", { count: iteration })
+ }}
+ </option>
+ </select>
+ </span>
+ <HoppButtonSecondary
+ v-tippy="{ theme: 'tooltip' }"
+ :title="t('collection_runner.next_iteration')"
+ :icon="IconChevronRight"
+ :disabled="viewedIteration >= iterationResults.length"
+ class="!p-1"
+ @click="jumpTo(viewedIteration + 1)"
+ />
+ </div>
+ </HttpTestRunnerMeta>
+ </div>
</div>
- </div>
- <HttpTestRunnerResult
- v-if="showResult"
- :tab="tab"
- :collection-adapter="collectionAdapter"
- :is-running="tab.document.status === 'running'"
- :selected-request-path="selectedRequestPath"
- @on-change-tab="showTestsType = $event as 'all' | 'passed' | 'failed'"
- @on-select-request="onSelectRequest"
- @request-path="onChangeRequestPath"
- />
+ <HttpTestRunnerResult
+ v-if="showResult"
+ :tab="tab"
+ :iteration-adapters="iterationAdapters"
+ :is-running="tab.document.status === 'running'"
+ :selected-request-path="selectedRequestPath"
+ :jump-to-iteration="jumpToIteration"
+ @on-change-tab="showTestsType = $event as 'all' | 'passed' | 'failed'"
+ @on-select-request="onSelectRequest"
+ @request-path="onChangeRequestPath"
+ @jumped="jumpToIteration = 0"
+ @visible-iteration="onVisibleIteration"
+ />
+ </div>
</template>
<template #secondary>
<div
@@ -72,6 +162,7 @@
v-else-if="selectedRequest && selectedRequest.response"
v-model:document="selectedRequest"
:show-response="tab.document.config.persistResponses"
+ :tab-id="tab.id"
/>
<HoppSmartPlaceholder
@@ -115,19 +206,24 @@
}
"
:prev-config="testRunnerConfig"
+ :prev-selection="tab.document.selectedRequestRefIds"
@hide-modal="showCollectionsRunnerModal = false"
/>
</template>
<script setup lang="ts">
import { useI18n } from "@composables/i18n"
-import { HoppCollection, HoppRESTHeader } from "@hoppscotch/data"
+import {
+ HoppCollection,
+ HoppCollectionVariable,
+ HoppRESTHeader,
+} from "@hoppscotch/data"
import { SmartTreeAdapter } from "@hoppscotch/ui"
import { useVModel } from "@vueuse/core"
import { useService } from "dioc/vue"
import { pipe } from "fp-ts/lib/function"
import * as TE from "fp-ts/TaskEither"
-import { computed, nextTick, onMounted, ref } from "vue"
+import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
import { useColorMode } from "~/composables/theming"
import { useToast } from "~/composables/toast"
import { GQLError } from "~/helpers/backend/GQLClient"
@@ -135,18 +231,26 @@ import {
getCompleteCollectionTree,
teamCollToHoppRESTColl,
} from "~/helpers/backend/helpers"
-import { HoppTestRunnerDocument } from "~/helpers/rest/document"
+import {
+ HoppTestRunnerDocument,
+ TestRunnerIterationResult,
+} from "~/helpers/rest/document"
import {
CollectionNode,
TestRunnerCollectionsAdapter,
} from "~/helpers/runner/adapter"
import { getErrorMessage } from "~/helpers/runner/collection-tree"
-import { transformInheritedCollectionVariablesToAggregateEnv } from "~/helpers/utils/inheritedCollectionVarTransformer"
+import { collectRequestIDs } from "~/helpers/runner/selection"
+import { populateValuesInInheritedCollectionVars } from "~/helpers/utils/inheritedCollectionVarTransformer"
import {
getRESTCollectionByRefId,
getRESTCollectionInheritedProps,
restCollectionStore,
} from "~/newstore/collections"
+import {
+ getCurrentEnvironment,
+ getSelectedEnvironmentType,
+} from "~/newstore/environments"
import { HoppTab } from "~/services/tab"
import { RESTTabService } from "~/services/tab/rest"
import { TeamCollectionsService } from "~/services/team-collection.service"
@@ -155,6 +259,14 @@ import {
TestRunnerService,
} from "~/services/test-runner/test-runner.service"
import IconPlus from "~icons/lucide/plus"
+import IconDownload from "~icons/lucide/download"
+import IconChevronLeft from "~icons/lucide/chevron-left"
+import IconChevronRight from "~icons/lucide/chevron-right"
+import {
+ exportRunnerResults,
+ RunnerExportScope,
+} from "~/helpers/import-export/export/runnerResults"
+import * as E from "fp-ts/Either"
const t = useI18n()
const toast = useToast()
@@ -172,8 +284,18 @@ const emit = defineEmits<{
const tabs = useService(RESTTabService)
const tab = useVModel(props, "modelValue", emit)
+// The sticky run header spans two rows of variable-height content (long
+// collection names, locale-dependent labels). Measure it at runtime so the
+// filter tabs and iteration headers below it stick at the correct offset via
+// the --upper-runner-sticky-fold CSS var, instead of a brittle hardcoded value.
+const headerEl = ref<HTMLElement | null>(null)
+const headerHeight = ref(0)
+let headerResizeObserver: ResizeObserver | null = null
+
+// RunnerResult's prop is a required string; the document field is undefined
+// until a request is selected.
const selectedRequestPath = computed(
- () => tab.value.document.selectedRequestPath
+ () => tab.value.document.selectedRequestPath ?? ""
)
const duration = computed(() => tab.value.document.testRunnerMeta.totalTime)
const avgResponseTime = computed(() =>
@@ -214,8 +336,18 @@ const collectionName = computed(() =>
: ""
)
+const runEnvironmentName = computed(
+ () => tab.value.document.environmentName ?? "Global"
+)
+
const testRunnerConfig = computed(() => tab.value.document.config)
+const iterationResults = computed(
+ () => tab.value.document.iterationResults ?? []
+)
+
+const hasResults = computed(() => iterationResults.value.length > 0)
+
const collection = computed(() => {
return tab.value.document.collection
})
@@ -236,6 +368,11 @@ const showResult = computed(() => {
const runTests = async () => {
const { collectionID, collectionType } = tab.value.document
+ tab.value.document.environmentName =
+ getSelectedEnvironmentType() === "NO_ENV_SELECTED"
+ ? "Global"
+ : getCurrentEnvironment().name
+
const isPersonalWorkspace = collectionType === "my-collections"
const collections = isPersonalWorkspace
@@ -254,6 +391,10 @@ const runTests = async () => {
// Root → Parent → Child → Request inheritance chain.
let ancestorPreRequestScripts: string[] = []
let ancestorTestScripts: string[] = []
+ // Ancestor collection variables, already resolved under their owning
+ // collections — passed separately from the run root's own variables so the
+ // runner never re-resolves a merged array under a single ID.
+ let ancestorVariables: HoppCollectionVariable[] = []
if (!isPersonalWorkspace) {
const requestAuth = tab.value.document.inheritedProperties?.auth
@@ -271,9 +412,26 @@ const runTests = async () => {
}
)
- const parentVariables = transformInheritedCollectionVariablesToAggregateEnv(
+ // Ancestors only — the run root's own level is excluded. Each level is
+ // resolved under its OWNING collection's server id (the key client-local
+ // team values are stored with); the root's own RAW variables go on
+ // `resolvedCollection.variables` for the plan walk, mirroring the
+ // personal path, so the runner never re-resolves a merged array under a
+ // single ID.
+ ancestorVariables = (
tab.value.document.inheritedProperties?.variables ?? []
)
+ .filter((group) => group.parentID !== collectionID)
+ .flatMap((group) =>
+ // `showSecret` — execution-only output; never written back to the
+ // document or persisted.
+ populateValuesInInheritedCollectionVars(
+ group.inheritedVariables,
+ group.parentID,
+ undefined,
+ true
+ )
+ )
// Team cascade includes the selected node itself in its scripts array;
// drop it here because runTestCollection will cascade that node's scripts
@@ -291,32 +449,37 @@ const runTests = async () => {
resolvedCollection = {
...collection.value,
auth: requestAuth,
- headers: requestHeaders as HoppRESTHeader[],
- variables: parentVariables,
+ // `inheritedProperties` is optional on the doc — without the fallback
+ // the runner gets `headers: undefined`.
+ headers: (requestHeaders ?? []) as HoppRESTHeader[],
+ variables: collection.value.variables ?? [],
}
} else {
const {
auth,
headers,
- variables,
+ ancestorVariables: varAncestors,
ancestorPreRequestScripts: preAncestors,
ancestorTestScripts: testAncestors,
} = collectionInheritedProps ?? {
auth: { authActive: true, authType: "none" },
headers: [],
- variables: [],
+ ancestorVariables: [],
ancestorPreRequestScripts: [],
ancestorTestScripts: [],
}
ancestorPreRequestScripts = preAncestors
ancestorTestScripts = testAncestors
+ ancestorVariables = varAncestors
resolvedCollection = {
...collection.value,
auth,
headers,
- variables,
+ // The run root keeps its own RAW variable list — the plan walk resolves
+ // it; ancestors travel separately, already resolved.
+ variables: collection.value.variables ?? [],
}
}
@@ -329,7 +492,8 @@ const runTests = async () => {
stopRef: testRunnerStopRef,
},
ancestorPreRequestScripts,
- ancestorTestScripts
+ ancestorTestScripts,
+ ancestorVariables
)
}
@@ -356,6 +520,7 @@ const runAgain = async () => {
}
tab.value.document.collection = updatedCollection
+ reconcileRequestSelection(updatedCollection)
await nextTick()
runTests()
} else {
@@ -364,6 +529,32 @@ const runAgain = async () => {
}
}
+/**
+ * Re-resolves the stored request selection against a freshly fetched tree —
+ * positional IDs shift when the collection is edited, and team `_ref_id`s
+ * regenerate on every fetch. Keeps whatever still resolves; if nothing does,
+ * falls back to running the full collection and says so.
+ */
+const reconcileRequestSelection = (collection: HoppCollection) => {
+ const stored = tab.value.document.selectedRequestRefIds
+
+ if (!Array.isArray(stored)) return
+
+ const available = new Set(collectRequestIDs(collection))
+ const stillValid = stored.filter((id) => available.has(id))
+
+ if (stillValid.length === stored.length) return
+
+ if (stillValid.length === 0) {
+ tab.value.document.selectedRequestRefIds = undefined
+ toast.info(t("collection_runner.selection_reset"))
+ return
+ }
+
+ tab.value.document.selectedRequestRefIds = stillValid
+ toast.info(t("collection_runner.selection_partially_reset"))
+}
+
const resetRunnerState = () => {
tab.value.document.testRunnerMeta = {
failedTests: 0,
@@ -377,13 +568,20 @@ const resetRunnerState = () => {
onMounted(() => {
if (tab.value.document.status === "idle") runTests()
- if (
- tab.value.document.status === "stopped" ||
- tab.value.document.status === "error"
- ) {
+
+ if (headerEl.value) {
+ headerResizeObserver = new ResizeObserver(() => {
+ if (headerEl.value) headerHeight.value = headerEl.value.offsetHeight
+ })
+ headerResizeObserver.observe(headerEl.value)
+ headerHeight.value = headerEl.value.offsetHeight
}
})
+onBeforeUnmount(() => {
+ headerResizeObserver?.disconnect()
+})
+
function calculateAverageTime(
totalTime: number,
completedRequests: number
@@ -396,18 +594,105 @@ const newRun = () => {
selectedCollectionID.value = collection.value.id
}
+// Restored iterations carry only their summary; require at least one that
+// still has rows, rather than offering an empty report.
+const canExport = computed(
+ () =>
+ showResult.value &&
+ tab.value.document.status !== "running" &&
+ iterationResults.value.some(({ resultCollection }) => resultCollection)
+)
+
+const exportResults = async (scope: RunnerExportScope) => {
+ const result = await exportRunnerResults(tab.value.document, scope)
+ if (E.isRight(result)) toast.success(t(result.right))
+ else toast.error(t(result.left))
+}
+
const testRunnerService = useService(TestRunnerService)
-const result = computed(() => {
- return tab.value.document.resultCollection
- ? [tab.value.document.resultCollection]
- : []
+const showTestsType = ref<"all" | "passed" | "failed">("all")
+
+// 0 = no pending jump; set to an iteration number to scroll its section into
+// view. Reset back to 0 after the result view consumes it so re-selecting the
+// same iteration triggers another scroll.
+const jumpToIteration = ref(0)
+
+// Keep the document's current iteration in step with the one the user
+// navigated to (the "current iteration" export scope reads it).
+// `jumpToIteration` is 1-based; `selectedIteration` is an index.
+watch(jumpToIteration, (iteration) => {
+ if (iteration > 0) tab.value.document.selectedIteration = iteration - 1
})
-const showTestsType = ref<"all" | "passed" | "failed">("all")
+/** 1-based iteration the user is currently viewing, clamped to the run. */
+const viewedIteration = computed(() => {
+ const total = iterationResults.value.length
+ const current = (tab.value.document.selectedIteration ?? 0) + 1
+ return Math.min(Math.max(current, 1), Math.max(total, 1))
+})
+
+const jumpTo = (iteration: number) => {
+ jumpToIteration.value = Math.min(
+ Math.max(iteration, 1),
+ iterationResults.value.length
+ )
+}
-const collectionAdapter: SmartTreeAdapter<CollectionNode> =
- new TestRunnerCollectionsAdapter(result, showTestsType)
+const onIterationSelect = (event: Event) => {
+ jumpTo(Number((event.target as HTMLSelectElement).value))
+}
+
+// Scroll position drives the counter, so it always names the iteration on
+// screen — not the last one jumped to.
+const onVisibleIteration = (iteration: number) => {
+ tab.value.document.selectedIteration = iteration - 1
+}
+
+type IterationAdapterEntry = {
+ iteration: number
+ /**
+ * `v-for` key in the result view. `HoppSmartTree` reads its adapter only on
+ * mount, so the key must change whenever the adapter is rebuilt to force a
+ * remount — keying by iteration number alone left the tree on a dead adapter.
+ */
+ key: string
+ adapter: SmartTreeAdapter<CollectionNode>
+}
+
+// Cached per iteration so appending one doesn't rebuild the rest and each
+// SmartTree keeps its expansion state; an entry is rebuilt only when the
+// backing iteration-result object is replaced.
+const adapterCache = new Map<
+ number,
+ { source: TestRunnerIterationResult; entry: IterationAdapterEntry }
+>()
+let adapterBuildCount = 0
+
+const iterationAdapters = computed<IterationAdapterEntry[]>(() =>
+ iterationResults.value.map((iterationResult) => {
+ const cached = adapterCache.get(iterationResult.iteration)
+ if (cached?.source === iterationResult) return cached.entry
+
+ const entry: IterationAdapterEntry = {
+ iteration: iterationResult.iteration,
+ key: `${iterationResult.iteration}-${++adapterBuildCount}`,
+ adapter: new TestRunnerCollectionsAdapter(
+ computed(() =>
+ iterationResult.resultCollection
+ ? [iterationResult.resultCollection]
+ : []
+ ),
+ showTestsType
+ ),
+ }
+ adapterCache.set(iterationResult.iteration, {
+ source: iterationResult,
+ entry,
+ })
+ return entry
+ })
+)
/**
* refetches the collection tree from the backend
diff --git a/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue b/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue
index 121346b81..6e0a7318f 100644
--- a/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue
+++ b/packages/hoppscotch-common/src/components/http/test/RunnerModal.vue
@@ -3,89 +3,285 @@
dialog
:title="t('collection_runner.run_collection')"
:full-width-body="true"
+ styles="sm:max-w-6xl xl:max-w-7xl 2xl:max-w-[80vw]"
@close="closeModal"
>
<template #body>
<HoppSmartTabs v-model="activeTab">
<HoppSmartTab id="gui" :label="t('collection_runner.ui')">
<div
- class="flex-shrink-0 w-full h-full p-4 overflow-auto overflow-x-auto bg-primary"
+ class="flex flex-col w-full bg-primary lg:flex-row lg:h-[calc(60vh_-_2.0625rem)] lg:min-h-0"
>
- <section>
- <h4 class="font-semibold text-secondaryDark">
- {{ t("collection_runner.run_config") }}
- </h4>
- <div class="mt-4">
- <!-- TODO: fix input component types. so that it accepts number -->
- <HoppSmartInput
- v-model="config.delay as any"
- type="number"
- :label="t('collection_runner.delay')"
- class="!rounded-r-none !border-r-0"
- :class="{ 'border-red-500': config.delay < 0 }"
- input-styles="floating-input !rounded-r-none !border-r-0"
- >
- <template #button>
- <span
- class="px-4 py-2 font-semibold border rounded-r bg-primaryLight border-divider text-secondaryLight"
- >
- ms
- </span>
- </template>
- </HoppSmartInput>
- <p v-if="config.delay < 0" class="text-xs text-red-500 mt-1">
- {{ t("collection_runner.negative_delay") }}
- </p>
- </div>
- </section>
-
- <section class="mt-6">
- <span class="text-xs text-secondaryLight">
- {{ t("collection_runner.advanced_settings") }}
- </span>
-
- <div class="flex flex-col gap-4 mt-4 items-start">
- <HoppSmartCheckbox
- class="pr-2"
- :on="config.stopOnError"
- @change="config.stopOnError = !config.stopOnError"
- >
- <span>
- {{ t("collection_runner.stop_on_error") }}
- </span>
- </HoppSmartCheckbox>
+ <div
+ class="flex-1 min-w-0 p-4 overflow-y-auto lg:border-r border-divider"
+ >
+ <section>
+ <h4 class="font-semibold text-secondaryDark">
+ {{ t("collection_runner.run_config") }}
+ </h4>
+ <div class="mt-4">
+ <HoppSmartInput
+ v-model="config.iterations as any"
+ type="number"
+ :label="t('collection_runner.iterations')"
+ :disabled="!!config.dataset"
+ class="!rounded-r-none !border-r-0"
+ :class="{ 'border-red-500': config.iterations < 1 }"
+ input-styles="floating-input !rounded-r-none !border-r-0"
+ >
+ <template #button>
+ <span
+ class="px-4 py-2 font-semibold border rounded-r bg-primaryLight border-divider text-secondaryLight"
+ >
+ {{
+ Number(config.iterations) === 1
+ ? t("collection_runner.time")
+ : t("collection_runner.times")
+ }}
+ </span>
+ </template>
+ </HoppSmartInput>
+ <p
+ v-if="config.iterations < 1"
+ class="text-xs text-red-500 mt-1"
+ >
+ {{ t("collection_runner.invalid_iterations") }}
+ </p>
+ <p
+ v-else-if="config.dataset"
+ class="text-xs text-secondaryLight mt-1"
+ >
+ {{ t("collection_runner.iterations_locked_to_dataset") }}
+ </p>
+ </div>
+ </section>
+
+ <section class="mt-6">
+ <h4 class="font-semibold text-secondaryDark">
+ {{ t("collection_runner.data_feed") }}
+ </h4>
+ <template v-if="config.dataset">
+ <div
+ class="mt-4 p-4 rounded border border-divider bg-primaryLight"
+ >
+ <div class="flex items-center gap-2">
+ <span class="font-semibold text-secondaryDark">
+ {{ config.dataset.fileName }}
+ </span>
+ <span class="text-secondaryLight">•</span>
+ <span class="font-semibold text-secondaryLight uppercase">
+ {{ config.dataset.type }}
+ </span>
+ <span class="text-secondaryLight">•</span>
+ <span class="text-accent">
+ {{
+ t(
+ config.dataset.rows.length === 1
+ ? "collection_runner.dataset_row"
+ : "collection_runner.dataset_rows",
+ { count: config.dataset.rows.length }
+ )
+ }}
+ </span>
+ <span class="flex-1"></span>
+ <HoppButtonSecondary
+ v-tippy="{ theme: 'tooltip' }"
+ :title="t('collection_runner.data_preview')"
+ :icon="IconEye"
+ outline
+ @click="showDataPreview = true"
+ />
+ <HoppButtonSecondary
+ v-tippy="{ theme: 'tooltip' }"
+ :title="t('collection_runner.remove_file')"
+ :icon="IconTrash"
+ outline
+ @click="removeDataset"
+ />
+ </div>
+ <p class="mt-2 text-accent">
+ {{
+ t("collection_runner.dataset_iterations_info", {
+ rows: config.dataset.rows.length,
+ total: config.iterations,
+ })
+ }}
+ </p>
+ </div>
+ </template>
+ <template v-else>
+ <p class="mt-1 text-secondaryLight">
+ {{ t("collection_runner.data_feed_help") }}
+ </p>
+ <div
+ class="flex flex-col mt-3 border border-dashed rounded border-dividerDark"
+ >
+ <input
+ ref="dataFileInput"
+ type="file"
+ class="p-4 cursor-pointer transition file:transition file:cursor-pointer text-secondary hover:text-secondaryDark file:mr-2 file:py-2 file:px-4 file:rounded file:border-0 file:text-secondary hover:file:text-secondaryDark file:bg-primaryLight hover:file:bg-primaryDark"
+ accept=".csv,.json,text/csv,application/json"
+ :aria-label="t('collection_runner.select_data_file')"
+ @change="handleDatasetFile"
+ />
+ </div>
+ </template>
+ </section>
+
+ <section class="mt-6">
+ <div>
+ <!-- TODO: fix input component types. so that it accepts number -->
+ <HoppSmartInput
+ v-model="config.delay as any"
+ type="number"
+ :label="t('collection_runner.delay')"
+ class="!rounded-r-none !border-r-0"
+ :class="{ 'border-red-500': config.delay < 0 }"
+ input-styles="floating-input !rounded-r-none !border-r-0"
+ >
+ <template #button>
+ <span
+ class="px-4 py-2 font-semibold border rounded-r bg-primaryLight border-divider text-secondaryLight"
+ >
+ ms
+ </span>
+ </template>
+ </HoppSmartInput>
+ <p v-if="config.delay < 0" class="text-xs text-red-500 mt-1">
+ {{ t("collection_runner.negative_delay") }}
+ </p>
+ </div>
+ </section>
+
+ <section class="mt-6">
+ <span class="text-xs text-secondaryLight">
+ {{ t("collection_runner.advanced_settings") }}
+ </span>
- <HoppSmartCheckbox
- class="pr-2"
- :on="config.persistResponses"
- @change="config.persistResponses = !config.persistResponses"
- >
- <span>
- {{ t("collection_runner.persist_responses") }}
- </span>
- </HoppSmartCheckbox>
+ <div class="flex flex-col gap-4 mt-4 items-start">
+ <HoppSmartCheckbox
+ class="pr-2"
+ :on="config.stopOnError"
+ @change="config.stopOnError = !config.stopOnError"
+ >
+ <span>
+ {{ t("collection_runner.stop_on_error") }}
+ </span>
+ </HoppSmartCheckbox>
+
+ <HoppSmartCheckbox
+ class="pr-2"
+ :on="config.persistResponses"
+ @change="config.persistResponses = !config.persistResponses"
+ >
+ <span>
+ {{ t("collection_runner.persist_responses") }}
+ </span>
+ </HoppSmartCheckbox>
+
+ <HoppSmartCheckbox
+ class="pr-2"
+ :on="config.keepVariableValues"
+ @change="
+ config.keepVariableValues = !config.keepVariableValues
+ "
+ >
+ <span>
+ {{ t("collection_runner.keep_variable_values") }}
+ </span>
+ <HoppButtonSecondary
+ v-tippy="{ theme: 'tooltip' }"
+ class="!py-0 pl-2"
+ to="https://docs.hoppscotch.io/documentation/features/inspections"
+ blank
+ :title="t('app.wiki')"
+ :icon="IconHelpCircle"
+ />
+ </HoppSmartCheckbox>
+ </div>
+ </section>
+ </div>
- <HoppSmartCheckbox
- class="pr-2"
- :on="config.keepVariableValues"
- @change="
- config.keepVariableValues = !config.keepVariableValues
- "
- >
- <span>
- {{ t("collection_runner.keep_variable_values") }}
+ <div class="flex flex-col flex-1 min-w-0 min-h-0 p-4">
+ <div class="flex items-center justify-between flex-shrink-0">
+ <h4 class="font-semibold text-secondaryDark">
+ {{ t("collection_runner.run_sequence") }}
+ </h4>
+ <div v-if="collectionTree" class="flex items-center gap-2">
+ <span class="text-xs text-secondaryLight">
+ {{
+ t("collection_runner.selected_requests_count", {
+ selected: selectedRequestIDs.size,
+ total: allRequestIDs.length,
+ })
+ }}
</span>
<HoppButtonSecondary
- v-tippy="{ theme: 'tooltip' }"
- class="!py-0 pl-2"
- to="https://docs.hoppscotch.io/documentation/features/inspections"
- blank
- :title="t('app.wiki')"
- :icon="IconHelpCircle"
+ :label="
+ allSelected
+ ? t('collection_runner.deselect_all')
+ : t('collection_runner.select_all')
+ "
+ outline
+ filled
+ @click="toggleSelectAll"
/>
- </HoppSmartCheckbox>
+ <HoppButtonSecondary
+ :label="t('collection_runner.reset_run_order')"
+ :disabled="requestOrder.length === 0"
+ outline
+ filled
+ @click="resetRunOrder"
+ />
+ </div>
</div>
- </section>
+
+ <div
+ v-if="loadingCollection"
+ class="flex justify-center mt-4 py-4"
+ >
+ <HoppSmartSpinner />
+ </div>
+ <div
+ v-else-if="collectionLoadFailed"
+ class="flex items-center justify-between gap-4 mt-4 p-4 rounded border border-divider bg-primaryLight"
+ >
+ <span class="text-secondaryLight">
+ {{ t("collection_runner.collection_load_failed") }}
+ </span>
+ <HoppButtonSecondary
+ :label="t('action.retry')"
+ outline
+ filled
+ @click="loadCollectionTree"
+ />
+ </div>
+ <template v-else-if="collectionTree">
+ <HoppSmartInput
+ v-model="requestFilter"
+ class="mt-4 flex-shrink-0"
+ :placeholder="t('collection_runner.filter_requests')"
+ />
+ <div
+ class="flex-1 min-h-0 mt-2 max-h-64 lg:max-h-none overflow-auto rounded border border-divider bg-primaryLight px-3 py-2"
+ >
+ <HttpTestRunnerRequestSelector
+ :collection="collectionTree"
+ :selected-i-ds="selectedRequestIDs"
+ :order="requestOrder"
+ :filter="requestFilter"
+ @toggle="toggleRequestSelection"
+ @reorder="requestOrder = $event"
+ />
+ </div>
+ </template>
+ <p
+ v-if="collectionTree && selectedRequestIDs.size === 0"
+ class="flex-shrink-0 text-xs text-red-500 mt-1"
+ >
+ {{ t("collection_runner.no_requests_selected") }}
+ </p>
+ </div>
</div>
</HoppSmartTab>
<HoppSmartTab id="cli" :label="t('collection_runner.cli')">
@@ -145,7 +341,12 @@
<HoppButtonPrimary
v-if="activeTab === 'gui'"
:label="`${t('test.run')}`"
- :disabled="config.delay < 0"
+ :disabled="
+ config.delay < 0 ||
+ config.iterations < 1 ||
+ !collectionTree ||
+ selectedRequestIDs.size === 0
+ "
:loading="loadingCollection"
:icon="IconPlay"
outline
@@ -167,6 +368,94 @@
</div>
</template>
</HoppSmartModal>
+
+ <HoppSmartModal
+ v-if="showDataPreview && config.dataset"
+ dialog
+ :title="t('collection_runner.data_preview')"
+ @close="showDataPreview = false"
+ >
+ <template #body>
+ <div class="p-4">
+ <div class="flex items-center gap-2 mb-4">
+ <span class="font-semibold text-secondaryDark">
+ {{ config.dataset.fileName }}
+ </span>
+ <span class="text-secondaryLight">•</span>
+ <span class="font-semibold text-secondaryLight uppercase">
+ {{ config.dataset.type }}
+ </span>
+ <span class="text-secondaryLight">•</span>
+ <span class="text-accent">
+ {{
+ t(
+ config.dataset.rows.length === 1
+ ? "collection_runner.dataset_row"
+ : "collection_runner.dataset_rows",
+ { count: config.dataset.rows.length }
+ )
+ }}
+ </span>
+ </div>
+ <div class="overflow-auto rounded border border-divider">
+ <table class="w-full text-left border-collapse">
+ <thead class="bg-primaryLight">
+ <tr>
+ <th
+ class="px-3 py-2 text-tiny font-semibold text-secondaryLight border-b border-divider"
+ >
+ #
+ </th>
+ <th
+ v-for="column in datasetColumns"
+ :key="column"
+ class="px-3 py-2 text-tiny font-semibold text-secondaryDark border-b border-divider whitespace-nowrap"
+ >
+ {{ column }}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="(row, rowIndex) in datasetPreviewRows"
+ :key="rowIndex"
+ class="border-b border-dividerLight last:border-0"
+ >
+ <td class="px-3 py-2 text-tiny text-secondaryLight">
+ {{ rowIndex + 1 }}
+ </td>
+ <td
+ v-for="column in datasetColumns"
+ :key="column"
+ class="px-3 py-2 text-secondaryDark align-top"
+ >
+ {{ row[column] ?? "" }}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <p
+ v-if="datasetPreviewTruncated"
+ class="mt-2 text-tiny text-secondaryLight"
+ >
+ {{
+ t("collection_runner.dataset_preview_truncated", {
+ count: DATASET_PREVIEW_ROW_CAP,
+ })
+ }}
+ </p>
+ </div>
+ </template>
+ <template #footer>
+ <HoppButtonSecondary
+ :label="`${t('action.close')}`"
+ outline
+ filled
+ @click="showDataPreview = false"
+ />
+ </template>
+ </HoppSmartModal>
</template>
<script setup lang="ts">
@@ -178,12 +467,16 @@ import { HoppCollection } from "@hoppscotch/data"
import { useService } from "dioc/vue"
import { useToast } from "~/composables/toast"
import { TestRunnerConfig } from "~/helpers/rest/document"
+import { parseDatasetFile } from "~/helpers/runner/dataset"
+import { collectRequestIDs } from "~/helpers/runner/selection"
import { copyToClipboard } from "~/helpers/utils/clipboard"
import { RESTTabService } from "~/services/tab/rest"
import IconCheck from "~icons/lucide/check"
import IconCopy from "~icons/lucide/copy"
+import IconEye from "~icons/lucide/eye"
import IconHelpCircle from "~icons/lucide/help-circle"
import IconPlay from "~icons/lucide/play"
+import IconTrash from "~icons/lucide/trash"
import { CurrentEnv } from "./Env.vue"
import { pipe } from "fp-ts/lib/function"
import {
@@ -191,6 +484,7 @@ import {
teamCollToHoppRESTColl,
} from "~/helpers/backend/helpers"
import * as TE from "fp-ts/TaskEither"
+import * as E from "fp-ts/Either"
import { GQLError } from "~/helpers/backend/GQLClient"
import { cloneDeep } from "lodash-es"
import { getErrorMessage } from "~/helpers/runner/collection-tree"
@@ -220,6 +514,11 @@ const props = defineProps<{
sameTab?: boolean
collectionRunnerData: CollectionRunnerData
prevConfig?: Partial<TestRunnerConfig>
+ /**
+ * The previous run's selection, in run order — carried over so a new run
+ * keeps the sequence the user arranged.
+ */
+ prevSelection?: string[]
}>()
const emit = defineEmits<{
@@ -231,6 +530,55 @@ const activeTab = ref<"gui" | "cli">("gui")
const environmentID = ref("")
const currentEnv = ref<CurrentEnv>(null)
+const showDataPreview = ref(false)
+const dataFileInput = ref<HTMLInputElement | null>(null)
+
+const collectionTree = ref<HoppCollection | null>(null)
+const selectedRequestIDs = ref<Set<string>>(new Set())
+const requestFilter = ref("")
+
+// Explicit run order as selection IDs. Empty means "natural collection
+// order", which is also what Reset restores.
+const requestOrder = ref<string[]>([])
+
+const resetRunOrder = () => {
+ requestOrder.value = []
+}
+
+const allRequestIDs = computed(() =>
+ collectionTree.value ? collectRequestIDs(collectionTree.value) : []
+)
+
+const allSelected = computed(
+ () =>
+ allRequestIDs.value.length > 0 &&
+ selectedRequestIDs.value.size === allRequestIDs.value.length
+)
+
+// Same rule the selector displays by: the user's explicit order first, then
+// anything it doesn't mention in natural order.
+const orderedRequestIDs = computed(() => {
+ if (requestOrder.value.length === 0) return allRequestIDs.value
+
+ const available = new Set(allRequestIDs.value)
+ const ordered = requestOrder.value.filter((id) => available.has(id))
+ const seen = new Set(ordered)
+
+ return [...ordered, ...allRequestIDs.value.filter((id) => !seen.has(id))]
+})
+
+// Receives a whole subtree at once, so a folder toggle rebuilds the Set once.
+const toggleRequestSelection = (ids: string[], select: boolean) => {
+ const next = new Set(selectedRequestIDs.value)
+ ids.forEach((id) => (select ? next.add(id) : next.delete(id)))
+ selectedRequestIDs.value = next
+}
+
+const toggleSelectAll = () => {
+ selectedRequestIDs.value = allSelected.value
+ ? new Set()
+ : new Set(allRequestIDs.value)
+}
const runnerLink = computed(() => {
return activeTab.value === "gui"
@@ -253,37 +601,208 @@ const config = ref<TestRunnerConfig>({
keepVariableValues: true,
})
-onMounted(() => {
+// Cap the data-preview so a large dataset doesn't stringify thousands of rows
+// into the DOM on every render. Computed once, and only while the preview is open.
+const DATASET_PREVIEW_ROW_CAP = 50
+
+const datasetPreviewRows = computed(() =>
+ (config.value.dataset?.rows ?? []).slice(0, DATASET_PREVIEW_ROW_CAP)
+)
+
+// Union of keys across the previewed rows — JSON rows need not be uniform.
+const datasetColumns = computed(() => {
+ const columns = new Set<string>()
+ datasetPreviewRows.value.forEach((row) =>
+ Object.keys(row).forEach((key) => columns.add(key))
+ )
+ return [...columns]
+})
+
+const datasetPreviewTruncated = computed(
+ () => (config.value.dataset?.rows.length ?? 0) > DATASET_PREVIEW_ROW_CAP
+)
+
+// The tree fetch can fail (a network call for team collections) and the run
+// controls key off `collectionTree` — a failure must stay recoverable.
+const collectionLoadFailed = ref(false)
+
+const loadCollectionTree = async () => {
+ collectionLoadFailed.value = false
+
+ const tree = await getCollectionTree(
+ props.collectionRunnerData.type,
+ props.collectionRunnerData.collectionID
+ )
+
+ if (!tree) {
+ collectionLoadFailed.value = true
+ return
+ }
+
+ collectionTree.value = tree as HoppCollection
+
+ const available = collectRequestIDs(collectionTree.value)
+
+ // Carry over the previous run's selection, dropping anything that no
+ // longer exists in the tree; everything selected otherwise.
+ const carriedOver = (props.prevSelection ?? []).filter((id) =>
+ available.includes(id)
+ )
+
+ if (carriedOver.length > 0) {
+ selectedRequestIDs.value = new Set(carriedOver)
+
+ // Only install an explicit order when the previous run actually had one:
+ // a selection in natural order is just "which requests", and treating it
+ // as an ordering would pin re-checked requests to the end of the run.
+ const naturalPosition = new Map(available.map((id, index) => [id, index]))
+ const isNaturalOrder = carriedOver.every(
+ (id, index) =>
+ index === 0 ||
+ naturalPosition.get(id)! > naturalPosition.get(carriedOver[index - 1])!
+ )
+
+ requestOrder.value = isNaturalOrder ? [] : carriedOver
+ return
+ }
+
+ selectedRequestIDs.value = new Set(available)
+ requestOrder.value = []
+}
+
+onMounted(async () => {
if (props.prevConfig) {
config.value = { ...config.value, ...props.prevConfig }
}
+
+ await loadCollectionTree()
})
+const resetFileInputs = () => {
+ if (dataFileInput.value) dataFileInput.value.value = ""
+}
+
+const removeDataset = () => {
+ config.value.dataset = undefined
+ config.value.iterations = 1
+ showDataPreview.value = false
+ resetFileInputs()
+}
+
+// The parsed rows are stored on the (persisted) tab document, which shares
+// the ~5MB localStorage quota with every other REST tab — and CSV rows
+// expand when re-serialized as keyed JSON objects. 2MB (roughly 20-40k
+// rows, i.e. iterations) keeps the worst case comfortably inside the quota.
+const DATA_FILE_SIZE_LIMIT_MB = 2
+
+const handleDatasetFile = async (event: Event) => {
+ const input = event.target as HTMLInputElement
+ const file = input.files?.[0]
+
+ if (!file) return
+
+ if (file.size > DATA_FILE_SIZE_LIMIT_MB * 1024 * 1024) {
+ toast.error(
+ t("collection_runner.data_file_size_limit_exceeded", {
+ sizeLimit: DATA_FILE_SIZE_LIMIT_MB,
+ })
+ )
+ resetFileInputs()
+ return
+ }
+
+ const result = await parseDatasetFile(file)
+
+ if (E.isLeft(result)) {
+ toast.error(`${t("collection_runner.invalid_data_file")}: ${result.left}`)
+ resetFileInputs()
+ return
+ }
+
+ if (result.right.rows.length === 0) {
+ toast.error(t("collection_runner.empty_data_file"))
+ resetFileInputs()
+ return
+ }
+
+ // What persists is the PARSED rows, and a wide CSV balloons once column
+ // names repeat per row — so the raw-file gate above isn't enough; gate the
+ // serialized size the tab state will actually carry.
+ if (
+ JSON.stringify(result.right.rows).length >
+ DATA_FILE_SIZE_LIMIT_MB * 1024 * 1024
+ ) {
+ toast.error(
+ t("collection_runner.data_file_size_limit_exceeded", {
+ sizeLimit: DATA_FILE_SIZE_LIMIT_MB,
+ })
+ )
+ resetFileInputs()
+ return
+ }
+
+ config.value.dataset = result.right
+ config.value.iterations = result.right.rows.length
+ resetFileInputs()
+}
+
const runTests = async () => {
- const collectionTree = await getCollectionTree(
- props.collectionRunnerData.type,
- props.collectionRunnerData.collectionID
- )
+ const iterations = Number(config.value.iterations)
+ const delay = Number(config.value.delay)
- if (!collectionTree) {
+ if (!Number.isFinite(iterations) || iterations < 1) {
+ toast.error(t("collection_runner.invalid_iterations"))
+ return
+ }
+
+ if (!Number.isFinite(delay) || delay < 0) {
+ toast.error(t("collection_runner.negative_delay"))
+ return
+ }
+
+ const tree =
+ collectionTree.value ??
+ ((await getCollectionTree(
+ props.collectionRunnerData.type,
+ props.collectionRunnerData.collectionID
+ )) as HoppCollection | null)
+
+ if (!tree) {
toast.error(t("collection_runner.collection_not_found"))
return
}
- if (checkIfCollectionIsEmpty(collectionTree)) {
+ if (checkIfCollectionIsEmpty(tree)) {
toast.error(t("collection_runner.empty_collection"))
return
}
+ if (selectedRequestIDs.value.size === 0) {
+ toast.error(t("collection_runner.no_requests_selected"))
+ return
+ }
+
+ // `undefined` means "everything, in collection order"; otherwise send the
+ // explicit run order, which the runner executes in exactly this order.
+ const selectedRequestRefIds =
+ allSelected.value && requestOrder.value.length === 0
+ ? undefined
+ : orderedRequestIDs.value.filter((id) => selectedRequestIDs.value.has(id))
+
let tabIdToClose = null
if (props.sameTab) tabIdToClose = cloneDeep(tabs.currentTabID.value)
tabs.createNewTab({
type: "test-runner",
collectionType: props.collectionRunnerData.type,
collectionID: props.collectionRunnerData.collectionID,
- collection: collectionTree as HoppCollection,
+ collection: tree,
isDirty: false,
- config: config.value,
+ config: {
+ ...config.value,
+ iterations,
+ delay,
+ },
+ selectedRequestRefIds,
status: "idle",
request: null,
testRunnerMeta: {
diff --git a/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vue b/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vue
new file mode 100644
index 000000000..b86a35807
--- /dev/null
+++ b/packages/hoppscotch-common/src/components/http/test/RunnerRequestSelector.vue
@@ -0,0 +1,187 @@
+<template>
+ <draggable
+ v-model="orderedEntries"
+ item-key="id"
+ animation="250"
+ handle=".draggable-handle"
+ ghost-class="cursor-move"
+ chosen-class="bg-primaryLight"
+ drag-class="cursor-grabbing"
+ class="flex flex-col"
+ :disabled="filterActive"
+ >
+ <template #item="{ element: entry }">
+ <label
+ class="group flex items-center gap-2 py-1.5 cursor-pointer text-secondaryDark"
+ >
+ <!-- Slot the request executes in; deselected rows hold none. -->
+ <span
+ class="w-5 flex-shrink-0 text-right text-tiny text-secondaryLight tabular-nums"
+ >
+ {{ runPositions.get(entry.id) ?? "–" }}
+ </span>
+
+ <!-- Not a <button>: a button here would be the label's first labelable
+ descendant, stealing row clicks from the checkbox. -->
+ <span
+ class="draggable-handle flex flex-shrink-0 cursor-grab items-center text-secondaryLight opacity-0 group-hover:opacity-100"
+ :class="{ invisible: filterActive }"
+ @click.prevent
+ >
+ <component :is="IconGripVertical" class="svg-icons" />
+ </span>
+
+ <HoppSmartCheckbox
+ :on="entry.selected"
+ @change="emit('toggle', [entry.id], !entry.selected)"
+ />
+
+ <!-- Folders collapse to icons; the full path is on the tooltip. -->
+ <span
+ v-if="entry.path.length"
+ v-tippy="{ theme: 'tooltip' }"
+ :title="entry.path.join(' / ')"
+ class="flex items-center flex-shrink-0 text-secondaryLight"
+ >
+ <template v-for="(folder, depth) in entry.path" :key="depth">
+ <component :is="IconFolder" class="svg-icons" />
+ <component :is="IconChevronRight" class="svg-icons opacity-60" />
+ </template>
+ </span>
+
+ <span
+ class="font-bold text-tiny flex-shrink-0"
+ :style="{ color: entry.methodColor }"
+ >
+ {{ entry.method }}
+ </span>
+ <span class="truncate">{{ entry.name }}</span>
+ </label>
+ </template>
+ </draggable>
+
+ <p v-if="orderedEntries.length === 0" class="py-2 text-secondaryLight">
+ {{ t("collection_runner.no_requests_match_filter") }}
+ </p>
+</template>
+
+<script setup lang="ts">
+import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"
+import { computed } from "vue"
+import draggable from "vuedraggable-es"
+import { useI18n } from "~/composables/i18n"
+import { getMethodLabelColorClassOf } from "~/helpers/rest/labelColoring"
+import { getRequestSelectionID } from "~/helpers/runner/selection"
+import IconChevronRight from "~icons/lucide/chevron-right"
+import IconFolder from "~icons/lucide/folder"
+import IconGripVertical from "~icons/lucide/grip-vertical"
+
+const t = useI18n()
+
+const props = withDefaults(
+ defineProps<{
+ collection: HoppCollection
+ selectedIDs: Set<string>
+ /** Run order, as selection IDs. Empty means "natural collection order". */
+ order: string[]
+ filter?: string
+ }>(),
+ { filter: "" }
+)
+
+const emit = defineEmits<{
+ (e: "toggle", ids: string[], select: boolean): void
+ (e: "reorder", order: string[]): void
+}>()
+
+type Entry = {
+ id: string
+ name: string
+ method: string
+ methodColor: string
+ /** Folder names from the collection root down to the request's parent. */
+ path: string[]
+ selected: boolean
+}
+
+const matches = (haystack: string, filter: string) =>
+ filter.trim().length === 0 ||
+ haystack.toLowerCase().includes(filter.trim().toLowerCase())
+
+const filterActive = computed(() => props.filter.trim().length > 0)
+
+/**
+ * Flattens the tree in the runner's walk order — folders (depth-first) before
+ * a node's own requests. Must agree with `collectRequestIDs` and
+ * `planCollection`.
+ */
+const flatten = (
+ collection: HoppCollection,
+ parentPath: number[],
+ folderNames: string[]
+): Entry[] => [
+ ...collection.folders.flatMap((folder, index) =>
+ flatten(folder, [...parentPath, index], [...folderNames, folder.name])
+ ),
+ ...collection.requests.map((request, index): Entry => {
+ const path = [...parentPath, index]
+ return {
+ id: getRequestSelectionID(request as HoppRESTRequest, path),
+ name: request.name,
+ method: request.method,
+ methodColor: getMethodLabelColorClassOf(request.method),
+ path: folderNames,
+ selected: props.selectedIDs.has(
+ getRequestSelectionID(request as HoppRESTRequest, path)
+ ),
+ }
+ }),
+]
+
+const naturalEntries = computed(() => flatten(props.collection, [], []))
+
+/**
+ * The user's explicit order first, then anything it doesn't mention in
+ * natural order — a request added after an ordering still shows up.
+ */
+const sortedEntries = computed(() => {
+ const byID = new Map(naturalEntries.value.map((entry) => [entry.id, entry]))
+ const ordered = props.order
+ .map((id) => byID.get(id))
+ .filter((entry): entry is Entry => entry !== undefined)
+
+ const seen = new Set(ordered.map((entry) => entry.id))
+ return [...ordered, ...naturalEntries.value.filter((e) => !seen.has(e.id))]
+})
+
+// Run slot per selected entry, counted over the full (unfiltered) sorted
+// list so "1" is always the first request that will actually run.
+const runPositions = computed(() => {
+ const positions = new Map<string, number>()
+ let slot = 0
+ for (const entry of sortedEntries.value) {
+ if (entry.selected) positions.set(entry.id, ++slot)
+ }
+ return positions
+})
+
+const orderedEntries = computed<Entry[]>({
+ get: () =>
+ sortedEntries.value.filter((entry) =>
+ matches(
+ `${entry.method} ${entry.name} ${entry.path.join(" ")}`,
+ props.filter
+ )
+ ),
+ // Dragging reports the filtered list; splice it back into the full order
+ // so hidden entries aren't dropped.
+ set: (dragged) => {
+ const visible = new Set(dragged.map((entry) => entry.id))
+ const queue = dragged.map((entry) => entry.id)
+ const next = sortedEntries.value.map((entry) =>
+ visible.has(entry.id) ? queue.shift()! : entry.id
+ )
+ emit("reorder", next)
+ },
+})
+</script>
diff --git a/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue b/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue
index 00e2448f2..f1c4f2651 100644
--- a/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue
+++ b/packages/hoppscotch-common/src/components/http/test/RunnerResult.vue
@@ -1,94 +1,118 @@
<template>
- <div class="sticky top-upperRunnerStickyFold z-10">
- <HoppSmartTabs
- v-model="selectedTestTab"
- styles="overflow-x-auto flex-shrink-0 bg-primary"
- render-inactive-tabs
- @update:model-value="emit('onChangeTab', $event)"
- >
- <HoppSmartTab
- :id="'all'"
- :label="`${t('tab.all_tests')}`"
- :info="tab.document.testRunnerMeta.totalTests.toString()"
- >
- </HoppSmartTab>
- <HoppSmartTab
- :id="'passed'"
- :label="`${t('tab.passed')}`"
- :info="tab.document.testRunnerMeta.passedTests.toString()"
+ <!-- Run results aren't persisted; a restored tab has nothing to show. -->
+ <template v-if="hasResults || isRunning">
+ <div ref="filterTabsEl" class="sticky top-upperRunnerStickyFold z-10">
+ <HoppSmartTabs
+ v-model="selectedTestTab"
+ styles="overflow-x-auto flex-shrink-0 bg-primary"
+ render-inactive-tabs
+ @update:model-value="emit('onChangeTab', $event)"
>
- </HoppSmartTab>
- <HoppSmartTab
- :id="'failed'"
- :label="`${t('tab.failed')}`"
- :info="tab.document.testRunnerMeta.failedTests.toString()"
+ <HoppSmartTab
+ :id="'all'"
+ :label="`${t('tab.all_tests')}`"
+ :info="tab.document.testRunnerMeta.totalTests.toString()"
+ >
+ </HoppSmartTab>
+ <HoppSmartTab
+ :id="'passed'"
+ :label="`${t('tab.passed')}`"
+ :info="tab.document.testRunnerMeta.passedTests.toString()"
+ >
+ </HoppSmartTab>
+ <HoppSmartTab
+ :id="'failed'"
+ :label="`${t('tab.failed')}`"
+ :info="tab.document.testRunnerMeta.failedTests.toString()"
+ >
+ </HoppSmartTab>
+ </HoppSmartTabs>
+ </div>
+
+ <div
+ class="flex flex-col justify-center test-runner pr-2"
+ :class="{
+ hidden:
+ (selectedTestTab === 'passed' &&
+ tab.document.testRunnerMeta.passedTests === 0) ||
+ (selectedTestTab === 'failed' &&
+ tab.document.testRunnerMeta.failedTests === 0),
+ }"
+ :style="{ '--runner-filter-tabs-height': `${filterTabsHeight}px` }"
+ >
+ <div
+ v-for="{ iteration, key, adapter } in iterationAdapters"
+ :key="key"
+ :ref="(el) => setIterationRef(iteration, el)"
+ class="iteration-group"
>
- </HoppSmartTab>
- </HoppSmartTabs>
- </div>
-
- <div
- class="flex flex-col justify-center test-runner pr-2"
- :class="{
- hidden:
+ <!-- Pins below the measured filter-tabs row. Sticky never lets the
+ element rise above its `top` line, so an offset larger than the
+ real tabs height parks the header over the first row's top edge. -->
+ <div
+ class="sticky top-[calc(var(--upper-runner-sticky-fold,0px)_+_var(--runner-filter-tabs-height,3rem))] z-[9] px-4 py-2 bg-primaryLight border-b border-divider font-semibold text-secondaryDark"
+ >
+ {{ t("collection_runner.iteration", { count: iteration }) }}
+ </div>
+ <HoppSmartTree :expand-all="true" :adapter="adapter">
+ <template #content="{ node }">
+ <HttpTestResultFolder
+ v-if="
+ node.data.type === 'folders' &&
+ node.data.data.data.requests.length > 0
+ "
+ :id="node.id"
+ :parent-i-d="node.data.data.parentIndex"
+ :data="node.data.data.data"
+ :is-open="true"
+ :is-last-item="node.data.isLastItem"
+ folder-type="folder"
+ />
+
+ <HttpTestResultRequest
+ v-if="node.data.type === 'requests' && !node.data.hidden"
+ class="runner-request"
+ :show-test-type="selectedTestTab"
+ :request="node.data.data.data"
+ :request-i-d="node.id"
+ :parent-i-d="node.data.data.parentIndex"
+ :is-selected="`${iteration}::${node.id}` === selectedRequestPath"
+ :is-last-item="node.data.isLastItem"
+ @select-request="
+ selectRequest(node.data.data.data, `${iteration}::${node.id}`)
+ "
+ />
+ </template>
+ </HoppSmartTree>
+ </div>
+ </div>
+
+ <HoppSmartPlaceholder
+ v-if="
(selectedTestTab === 'passed' &&
tab.document.testRunnerMeta.passedTests === 0) ||
(selectedTestTab === 'failed' &&
- tab.document.testRunnerMeta.failedTests === 0),
- }"
- >
- <HoppSmartTree :expand-all="true" :adapter="collectionAdapter">
- <template #content="{ node }">
- <HttpTestResultFolder
- v-if="
- node.data.type === 'folders' &&
- node.data.data.data.requests.length > 0
- "
- :id="node.id"
- :parent-i-d="node.data.data.parentIndex"
- :data="node.data.data.data"
- :is-open="true"
- :is-selected="node.data.isSelected"
- :is-last-item="node.data.isLastItem"
- :show-selection="showCheckbox"
- folder-type="folder"
- />
-
- <HttpTestResultRequest
- v-if="node.data.type === 'requests' && !node.data.hidden"
- class="runner-request"
- :show-test-type="selectedTestTab"
- :request="node.data.data.data"
- :request-i-d="node.id"
- :parent-i-d="node.data.data.parentIndex"
- :is-selected="node.id === selectedRequestPath"
- :show-selection="showCheckbox"
- :is-last-item="node.data.isLastItem"
- @select-request="selectRequest(node.data.data.data, node.id)"
- />
- </template>
- </HoppSmartTree>
- </div>
+ tab.document.testRunnerMeta.failedTests === 0)
+ "
+ :src="`/images/states/${colorMode.value}/pack.svg`"
+ :text="
+ selectedTestTab === 'passed'
+ ? `${t('collection_runner.no_passed_tests')}`
+ : `${t('collection_runner.no_failed_tests')}`
+ "
+ />
+ </template>
<HoppSmartPlaceholder
- v-if="
- (selectedTestTab === 'passed' &&
- tab.document.testRunnerMeta.passedTests === 0) ||
- (selectedTestTab === 'failed' &&
- tab.document.testRunnerMeta.failedTests === 0)
- "
+ v-else
:src="`/images/states/${colorMode.value}/pack.svg`"
- :text="
- selectedTestTab === 'passed'
- ? `${t('collection_runner.no_passed_tests')}`
- : `${t('collection_runner.no_failed_tests')}`
- "
+ :text="`${t('collection_runner.results_not_restored')}`"
/>
</template>
<script setup lang="ts">
import { SmartTreeAdapter } from "@hoppscotch/ui"
-import { ref } from "vue"
+import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue"
import { useI18n } from "~/composables/i18n"
import { useColorMode } from "~/composables/theming"
import { HoppTestRunnerDocument } from "~/helpers/rest/document"
@@ -98,22 +122,140 @@ import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"
const t = useI18n()
const colorMode = useColorMode()
-defineProps<{
+const props = defineProps<{
tab: HoppTab<HoppTestRunnerDocument>
- collectionAdapter: SmartTreeAdapter<any>
+ iterationAdapters: {
+ iteration: number
+ /** Changes whenever the adapter is rebuilt, so the tree remounts with it. */
+ key: string
+ adapter: SmartTreeAdapter<any>
+ }[]
isRunning: boolean
selectedRequestPath: string
+ jumpToIteration: number
}>()
const emit = defineEmits<{
(e: "onSelectRequest", request: TestRunnerRequest): void
(e: "onChangeTab", event: string): void
(e: "requestPath", path: string): void
+ (e: "jumped"): void
+ (e: "visibleIteration", iteration: number): void
}>()
const selectedTestTab = ref<"all" | "passed" | "failed">("all")
-const showCheckbox = ref(false)
+const hasResults = computed(() => props.iterationAdapters.length > 0)
+
+// The iteration headers pin below the filter-tabs row, so its real height
+// feeds their sticky offset via --runner-filter-tabs-height. Measured like
+// the run-details fold in Runner.vue rather than hardcoded.
+const filterTabsEl = ref<HTMLElement | null>(null)
+const filterTabsHeight = ref(48)
+let filterTabsResizeObserver: ResizeObserver | null = null
+
+watch(filterTabsEl, (el) => {
+ filterTabsResizeObserver?.disconnect()
+ if (!el) return
+
+ filterTabsResizeObserver ??= new ResizeObserver((entries) => {
+ const height = entries.at(-1)?.contentRect.height
+ if (height) filterTabsHeight.value = Math.round(height)
+ })
+ filterTabsResizeObserver.observe(el)
+})
+
+onBeforeUnmount(() => filterTabsResizeObserver?.disconnect())
+
+const iterationRefs = new Map<number, HTMLElement>()
+
+const setIterationRef = (iteration: number, el: unknown) => {
+ if (el instanceof HTMLElement) iterationRefs.set(iteration, el)
+ else iterationRefs.delete(iteration)
+}
+
+// Report the iteration under the reading line (just below the pinned filter
+// tabs) so the jump control tracks manual scrolling. The scroll container
+// belongs to the pane layout, so listen in the capture phase on the document
+// instead of reaching for an ancestor by class.
+let visibleIterationScheduled = false
+
+const scrollContainerOf = (el: HTMLElement): HTMLElement | null => {
+ for (let node = el.parentElement; node; node = node.parentElement) {
+ const overflowY = getComputedStyle(node).overflowY
+ if (overflowY === "auto" || overflowY === "scroll") return node
+ }
+ return null
+}
+
+const reportVisibleIteration = () => {
+ visibleIterationScheduled = false
+ const tabsEl = filterTabsEl.value
+ if (!tabsEl || iterationRefs.size === 0) return
+
+ // At the bottom of an overflowing pane the reading line can't reach the
+ // tail iterations; report the last one so a jump there isn't overwritten.
+ // Without the overflow check a short, non-scrolling run is always "at the
+ // bottom" and would report the last iteration while the user sees the first.
+ const container = scrollContainerOf(tabsEl)
+ if (
+ container &&
+ container.scrollHeight > container.clientHeight &&
+ container.scrollTop + container.clientHeight >= container.scrollHeight - 2
+ ) {
+ emit("visibleIteration", Math.max(...iterationRefs.keys()))
+ return
+ }
+
+ const line = tabsEl.getBoundingClientRect().bottom + 4
+ for (const [iteration, el] of iterationRefs) {
+ const rect = el.getBoundingClientRect()
+ if (rect.top <= line && rect.bottom > line) {
+ emit("visibleIteration", iteration)
+ return
+ }
+ }
+}
+
+const onScrollCapture = (event: Event) => {
+ // Capture-phase on document sees every scroll in the app; only react when
+ // the scrolled container is an ancestor of this result view.
+ const tabsEl = filterTabsEl.value
+ if (!tabsEl) return
+ const target = event.target
+ if (target instanceof Element && !target.contains(tabsEl)) return
+
+ if (visibleIterationScheduled) return
+ visibleIterationScheduled = true
+ requestAnimationFrame(reportVisibleIteration)
+}
+
+onMounted(() => {
+ document.addEventListener("scroll", onScrollCapture, {
+ capture: true,
+ passive: true,
+ })
+ // A remount (tab switch and back) restores the list scrolled to the top
+ // while the document may remember another iteration — re-align once.
+ nextTick().then(reportVisibleIteration)
+})
+onBeforeUnmount(() =>
+ document.removeEventListener("scroll", onScrollCapture, { capture: true })
+)
+
+// The iteration group's scroll-margin-top (see <style>) offsets the scroll so
+// the header lands below the sticky run-details fold and filter tabs.
+watch(
+ () => props.jumpToIteration,
+ async (iteration) => {
+ if (!iteration) return
+ await nextTick()
+ iterationRefs
+ .get(iteration)
+ ?.scrollIntoView({ behavior: "smooth", block: "start" })
+ emit("jumped")
+ }
+)
const selectRequest = (request: TestRunnerRequest, indexPath: string) => {
emit("onSelectRequest", request)
@@ -122,7 +264,7 @@ const selectRequest = (request: TestRunnerRequest, indexPath: string) => {
</script>
<style>
-.test-runner > div > div > div > div > div {
+.test-runner > div > div > div > div > div > div {
margin-left: 0;
width: 0;
}
@@ -130,4 +272,13 @@ const selectRequest = (request: TestRunnerRequest, indexPath: string) => {
.test-runner .runner-request {
@apply ml-2;
}
+
+/* Offset jump-to-iteration scrolling past the sticky run-details fold and the
+ filter-tabs row so the iteration header isn't hidden behind them. */
+.iteration-group {
+ scroll-margin-top: calc(
+ var(--upper-runner-sticky-fold, 0px) +
+ var(--runner-filter-tabs-height, 3rem)
+ );
+}
</style>
diff --git a/packages/hoppscotch-common/src/components/http/test/TestResult.vue b/packages/hoppscotch-common/src/components/http/test/TestResult.vue
index 34b54973f..542c2f6e9 100644
--- a/packages/hoppscotch-common/src/components/http/test/TestResult.vue
+++ b/packages/hoppscotch-common/src/components/http/test/TestResult.vue
@@ -191,6 +191,10 @@ import { useI18n } from "@composables/i18n"
import { useReadonlyStream, useStream } from "@composables/stream"
import { isEqual } from "lodash-es"
import { computed, ref } from "vue"
+// Explicit import: auto-resolution inside `http/test/` maps the name to the
+// missing `http/test/ResultEntry.vue` (directoryAsNamespace) and fails at
+// runtime, so nested test entries never rendered.
+import HttpTestResultEntry from "~/components/http/TestResultEntry.vue"
import { HoppTestData, HoppTestResult } from "~/helpers/types/HoppTestResult"
import {
globalEnv$,
diff --git a/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue b/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue
index 1598a5072..1918396a1 100644
--- a/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue
+++ b/packages/hoppscotch-common/src/components/lenses/ResponseBodyRenderer.vue
@@ -96,9 +96,9 @@ const EXPERIMENTAL_SCRIPTING_SANDBOX = useSetting(
"EXPERIMENTAL_SCRIPTING_SANDBOX"
)
-const isSavable = computed(() => {
- return doc.value.response?.type === "success" && doc.value.saveContext
-})
+const isSavable = computed(() =>
+ Boolean(doc.value.response?.type === "success" && doc.value.saveContext)
+)
const showIndicator = computed(() => {
if (!doc.value.testResults) return false
diff --git a/packages/hoppscotch-common/src/helpers/RequestRunner.ts b/packages/hoppscotch-common/src/helpers/RequestRunner.ts
index 887431493..94221a6f4 100644
--- a/packages/hoppscotch-common/src/helpers/RequestRunner.ts
+++ b/packages/hoppscotch-common/src/helpers/RequestRunner.ts
@@ -57,8 +57,10 @@ import { HoppTab } from "~/services/tab"
import { updateTeamEnvironment } from "./backend/mutations/TeamEnvironment"
import { createRESTNetworkRequestStream } from "./network"
import { HoppRequestDocument } from "./rest/document"
+import { stripIterationVarsFromEnvs } from "./runner/iteration-vars"
import {
getTemporaryVariables,
+ scriptEnvsToTemporaryVariables,
setTemporaryVariables,
} from "./runner/temp_envs"
import { HoppRESTResponse } from "./types/HoppRESTResponse"
@@ -870,7 +872,8 @@ export async function runTestRunnerRequest(
inheritedVariables: HoppCollectionVariable[] = [],
initialEnvironmentState: InitialEnvironmentState,
inheritedPreRequestScripts: string[] = [],
- inheritedTestScripts: string[] = []
+ inheritedTestScripts: string[] = [],
+ iterationVars: Environment["variables"] = []
): Promise<
| E.Left<"script_fail">
| E.Right<{
@@ -892,13 +895,23 @@ export async function runTestRunnerRequest(
initialEnvsForComparison,
} = initialEnvironmentState
+ const iterationVarKeys = new Set(iterationVars.map(({ key }) => key))
+ // Injected into `selected` only — the sandbox env shape has no temp scope;
+ // template resolution gets the iteration values via the effective request.
+ const initialEnvsWithIterationData = {
+ ...initialEnvs,
+ selected: [...iterationVars, ...initialEnvs.selected],
+ }
+ const stripIterationVars = (envs: TestResult["envs"]): TestResult["envs"] =>
+ stripIterationVarsFromEnvs(envs, iterationVarKeys, initialEnvs.selected)
+
// Wait for browser to paint the loading state (Send -> Cancel button)
// Adds ~32ms latency but ensures immediate visual feedback
await waitForBrowserPaint()
return delegatePreRequestScriptRunner(
request,
- initialEnvs,
+ initialEnvsWithIterationData,
cookieJarEntries,
inheritedPreRequestScripts
).then(async (preRequestScriptResult) => {
@@ -928,16 +941,24 @@ export async function runTestRunnerRequest(
id: "env-id",
v: 2,
name: "Env",
- variables: filterNonEmptyEnvironmentVariables(
- combineEnvVariables({
+ variables: filterNonEmptyEnvironmentVariables([
+ // Data-file iteration values take precedence over every other scope
+ // (request, collection, environment) for that iteration, matching
+ // Postman's data-variable semantics: the Data scope outranks the
+ // Environment scope that a pre-request script writes to, so a
+ // `pm.environment.set` on a data-column key does not shadow it.
+ // Prepend the iteration values once, then drop those keys from the
+ // combined scopes so each appears exactly once and stays authoritative.
+ ...iterationVars,
+ ...combineEnvVariables({
environments: {
...preRequestScriptResult.right.updatedEnvs,
temp: !persistEnv ? getTemporaryVariables() : [],
},
requestVariables: finalRequestVariables,
collectionVariables: inheritedVariables,
- })
- ),
+ }).filter(({ key }) => !iterationVarKeys.has(key)),
+ ]),
})
const [stream] = createRESTNetworkRequestStream(effectiveRequest)
@@ -964,9 +985,17 @@ export async function runTestRunnerRequest(
)
if (E.isRight(postRequestScriptResult)) {
+ // Iteration values are injected into the environment for the
+ // duration of the request only; strip them back out so a data run
+ // never persists data-file columns as environment variables.
+ const filteredPostRequestScriptResult = {
+ ...postRequestScriptResult.right,
+ envs: stripIterationVars(postRequestScriptResult.right.envs),
+ }
+
// Combine console entries from pre and post request scripts
const combinedResult = {
- ...postRequestScriptResult.right,
+ ...filteredPostRequestScriptResult,
consoleEntries: [
...(preRequestScriptResult.right.consoleEntries ?? []),
...(postRequestScriptResult.right.consoleEntries ?? []),
@@ -984,11 +1013,11 @@ export async function runTestRunnerRequest(
if (
hasEnvironmentChanges(
initialEnvsForComparison, // Initial script environment when requests started
- postRequestScriptResult.right.envs // Final script environment after test script execution
+ filteredPostRequestScriptResult.envs // Final script environment after test script execution
)
) {
updateEnvsAfterTestScript(
- postRequestScriptResult,
+ E.right(filteredPostRequestScriptResult),
initialEnvironmentIndex,
initialEnvName,
initialEnvsForComparison,
@@ -996,13 +1025,11 @@ export async function runTestRunnerRequest(
)
}
} else {
- // Combine global and selected environment changes
- const allChanges = [
- ...postRequestScriptResult.right.envs.global,
- ...postRequestScriptResult.right.envs.selected,
- ]
-
- setTemporaryVariables(allChanges)
+ setTemporaryVariables(
+ scriptEnvsToTemporaryVariables(
+ filteredPostRequestScriptResult.envs
+ )
+ )
}
return E.right({
diff --git a/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts b/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts
index c9dee8f23..0145a7475 100644
--- a/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts
+++ b/packages/hoppscotch-common/src/helpers/fixBrokenRequestVersion.ts
@@ -35,10 +35,20 @@ export const fixBrokenRequestVersion = (
}
if (x.doc.type === "test-runner") {
- x.doc.request = safelyExtractRESTRequest(
- x.doc.request,
- getDefaultRESTRequest()
- )
+ // Runner docs persist `request: null` deliberately. Resurrecting the
+ // null into a default request lets a runner doc with an invalid
+ // collection satisfy the tab-state union's request-tab branch and
+ // silently morph into a blank request tab — only sanitize a request
+ // that actually exists. A missing key is normalized to null: the tab
+ // schema accepts null but not undefined.
+ if (x.doc.request === null || x.doc.request === undefined) {
+ x.doc.request = null
+ } else {
+ x.doc.request = safelyExtractRESTRequest(
+ x.doc.request,
+ getDefaultRESTRequest()
+ )
+ }
if (x.doc.resultCollection) {
x.doc.resultCollection.requests = x.doc.resultCollection?.requests.map(
@@ -47,6 +57,13 @@ export const fixBrokenRequestVersion = (
}
)
}
+
+ // Run results are no longer persisted, but an earlier build's state can
+ // still carry per-iteration result trees whose stale requests would
+ // fail schema validation and take the whole tab state down — drop them.
+ if ("iterationResults" in x.doc) {
+ x.doc.iterationResults = undefined
+ }
}
return x
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.ts b/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.ts
new file mode 100644
index 000000000..f04457da6
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/import-export/export/__tests__/runnerResults.spec.ts
@@ -0,0 +1,163 @@
+import { describe, expect, test } from "vitest"
+
+import { HoppTestRunnerDocument } from "~/helpers/rest/document"
+import { buildRunnerResultReport } from "../runnerResults"
+
+// Minimal document fixture: a single iteration with one request whose response
+// carries the given kernel response `type`. Cast through `unknown` so the
+// fixture only has to specify the fields the report builder actually reads.
+const makeDocument = (
+ responseType: "success" | "fail"
+): HoppTestRunnerDocument => {
+ const response = {
+ type: responseType,
+ statusCode: responseType === "fail" ? 500 : 200,
+ statusText: responseType === "fail" ? "Internal Server Error" : "OK",
+ headers: [{ key: "content-type", value: "application/json" }],
+ body: new TextEncoder().encode(`{"error":${responseType === "fail"}}`)
+ .buffer,
+ meta: { responseSize: 17, responseDuration: 42 },
+ req: {},
+ }
+
+ const request = {
+ name: "req",
+ method: "GET",
+ endpoint: "https://example.com",
+ passedTests: 0,
+ failedTests: 0,
+ error: undefined,
+ testResults: null,
+ response,
+ }
+
+ const meta = {
+ totalRequests: 1,
+ completedRequests: 1,
+ totalTests: 0,
+ passedTests: 0,
+ failedTests: 0,
+ totalTime: 42,
+ }
+
+ return {
+ collectionID: "coll-id",
+ collection: { name: "My Collection" },
+ collectionType: "my-collections",
+ environmentName: "Env",
+ status: "idle",
+ selectedIteration: 0,
+ config: {
+ iterations: 1,
+ delay: 0,
+ stopOnError: false,
+ persistResponses: true,
+ keepVariableValues: false,
+ },
+ testRunnerMeta: meta,
+ iterationResults: [
+ {
+ iteration: 0,
+ meta,
+ resultCollection: {
+ name: "My Collection",
+ folders: [],
+ requests: [request],
+ },
+ },
+ ],
+ } as unknown as HoppTestRunnerDocument
+}
+
+describe("buildRunnerResultReport", () => {
+ test("preserves status/headers/body/meta for failed (4xx/5xx) responses", () => {
+ const report = buildRunnerResultReport(
+ makeDocument("fail"),
+ "all",
+ "base64"
+ )
+ const exported = report.iterationResults[0].requests[0].response
+
+ // Regression guard: error responses carry kernel type "fail" (not "failure"),
+ // so they must be serialized with full detail rather than falling through to
+ // the generic { type, error } branch that drops everything else.
+ expect(exported?.type).toBe("fail")
+ expect(exported?.statusCode).toBe(500)
+ expect(exported?.statusText).toBe("Internal Server Error")
+ expect(exported?.durationInMs).toBe(42)
+ expect(exported?.sizeInBytes).toBe(17)
+ expect(exported?.headers).toEqual([
+ { key: "content-type", value: "application/json" },
+ ])
+ expect(exported?.body).toBeDefined()
+ })
+
+ test("serializes successful responses with full detail", () => {
+ const report = buildRunnerResultReport(
+ makeDocument("success"),
+ "all",
+ "base64"
+ )
+ const exported = report.iterationResults[0].requests[0].response
+
+ expect(exported?.type).toBe("success")
+ expect(exported?.statusCode).toBe(200)
+ expect(exported?.durationInMs).toBe(42)
+ })
+
+ test("derives a failed outcome from an errored assertion (no plain failures)", () => {
+ const request = {
+ name: "req",
+ method: "GET",
+ endpoint: "https://example.com",
+ passedTests: 1,
+ failedTests: 0,
+ error: undefined,
+ testResults: {
+ description: "",
+ scriptError: false,
+ expectResults: [{ status: "error", message: "assertion threw" }],
+ tests: [],
+ },
+ response: null,
+ }
+
+ const document = {
+ collectionID: "coll-id",
+ collection: { name: "My Collection" },
+ collectionType: "my-collections",
+ status: "idle",
+ selectedIteration: 0,
+ config: { iterations: 1 },
+ testRunnerMeta: {
+ totalRequests: 1,
+ completedRequests: 1,
+ totalTests: 1,
+ passedTests: 1,
+ failedTests: 0,
+ totalTime: 0,
+ },
+ iterationResults: [
+ {
+ iteration: 0,
+ meta: {
+ totalRequests: 1,
+ completedRequests: 1,
+ totalTests: 1,
+ passedTests: 1,
+ failedTests: 0,
+ totalTime: 0,
+ },
+ resultCollection: {
+ name: "My Collection",
+ folders: [],
+ requests: [request],
+ },
+ },
+ ],
+ } as unknown as HoppTestRunnerDocument
+
+ const report = buildRunnerResultReport(document, "all", "none")
+ expect(report.outcome).toBe("failed")
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.ts b/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.ts
new file mode 100644
index 000000000..b952c8be6
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/import-export/export/runnerResults.ts
@@ -0,0 +1,402 @@
+import { HoppCollection } from "@hoppscotch/data"
+import * as E from "fp-ts/Either"
+import {
+ HoppTestRunnerDocument,
+ TestRunnerIterationResult,
+ TestRunnerMeta,
+} from "~/helpers/rest/document"
+import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"
+import { HoppTestData, HoppTestResult } from "~/helpers/types/HoppTestResult"
+import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"
+import { platform } from "~/platform"
+
+/**
+ * Controls how response bodies are serialized into the report:
+ * - "base64": binary-safe, capped at BODY_CAP_BYTES (used for the DB report)
+ * - "readable": UTF-8 string for text bodies, base64 fallback for binary (used for the export file)
+ * - "none": bodies omitted entirely (used for the local metadata-only cache)
+ */
+export type RunnerBodyMode = "base64" | "readable" | "none"
+
+const BODY_CAP_BYTES = 300_000
+
+export type ExportedAssertion = {
+ description: string
+ status: "pass" | "fail" | "error"
+ message: string
+}
+
+export type ExportedResponse = {
+ type: HoppRESTResponse["type"]
+ statusCode?: number
+ statusText?: string
+ durationInMs?: number
+ sizeInBytes?: number
+ headers?: { key: string; value: string }[]
+ body?: string
+ bodyEncoding?: "utf-8" | "base64"
+ bodyOmittedReason?: "too-large" | "not-persisted"
+ error?: string
+}
+
+export type ExportedRequest = {
+ name: string
+ method: string
+ endpoint: string
+ passedTests: number
+ failedTests: number
+ error?: string
+ assertions: ExportedAssertion[]
+ response?: ExportedResponse
+}
+
+export type ExportedSummary = {
+ totalRequests: number
+ completedRequests: number
+ totalTests: number
+ passedTests: number
+ failedTests: number
+ totalTimeInMs: number
+}
+
+export type ExportedIteration = {
+ iteration: number
+ summary: ExportedSummary
+ requests: ExportedRequest[]
+}
+
+export type CollectionRunType = "PERSONAL" | "SHARED"
+
+export type CollectionRunOutcome = "passed" | "failed" | "errored"
+
+const COLLECTION_RUN_TYPE_LABELS: Record<CollectionRunType, string> = {
+ PERSONAL: "Personal Collection",
+ SHARED: "Shared Collection",
+}
+
+const collectionRunTypeLabel = (type: CollectionRunType): string =>
+ COLLECTION_RUN_TYPE_LABELS[type] ?? type
+
+export type RunnerResultReport = {
+ collectionID: string
+ collectionName: string
+ collectionType: CollectionRunType
+ environment: string
+ outcome: CollectionRunOutcome
+ exportedAt: string
+ config: {
+ iterations: number
+ delayInMs: number
+ stopOnError: boolean
+ persistResponses: boolean
+ keepVariableValues: boolean
+ dataFile?: string
+ }
+ summary: ExportedSummary
+ iterationResults: ExportedIteration[]
+}
+
+const toSummary = (meta: TestRunnerMeta): ExportedSummary => ({
+ totalRequests: meta.totalRequests,
+ completedRequests: meta.completedRequests,
+ totalTests: meta.totalTests,
+ passedTests: meta.passedTests,
+ failedTests: meta.failedTests,
+ totalTimeInMs: meta.totalTime,
+})
+
+const arrayBufferToBase64 = (buffer: ArrayBuffer): string => {
+ const bytes = new Uint8Array(buffer)
+ const chunkSize = 0x8000
+ let binary = ""
+ for (let i = 0; i < bytes.length; i += chunkSize) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize))
+ }
+ return btoa(binary)
+}
+
+const getContentType = (headers: { key: string; value: string }[]): string =>
+ headers.find((header) => header.key.toLowerCase() === "content-type")
+ ?.value ?? ""
+
+const isTextContentType = (contentType: string): boolean =>
+ /\b(json|xml|html|javascript|csv)\b/i.test(contentType) ||
+ /^text\//i.test(contentType)
+
+const serializeBody = (
+ body: ArrayBuffer,
+ headers: { key: string; value: string }[],
+ mode: RunnerBodyMode
+): Pick<ExportedResponse, "body" | "bodyEncoding" | "bodyOmittedReason"> => {
+ if (mode === "none") return {}
+
+ if (mode === "base64") {
+ if (body.byteLength > BODY_CAP_BYTES)
+ return { bodyOmittedReason: "too-large" }
+ return { body: arrayBufferToBase64(body), bodyEncoding: "base64" }
+ }
+
+ // mode === "readable"
+ if (isTextContentType(getContentType(headers))) {
+ return { body: new TextDecoder().decode(body), bodyEncoding: "utf-8" }
+ }
+ return { body: arrayBufferToBase64(body), bodyEncoding: "base64" }
+}
+
+const flattenAssertions = (tests: HoppTestData[]): ExportedAssertion[] =>
+ tests.flatMap((test) => [
+ ...test.expectResults.map((result) => ({
+ description: test.description,
+ status: result.status,
+ message: result.message,
+ })),
+ ...flattenAssertions(test.tests),
+ ])
+
+const collectAssertions = (
+ testResults: HoppTestResult | null | undefined
+): ExportedAssertion[] => {
+ if (!testResults) return []
+ return [
+ ...testResults.expectResults.map((result) => ({
+ description: testResults.description,
+ status: result.status,
+ message: result.message,
+ })),
+ ...flattenAssertions(testResults.tests),
+ ]
+}
+
+const exportResponse = (
+ response: HoppRESTResponse | null | undefined,
+ bodyMode: RunnerBodyMode
+): ExportedResponse | undefined => {
+ if (!response) return undefined
+
+ // The kernel REST layer emits `"fail"` for HTTP error responses (4xx/5xx),
+ // even though the legacy `HoppRESTResponse` union still calls it `"failure"`.
+ // Match `"fail"` so error iterations keep their status/body/meta in the export
+ // (every other runner code path keys off `"fail"` too).
+ if (response.type === "success" || response.type === "fail") {
+ return {
+ type: response.type,
+ statusCode: response.statusCode,
+ statusText: response.statusText,
+ durationInMs: response.meta.responseDuration,
+ sizeInBytes: response.meta.responseSize,
+ headers: response.headers,
+ ...serializeBody(response.body, response.headers, bodyMode),
+ }
+ }
+
+ return {
+ type: response.type,
+ error:
+ "error" in response
+ ? String((response as { error: unknown }).error)
+ : undefined,
+ }
+}
+
+const exportRequest = (
+ request: TestRunnerRequest,
+ bodyMode: RunnerBodyMode
+): ExportedRequest => ({
+ name: request.name,
+ method: request.method,
+ endpoint: request.endpoint,
+ passedTests: request.passedTests,
+ failedTests: request.failedTests,
+ error: request.error,
+ assertions: collectAssertions(request.testResults),
+ response: exportResponse(request.response, bodyMode),
+})
+
+const exportCollectionRequests = (
+ collection: HoppCollection,
+ bodyMode: RunnerBodyMode
+): ExportedRequest[] => [
+ ...collection.requests.map((request) =>
+ exportRequest(request as TestRunnerRequest, bodyMode)
+ ),
+ ...collection.folders.flatMap((folder) =>
+ exportCollectionRequests(folder, bodyMode)
+ ),
+]
+
+const exportIteration = (
+ iterationResult: TestRunnerIterationResult,
+ bodyMode: RunnerBodyMode
+): ExportedIteration => ({
+ iteration: iterationResult.iteration,
+ summary: toSummary(iterationResult.meta),
+ // A restored iteration keeps only its summary — no rows to export.
+ requests: iterationResult.resultCollection
+ ? exportCollectionRequests(iterationResult.resultCollection, bodyMode)
+ : [],
+})
+
+const collectionHasRequestError = (collection: HoppCollection): boolean =>
+ collection.requests.some((request) =>
+ Boolean((request as TestRunnerRequest).error)
+ ) || collection.folders.some(collectionHasRequestError)
+
+const hasErrorAssertion = (tests: HoppTestData[]): boolean =>
+ tests.some(
+ (test) =>
+ test.expectResults.some((result) => result.status === "error") ||
+ hasErrorAssertion(test.tests)
+ )
+
+const testResultHasError = (
+ testResults: HoppTestResult | null | undefined
+): boolean => {
+ if (!testResults) return false
+ return (
+ testResults.scriptError ||
+ testResults.expectResults.some((result) => result.status === "error") ||
+ hasErrorAssertion(testResults.tests)
+ )
+}
+
+const collectionHasTestError = (collection: HoppCollection): boolean =>
+ collection.requests.some((request) =>
+ testResultHasError((request as TestRunnerRequest).testResults)
+ ) || collection.folders.some(collectionHasTestError)
+
+const deriveOutcome = (
+ document: HoppTestRunnerDocument
+): "passed" | "failed" | "errored" => {
+ if (document.status === "error") return "errored"
+
+ // A test-script error or an assertion with `status: "error"` does not bump
+ // failedTests, so fold those in explicitly — otherwise a run with an errored
+ // assertion (but no plain failures) would be reported as passed.
+ const hasError = (document.iterationResults ?? []).some(
+ (iteration) =>
+ iteration.resultCollection !== undefined &&
+ (collectionHasRequestError(iteration.resultCollection) ||
+ collectionHasTestError(iteration.resultCollection))
+ )
+
+ return document.testRunnerMeta.failedTests > 0 || hasError
+ ? "failed"
+ : "passed"
+}
+
+export type RunnerExportScope = "all" | "current"
+
+export const buildRunnerResultReport = (
+ document: HoppTestRunnerDocument,
+ scope: RunnerExportScope,
+ bodyMode: RunnerBodyMode
+): RunnerResultReport => {
+ const allIterations = document.iterationResults ?? []
+ const selectedIndex = document.selectedIteration ?? 0
+
+ const iterations =
+ scope === "current"
+ ? allIterations.filter((_, index) => index === selectedIndex)
+ : allIterations
+
+ return {
+ collectionID: document.collectionID,
+ collectionName: document.collection.name,
+ collectionType:
+ document.collectionType === "my-collections" ? "PERSONAL" : "SHARED",
+ environment: document.environmentName ?? "Global",
+ outcome: deriveOutcome(document),
+ exportedAt: new Date().toISOString(),
+ config: {
+ iterations: document.config.iterations,
+ delayInMs: document.config.delay,
+ stopOnError: document.config.stopOnError,
+ persistResponses: document.config.persistResponses,
+ keepVariableValues: document.config.keepVariableValues,
+ dataFile: document.config.dataset?.fileName,
+ },
+ summary: toSummary(document.testRunnerMeta),
+ iterationResults: iterations.map((iteration) =>
+ exportIteration(iteration, bodyMode)
+ ),
+ }
+}
+
+const decodeBase64Text = (base64: string): string | null => {
+ try {
+ const binary = atob(base64)
+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0))
+ return new TextDecoder().decode(bytes)
+ } catch {
+ return null
+ }
+}
+
+const base64ToReadableResponse = (response: ExportedResponse): void => {
+ if (response.bodyEncoding !== "base64" || response.body === undefined) return
+ if (!isTextContentType(getContentType(response.headers ?? []))) return
+
+ const decoded = decodeBase64Text(response.body)
+ if (decoded === null) return
+
+ response.body = decoded
+ response.bodyEncoding = "utf-8"
+}
+
+/**
+ * The exported file uses a human-readable collectionType label while the
+ * stored report keeps a stable code.
+ */
+type ExportedReport = Omit<RunnerResultReport, "collectionType"> & {
+ collectionType: string
+}
+
+/**
+ * Re-encodes a stored (base64-body) report into the readable export format so
+ * exported files never contain base64 text bodies. Binary bodies stay base64.
+ */
+const reencodeReportForExport = (
+ report: RunnerResultReport
+): ExportedReport => {
+ const clone: RunnerResultReport = JSON.parse(JSON.stringify(report))
+ clone.iterationResults.forEach((iteration) =>
+ iteration.requests.forEach((request) => {
+ if (request.response) base64ToReadableResponse(request.response)
+ })
+ )
+ return {
+ ...clone,
+ collectionType: collectionRunTypeLabel(clone.collectionType),
+ }
+}
+
+const saveReport = async (report: ExportedReport, filename: string) => {
+ const result = await platform.kernelIO.saveFileWithDialog({
+ data: JSON.stringify(report, null, 2),
+ contentType: "application/json",
+ suggestedFilename: filename,
+ filters: [
+ {
+ name: "Hoppscotch Collection Run Results JSON file",
+ extensions: ["json"],
+ },
+ ],
+ })
+
+ if (result.type === "unknown" || result.type === "saved") {
+ return E.right("state.download_started")
+ }
+
+ return E.left("state.download_failed")
+}
+
+export const exportRunnerResults = async (
+ document: HoppTestRunnerDocument,
+ scope: RunnerExportScope
+) =>
+ saveReport(
+ reencodeReportForExport(
+ buildRunnerResultReport(document, scope, "readable")
+ ),
+ `${document.collection.name || "collection"}-run.json`
+ )
diff --git a/packages/hoppscotch-common/src/helpers/rest/document.ts b/packages/hoppscotch-common/src/helpers/rest/document.ts
index 95c655894..8558934de 100644
--- a/packages/hoppscotch-common/src/helpers/rest/document.ts
+++ b/packages/hoppscotch-common/src/helpers/rest/document.ts
@@ -8,6 +8,7 @@ import { HoppInheritedProperty } from "../types/HoppInheritedProperties"
import { HoppRESTResponse } from "../types/HoppRESTResponse"
import { HoppTestResult } from "../types/HoppTestResult"
import { TestRunnerRequest } from "~/services/test-runner/test-runner.service"
+import { TestRunnerDataset } from "../runner/dataset"
export type HoppRESTSaveContext =
| {
@@ -101,6 +102,22 @@ export type TestRunnerConfig = {
stopOnError: boolean
persistResponses: boolean
keepVariableValues: boolean
+ dataset?: TestRunnerDataset
+}
+
+export type TestRunnerMeta = {
+ totalRequests: number
+ completedRequests: number
+ totalTests: number
+ passedTests: number
+ failedTests: number
+ totalTime: number
+}
+
+export type TestRunnerIterationResult = {
+ iteration: number
+ resultCollection?: HoppCollection
+ meta: TestRunnerMeta
}
export type HoppTestRunnerDocument = {
@@ -146,17 +163,35 @@ export type HoppTestRunnerDocument = {
*/
resultCollection?: HoppCollection
+ /**
+ * Results grouped by iteration.
+ */
+ iterationResults?: TestRunnerIterationResult[]
+
+ /**
+ * Selected result iteration in the UI.
+ */
+ selectedIteration?: number
+
+ /**
+ * Requests selected to run. `undefined` runs the full collection; a non-empty
+ * array runs only those requests. An empty array means "no selection" and is
+ * rejected by the runner (the UI never produces it — it uses `undefined` for
+ * "run all").
+ */
+ selectedRequestRefIds?: string[]
+
+ /**
+ * Name of the environment active when the run started ("Global" when none
+ * was selected). Captured at run start so it is stable across later env
+ * switches.
+ */
+ environmentName?: string
+
/**
* The test runner meta information
*/
- testRunnerMeta: {
- totalRequests: number
- completedRequests: number
- totalTests: number
- passedTests: number
- failedTests: number
- totalTime: number
- }
+ testRunnerMeta: TestRunnerMeta
/**
* Selected test runner request
diff --git a/packages/hoppscotch-common/src/helpers/runner/__tests__/dataset.spec.ts b/packages/hoppscotch-common/src/helpers/runner/__tests__/dataset.spec.ts
new file mode 100644
index 000000000..bde592570
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/__tests__/dataset.spec.ts
@@ -0,0 +1,215 @@
+import * as E from "fp-ts/Either"
+import { describe, expect, test } from "vitest"
+import { datasetRowToTempVars, parseDatasetFile } from "../dataset"
+
+const file = (name: string, body: string) => new File([body], name)
+
+describe("collection runner dataset parsing", () => {
+ test("parses CSV headers as variable names and rows as iteration data", async () => {
+ const result = await parseDatasetFile(
+ file(
+ "testing.csv",
+ " title ,body,userId\nfirst,im first one,1\nsecond,im second one,2"
+ )
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right).toEqual({
+ type: "csv",
+ fileName: "testing.csv",
+ rows: [
+ { title: "first", body: "im first one", userId: "1" },
+ { title: "second", body: "im second one", userId: "2" },
+ ],
+ })
+ })
+
+ // PapaParse emits UndetectableDelimiter on single-column files even though
+ // the parse succeeded; it must not be treated as fatal.
+ test("accepts a single-column CSV", async () => {
+ const result = await parseDatasetFile(
+ file("testing.csv", "userId\n1\n2\n3")
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([
+ { userId: "1" },
+ { userId: "2" },
+ { userId: "3" },
+ ])
+ })
+
+ test("accepts a single-column CSV prefixed with a UTF-8 BOM", async () => {
+ const result = await parseDatasetFile(file("testing.csv", "userId\n1\n2"))
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([{ userId: "1" }, { userId: "2" }])
+ })
+
+ test("ignores trailing whitespace-only lines", async () => {
+ const result = await parseDatasetFile(
+ file("testing.csv", "a,b\n1,2\n \n")
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([{ a: "1", b: "2" }])
+ })
+
+ test("reports the spreadsheet line number for a malformed row", async () => {
+ const result = await parseDatasetFile(
+ file("testing.csv", "a,b\n1,2\n3\n4,5")
+ )
+
+ expect(E.isLeft(result)).toBe(true)
+ if (E.isRight(result)) return
+
+ // Header is line 1, so the short row (parsed row index 1) is line 3.
+ expect(result.left).toContain("Line 3")
+ })
+
+ test("reports the spreadsheet line number for an unterminated quote", async () => {
+ const result = await parseDatasetFile(
+ file("testing.csv", 'user,pass\nbob,x\nalice,"unclosed')
+ )
+
+ expect(E.isLeft(result)).toBe(true)
+ if (E.isRight(result)) return
+
+ // Quotes errors count the header itself as row 0 (PapaParse reports
+ // row 2 here), so the bad row is file line 3 — not line 4.
+ expect(result.left).toContain("Line 3")
+ })
+
+ // skipEmptyLines: "greedy" tests the parsed values with quotes already
+ // stripped, so a row whose every field is quoted whitespace is dropped
+ // exactly like a bare whitespace-only line. Accepted trade-off; a row with
+ // any non-blank field survives, and its quoted whitespace is preserved.
+ test("drops a row whose only field values are quoted whitespace", async () => {
+ const result = await parseDatasetFile(
+ file("testing.csv", 'user\nalice\n" "\nbob\n')
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([{ user: "alice" }, { user: "bob" }])
+ })
+
+ test("keeps a quoted-whitespace field when another field has content", async () => {
+ const result = await parseDatasetFile(
+ file("testing.csv", 'a,b\n1,2\nx," "\n3,4')
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([
+ { a: "1", b: "2" },
+ { a: "x", b: " " },
+ { a: "3", b: "4" },
+ ])
+ })
+
+ test("parses JSON rows and stringifies non-string values", async () => {
+ const result = await parseDatasetFile(
+ file(
+ "testing.json",
+ JSON.stringify([
+ {
+ title: "first",
+ active: true,
+ count: 1,
+ nullable: null,
+ ids: [1, 2],
+ meta: { role: "admin" },
+ },
+ ])
+ )
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([
+ {
+ title: "first",
+ active: "true",
+ count: "1",
+ nullable: "",
+ ids: "[1,2]",
+ meta: '{"role":"admin"}',
+ },
+ ])
+ })
+
+ test("preserves empty JSON rows as iterations with no variables", async () => {
+ const result = await parseDatasetFile(
+ file(
+ "testing.json",
+ JSON.stringify([{ title: "first" }, {}, { title: "third" }])
+ )
+ )
+
+ expect(E.isRight(result)).toBe(true)
+ if (E.isLeft(result)) return
+
+ expect(result.right.rows).toEqual([
+ { title: "first" },
+ {},
+ { title: "third" },
+ ])
+ })
+
+ test("returns a Left when the file cannot be read", async () => {
+ // A non-Blob makes FileReader.readAsText throw; the rejection must surface
+ // as a Left rather than an unhandled promise rejection.
+ const result = await parseDatasetFile({
+ name: "unreadable.json",
+ } as unknown as File)
+
+ expect(E.isLeft(result)).toBe(true)
+ })
+
+ test("rejects JSON files that are not arrays of objects", async () => {
+ const primitiveArray = await parseDatasetFile(
+ file("testing.json", JSON.stringify(["first", "second"]))
+ )
+ const nestedArray = await parseDatasetFile(
+ file("testing.json", JSON.stringify([[1], [2]]))
+ )
+ const object = await parseDatasetFile(
+ file("testing.json", JSON.stringify({ title: "first" }))
+ )
+
+ expect(E.isLeft(primitiveArray)).toBe(true)
+ expect(E.isLeft(nestedArray)).toBe(true)
+ expect(E.isLeft(object)).toBe(true)
+ })
+
+ test("converts a dataset row to temporary environment variables", () => {
+ expect(
+ datasetRowToTempVars({ title: "first", body: "im first one" })
+ ).toEqual([
+ {
+ key: "title",
+ initialValue: "first",
+ currentValue: "first",
+ secret: false,
+ },
+ {
+ key: "body",
+ initialValue: "im first one",
+ currentValue: "im first one",
+ secret: false,
+ },
+ ])
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/runner/__tests__/iteration-vars.spec.ts b/packages/hoppscotch-common/src/helpers/runner/__tests__/iteration-vars.spec.ts
new file mode 100644
index 000000000..312344a8e
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/__tests__/iteration-vars.spec.ts
@@ -0,0 +1,137 @@
+import { describe, expect, test } from "vitest"
+import { stripIterationVarsFromEnvs } from "../iteration-vars"
+
+const v = (key: string, value: string) => ({
+ key,
+ currentValue: value,
+ initialValue: value,
+ secret: false,
+})
+
+const keys = (...names: string[]) => new Set(names)
+
+const selectedOf = (result: { selected: { key: string }[] }) =>
+ result.selected.map(({ key, ...rest }) => [
+ key,
+ (rest as { currentValue: string }).currentValue,
+ ])
+
+describe("stripIterationVarsFromEnvs", () => {
+ test("returns the envs untouched when no iteration keys were injected", () => {
+ const envs = { global: [v("g", "1")], selected: [v("a", "1")] }
+ expect(stripIterationVarsFromEnvs(envs, new Set(), [v("a", "0")])).toBe(
+ envs
+ )
+ })
+
+ test("restores a shadowed env var and drops an unshadowed injected key", () => {
+ const initial = [v("token", "real"), v("host", "prod")]
+ // Injected: token (shadows) and userId (new). Post-script selected carries
+ // the injected values first, then the initial scope.
+ const envs = {
+ global: [],
+ selected: [
+ v("token", "row-token"),
+ v("userId", "42"),
+ v("token", "real"),
+ v("host", "prod"),
+ ],
+ }
+
+ const result = stripIterationVarsFromEnvs(
+ envs,
+ keys("token", "userId"),
+ initial
+ )
+
+ expect(selectedOf(result)).toEqual([
+ ["token", "real"],
+ ["host", "prod"],
+ ])
+ })
+
+ test("keeps a script update to a non-iteration key, at its original position", () => {
+ const initial = [v("a", "1"), v("b", "2")]
+ const envs = {
+ global: [],
+ selected: [v("col", "row"), v("a", "1"), v("b", "scripted")],
+ }
+
+ const result = stripIterationVarsFromEnvs(envs, keys("col"), initial)
+
+ expect(selectedOf(result)).toEqual([
+ ["a", "1"],
+ ["b", "scripted"],
+ ])
+ })
+
+ test("a script deletion of a non-iteration key stays deleted", () => {
+ const initial = [v("a", "1"), v("b", "2")]
+ const envs = { global: [], selected: [v("col", "row"), v("b", "2")] }
+
+ const result = stripIterationVarsFromEnvs(envs, keys("col"), initial)
+
+ expect(selectedOf(result)).toEqual([["b", "2"]])
+ })
+
+ test("script-added keys append after the initial scope", () => {
+ const initial = [v("a", "1")]
+ const envs = {
+ global: [],
+ selected: [v("col", "row"), v("a", "1"), v("added", "new")],
+ }
+
+ const result = stripIterationVarsFromEnvs(envs, keys("col"), initial)
+
+ expect(selectedOf(result)).toEqual([
+ ["a", "1"],
+ ["added", "new"],
+ ])
+ })
+
+ test("does not collapse duplicate non-iteration keys onto one entry", () => {
+ // The env editor allows the same key on several rows; a flat last-wins
+ // lookup would collapse [A:"1", A:"2"] into [A:"2", A:"2"].
+ const initial = [v("A", "1"), v("A", "2"), v("b", "x")]
+ const envs = {
+ global: [],
+ selected: [v("col", "row"), v("A", "1"), v("A", "2"), v("b", "x")],
+ }
+
+ const result = stripIterationVarsFromEnvs(envs, keys("col"), initial)
+
+ expect(selectedOf(result)).toEqual([
+ ["A", "1"],
+ ["A", "2"],
+ ["b", "x"],
+ ])
+ })
+
+ test("pairs duplicate keys by occurrence when a script updates the first", () => {
+ const initial = [v("A", "1"), v("A", "2")]
+ // Sandbox setEnv mutates the first matching occurrence in place.
+ const envs = {
+ global: [],
+ selected: [v("col", "row"), v("A", "9"), v("A", "2")],
+ }
+
+ const result = stripIterationVarsFromEnvs(envs, keys("col"), initial)
+
+ expect(selectedOf(result)).toEqual([
+ ["A", "9"],
+ ["A", "2"],
+ ])
+ })
+
+ test("passes global through untouched", () => {
+ const globalVars = [v("col", "script-wrote-this")]
+ const result = stripIterationVarsFromEnvs(
+ { global: globalVars, selected: [v("col", "row")] },
+ keys("col"),
+ []
+ )
+
+ expect(result.global).toBe(globalVars)
+ expect(result.selected).toEqual([])
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/runner/__tests__/selection.spec.ts b/packages/hoppscotch-common/src/helpers/runner/__tests__/selection.spec.ts
new file mode 100644
index 000000000..9240e3a70
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/__tests__/selection.spec.ts
@@ -0,0 +1,70 @@
+import { HoppCollection } from "@hoppscotch/data"
+import { describe, expect, test } from "vitest"
+import { applyRunOrder, collectRequestIDs } from "../selection"
+
+const request = (name: string) => ({ _ref_id: name, name }) as any
+
+const collection = (
+ name: string,
+ requests: string[],
+ folders: HoppCollection[] = []
+) => ({ name, requests: requests.map(request), folders }) as any
+
+const items = (...ids: string[]) => ids.map((id) => ({ id }))
+const idsOf = (list: { id: string }[]) => list.map(({ id }) => id)
+const order = (...ids: string[]) => new Map(ids.map((id, index) => [id, index]))
+
+// `collectRequestIDs`, `RunnerRequestSelector.flatten` and `planCollection`
+// flatten independently and must agree on the order: folders (depth-first)
+// before a node's own requests.
+describe("collectRequestIDs ordering contract", () => {
+ test("descends into folders before a collection's own requests", () => {
+ const tree = collection(
+ "root",
+ ["a", "b"],
+ [
+ collection("f1", ["c"], [collection("f1a", ["d"])]),
+ collection("f2", ["e"]),
+ ]
+ )
+
+ expect(collectRequestIDs(tree)).toEqual(["d", "c", "e", "a", "b"])
+ })
+
+ test("falls back to a positional id when a request has no _ref_id", () => {
+ const tree = {
+ name: "root",
+ requests: [{ name: "no-ref" }],
+ folders: [{ name: "f", requests: [{ name: "nested" }], folders: [] }],
+ } as any
+
+ expect(collectRequestIDs(tree)).toEqual(["path:0/0", "path:0"])
+ })
+})
+
+describe("applyRunOrder", () => {
+ test("runs requests in the sequence the user set", () => {
+ const result = applyRunOrder(items("a", "b", "c"), order("c", "a", "b"))
+ expect(idsOf(result)).toEqual(["c", "a", "b"])
+ })
+
+ test("keeps collection order when no sequence is set", () => {
+ const result = applyRunOrder(items("a", "b", "c"), new Map())
+ expect(idsOf(result)).toEqual(["a", "b", "c"])
+ })
+
+ test("appends requests the sequence does not mention, in collection order", () => {
+ const result = applyRunOrder(items("a", "b", "c", "d"), order("c", "a"))
+ expect(idsOf(result)).toEqual(["c", "a", "b", "d"])
+ })
+
+ test("ignores sequence entries whose request no longer exists", () => {
+ const result = applyRunOrder(items("a", "b"), order("deleted", "b", "a"))
+ expect(idsOf(result)).toEqual(["b", "a"])
+ })
+
+ test("is stable for items sharing a position", () => {
+ const result = applyRunOrder(items("a", "b", "c"), new Map([["c", 0]]))
+ expect(idsOf(result)).toEqual(["c", "a", "b"])
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/runner/__tests__/temp_envs.spec.ts b/packages/hoppscotch-common/src/helpers/runner/__tests__/temp_envs.spec.ts
new file mode 100644
index 000000000..aa481dc6e
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/__tests__/temp_envs.spec.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from "vitest"
+import { filterNonEmptyEnvironmentVariables } from "~/helpers/utils/environments"
+import { scriptEnvsToTemporaryVariables } from "../temp_envs"
+
+const v = (key: string, value: string) => ({
+ key,
+ currentValue: value,
+ initialValue: value,
+ secret: false,
+})
+
+describe("scriptEnvsToTemporaryVariables", () => {
+ test("orders selected before global", () => {
+ const result = scriptEnvsToTemporaryVariables({
+ global: [v("G", "g"), v("K", "global")],
+ selected: [v("K", "selected"), v("S", "s")],
+ })
+
+ expect(result.map(({ key }) => key)).toEqual(["K", "S", "G", "K"])
+ expect(result[0]).toEqual(
+ expect.objectContaining({ key: "K", currentValue: "selected" })
+ )
+ })
+
+ // A key present in BOTH scopes must resolve to the same value on every
+ // request: request 1 resolves with an empty temp store, request 2+ through
+ // the temp store written from the previous request's script envs.
+ test("keeps a both-scopes key resolving to its selected value across requests", () => {
+ const selected = [v("K", "selected-value")]
+ const global = [v("K", "global-value")]
+
+ const resolveRequest = (
+ temp: ReturnType<typeof scriptEnvsToTemporaryVariables>
+ ) =>
+ filterNonEmptyEnvironmentVariables([
+ ...temp,
+ ...selected,
+ ...global,
+ ]).find(({ key }) => key === "K")
+
+ // Request 1: no temp store yet.
+ const request1 = resolveRequest([])
+ // Request 2+: temp store carries the previous request's script envs.
+ const request2 = resolveRequest(
+ scriptEnvsToTemporaryVariables({ global, selected })
+ )
+
+ expect(request1?.currentValue).toBe("selected-value")
+ expect(request2?.currentValue).toBe("selected-value")
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/runner/dataset.ts b/packages/hoppscotch-common/src/helpers/runner/dataset.ts
new file mode 100644
index 000000000..ff0e68961
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/dataset.ts
@@ -0,0 +1,139 @@
+import { Environment } from "@hoppscotch/data"
+import * as E from "fp-ts/Either"
+import Papa from "papaparse"
+
+export type DatasetFileType = "csv" | "json"
+
+export type DatasetRow = Record<string, string>
+
+export type TestRunnerDataset = {
+ fileName: string
+ type: DatasetFileType
+ rows: DatasetRow[]
+}
+
+const getDatasetFileType = (fileName: string): DatasetFileType | null => {
+ const extension = fileName.split(".").pop()?.toLowerCase()
+
+ if (extension === "csv" || extension === "json") return extension
+ return null
+}
+
+const isPlainObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value)
+
+export const stringifyDatasetValue = (value: unknown) => {
+ if (value === null || value === undefined) return ""
+ if (typeof value === "object") return JSON.stringify(value)
+
+ return String(value)
+}
+
+const normalizeRow = (row: Record<string, unknown>): DatasetRow =>
+ Object.fromEntries(
+ Object.entries(row)
+ .filter(([key]) => key.trim().length > 0)
+ .map(([key, value]) => [key.trim(), stringifyDatasetValue(value)])
+ )
+
+// PapaParse reports notices through the same `errors` array as real failures.
+// `UndetectableDelimiter` fires on every single-column file even though the
+// parse succeeded, so `Delimiter` errors are never fatal.
+const isFatalParseError = (error: Papa.ParseError) => error.type !== "Delimiter"
+
+// PapaParse's `row` base differs by error type: FieldMismatch counts 0-based
+// data rows (header excluded, so +2 is the file line), but Quotes errors come
+// from the core parser where the header itself is row 0 (so +1).
+const formatParseError = (error: Papa.ParseError) =>
+ typeof error.row === "number"
+ ? `Line ${error.row + (error.type === "Quotes" ? 1 : 2)}: ${error.message}`
+ : error.message
+
+const parseCSV = (contents: string): E.Either<string, DatasetRow[]> => {
+ const parsed = Papa.parse<Record<string, unknown>>(contents, {
+ header: true,
+ // "greedy" also drops whitespace-only lines, which plain `true` parses as
+ // one-field rows that fail the file with TooFewFields. Trade-off: greedy
+ // tests the parsed values (quotes already stripped), so a row whose every
+ // field is quoted whitespace (e.g. `" "`) is dropped too.
+ skipEmptyLines: "greedy",
+ transformHeader: (header) => header.trim(),
+ })
+
+ const fatalErrors = parsed.errors.filter(isFatalParseError)
+
+ if (fatalErrors.length > 0) {
+ return E.left(fatalErrors.map(formatParseError).join(", "))
+ }
+
+ // A row with no data columns is still a valid iteration.
+ return E.right(parsed.data.map(normalizeRow))
+}
+
+const parseJSON = (contents: string): E.Either<string, DatasetRow[]> => {
+ try {
+ const parsed = JSON.parse(contents)
+
+ if (!Array.isArray(parsed)) {
+ return E.left("JSON data file must be an array of objects")
+ }
+
+ if (!parsed.every(isPlainObject)) {
+ return E.left("JSON data file must contain only objects")
+ }
+
+ // An empty object is still a valid iteration; don't drop it.
+ return E.right(parsed.map(normalizeRow))
+ } catch (error) {
+ return E.left(
+ error instanceof Error ? error.message : "Invalid JSON data file"
+ )
+ }
+}
+
+const readFileAsText = (file: File) =>
+ new Promise<string>((resolve, reject) => {
+ const reader = new FileReader()
+
+ reader.onload = () => resolve(String(reader.result ?? ""))
+ reader.onerror = () =>
+ reject(reader.error ?? new Error("Failed to read data file"))
+ reader.readAsText(file)
+ })
+
+export const parseDatasetFile = async (
+ file: File
+): Promise<E.Either<string, TestRunnerDataset>> => {
+ const type = getDatasetFileType(file.name)
+
+ if (!type) return E.left("Unsupported data file type")
+
+ let contents: string
+ try {
+ contents = await readFileAsText(file)
+ } catch (error) {
+ return E.left(
+ error instanceof Error ? error.message : "Failed to read data file"
+ )
+ }
+
+ const parsedRows = type === "csv" ? parseCSV(contents) : parseJSON(contents)
+
+ if (E.isLeft(parsedRows)) return parsedRows
+
+ return E.right({
+ fileName: file.name,
+ type,
+ rows: parsedRows.right,
+ })
+}
+
+export const datasetRowToTempVars = (
+ row: DatasetRow
+): Environment["variables"] =>
+ Object.entries(row).map(([key, value]) => ({
+ key,
+ initialValue: value,
+ currentValue: value,
+ secret: false,
+ }))
diff --git a/packages/hoppscotch-common/src/helpers/runner/iteration-vars.ts b/packages/hoppscotch-common/src/helpers/runner/iteration-vars.ts
new file mode 100644
index 000000000..09c7c9ce9
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/iteration-vars.ts
@@ -0,0 +1,60 @@
+import { Environment } from "@hoppscotch/data"
+import { TestResult } from "@hoppscotch/js-sandbox"
+
+/**
+ * Strips injected data-file iteration variables back out of a post-script env
+ * so a data-driven run stays ephemeral on writeback, restoring any selected
+ * variable a dataset column shadowed.
+ *
+ * The initial scope is walked in its original order because
+ * `updateEnvsAfterTestScript` persists `selected` wholesale — rebuilding in a
+ * different order would reshuffle the user's environment. Lookups are
+ * occurrence-paired rather than key-flat: the env editor allows duplicate
+ * keys and sandbox writes mutate the first matching occurrence. Script-added
+ * keys are appended; `global` is left alone (iteration values are never
+ * injected into it).
+ *
+ * Known limit: if a script DELETES an occurrence of a key duplicated in the
+ * initial scope, the surviving occurrence keeps the deleted row's position
+ * (initial-order walk) instead of its post-script one. Values stay correct;
+ * only the relative order of that pair can differ from the script's view.
+ */
+export const stripIterationVarsFromEnvs = (
+ envs: TestResult["envs"],
+ iterationVarKeys: Set<string>,
+ initialSelected: Environment["variables"]
+): TestResult["envs"] => {
+ if (iterationVarKeys.size === 0) return envs
+
+ // key → queue of final entries, consumed one per initial occurrence.
+ const finalByKey = new Map<string, TestResult["envs"]["selected"]>()
+ for (const env of envs.selected) {
+ const queue = finalByKey.get(env.key)
+ if (queue) queue.push(env)
+ else finalByKey.set(env.key, [env])
+ }
+
+ const initialKeys = new Set(initialSelected.map(({ key }) => key))
+
+ const rebuilt: TestResult["envs"]["selected"] = []
+ for (const initialVar of initialSelected) {
+ if (iterationVarKeys.has(initialVar.key)) {
+ rebuilt.push(initialVar)
+ continue
+ }
+
+ // No final occurrence left → a script deleted this row.
+ const final = finalByKey.get(initialVar.key)?.shift()
+ if (final) rebuilt.push(final)
+ }
+
+ return {
+ global: envs.global,
+ selected: [
+ ...rebuilt,
+ ...envs.selected.filter(
+ ({ key }) => !initialKeys.has(key) && !iterationVarKeys.has(key)
+ ),
+ ],
+ }
+}
diff --git a/packages/hoppscotch-common/src/helpers/runner/selection.ts b/packages/hoppscotch-common/src/helpers/runner/selection.ts
new file mode 100644
index 000000000..8139e3d0a
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/runner/selection.ts
@@ -0,0 +1,47 @@
+import { HoppCollection, HoppRESTRequest } from "@hoppscotch/data"
+
+export const getRequestSelectionID = (
+ request: HoppRESTRequest,
+ path: number[]
+) => request._ref_id || `path:${path.join("/")}`
+
+/**
+ * Applies a run sequence to a list of items keyed by selection ID.
+ *
+ * Items named by `runOrder` come first, in the position it gives them; the
+ * rest keep their original relative order behind them, so a request added
+ * after the sequence was saved still runs.
+ */
+export const applyRunOrder = <T extends { id: string }>(
+ items: T[],
+ runOrder: Map<string, number>
+): T[] => {
+ const positionOf = (item: T) =>
+ runOrder.get(item.id) ?? Number.MAX_SAFE_INTEGER
+
+ return items
+ .map((item, index) => ({ item, index }))
+ .sort(
+ (a, b) => positionOf(a.item) - positionOf(b.item) || a.index - b.index
+ )
+ .map(({ item }) => item)
+}
+
+/**
+ * Recursively collects the selection IDs of every request in a collection
+ * tree, in the runner's execution order: folders (depth-first) before a
+ * node's own requests. `RunnerRequestSelector` and `planCollection` flatten
+ * with the same rule — the three must agree or the displayed run sequence
+ * stops matching the executed one.
+ */
+export const collectRequestIDs = (
+ collection: HoppCollection,
+ parentPath: number[] = []
+): string[] => [
+ ...collection.folders.flatMap((folder, index) =>
+ collectRequestIDs(folder, [...parentPath, index])
+ ),
+ ...collection.requests.map((request, index) =>
+ getRequestSelectionID(request as HoppRESTRequest, [...parentPath, index])
+ ),
+]
diff --git a/packages/hoppscotch-common/src/helpers/runner/temp_envs.ts b/packages/hoppscotch-common/src/helpers/runner/temp_envs.ts
index 88772573f..a34b782d1 100644
--- a/packages/hoppscotch-common/src/helpers/runner/temp_envs.ts
+++ b/packages/hoppscotch-common/src/helpers/runner/temp_envs.ts
@@ -18,3 +18,18 @@ export function clearTemporaryVariables() {
export function addTemporaryVariable(variable: GlobalEnvironmentVariable) {
temporaryVariables.value.push(variable)
}
+
+/**
+ * Shapes post-script env changes for the temporary-variable store
+ * (keepVariableValues = false runs).
+ *
+ * Selected must precede global: the temp scope outranks both real scopes and
+ * is deduped first-occurrence-wins, so this order keeps a key present in both
+ * scopes resolving to its selected value on every request of a run.
+ */
+export function scriptEnvsToTemporaryVariables(envs: {
+ global: GlobalEnvironmentVariable[]
+ selected: GlobalEnvironmentVariable[]
+}): GlobalEnvironmentVariable[] {
+ return [...envs.selected, ...envs.global]
+}
diff --git a/packages/hoppscotch-common/src/helpers/utils/__tests__/inheritedCollectionVarTransformer.spec.ts b/packages/hoppscotch-common/src/helpers/utils/__tests__/inheritedCollectionVarTransformer.spec.ts
new file mode 100644
index 000000000..84c786a36
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/utils/__tests__/inheritedCollectionVarTransformer.spec.ts
@@ -0,0 +1,286 @@
+import { afterEach, describe, expect, test } from "vitest"
+import { getService } from "~/modules/dioc"
+import { CurrentValueService } from "~/services/current-environment-value.service"
+import { SecretEnvironmentService } from "~/services/secret-environment.service"
+import {
+ populateValuesInInheritedCollectionVars,
+ resolveInheritedVariables,
+} from "../inheritedCollectionVarTransformer"
+
+const currentValues = getService(CurrentValueService)
+const secretEnvs = getService(SecretEnvironmentService)
+
+// The services are module-scoped singletons — drop everything a test stored
+// so no state leaks into the next one.
+afterEach(() => {
+ currentValues.environments.clear()
+ secretEnvs.secretEnvironments.clear()
+})
+
+const collectionVar = (key: string, currentValue = "") => ({
+ key,
+ currentValue,
+ initialValue: "",
+ secret: false,
+})
+
+const secretCollectionVar = (key: string) => ({
+ key,
+ // Secret values never live on the collection JSON — only in
+ // SecretEnvironmentService.
+ currentValue: "",
+ initialValue: "",
+ secret: true,
+})
+
+const storedSecret = (key: string, value: string, varIndex: number) => ({
+ key,
+ value,
+ varIndex,
+})
+
+const stored = (key: string, currentValue: string, varIndex: number) => ({
+ key,
+ currentValue,
+ varIndex,
+ isSecret: false,
+})
+
+describe("resolveInheritedVariables", () => {
+ test("resolves each collection's variables under its own ID", () => {
+ currentValues.addEnvironment("coll-c", [stored("A", "a-current", 0)])
+ currentValues.addEnvironment("coll-f", [stored("B", "b-current", 0)])
+
+ const levelC = resolveInheritedVariables([], [collectionVar("A")], "coll-c")
+ const levelF = resolveInheritedVariables(
+ levelC,
+ [collectionVar("B")],
+ "coll-f"
+ )
+ const levelG = resolveInheritedVariables(levelF, [], "coll-g")
+
+ expect(levelG).toEqual([
+ expect.objectContaining({ key: "A", currentValue: "a-current" }),
+ expect.objectContaining({ key: "B", currentValue: "b-current" }),
+ ])
+ })
+
+ // Re-resolving the MERGED array under one ID reads by index collision:
+ // A (merged index 0) would be looked up at (F.id, 0) — B's storage slot.
+ test("a folder's stored value is never assigned to an ancestor's variable", () => {
+ // Only F has a stored current value.
+ currentValues.addEnvironment("coll-f", [stored("B", "b-current", 0)])
+
+ const levelC = resolveInheritedVariables(
+ [],
+ [collectionVar("A", "a-own")],
+ "coll-c"
+ )
+ const levelF = resolveInheritedVariables(
+ levelC,
+ [collectionVar("B")],
+ "coll-f"
+ )
+ const levelG = resolveInheritedVariables(levelF, [], "coll-g")
+
+ const a = levelG.find(({ key }) => key === "A")
+ const b = levelG.find(({ key }) => key === "B")
+
+ expect(a?.currentValue).toBe("a-own")
+ expect(a?.currentValue).not.toBe("b-current")
+ expect(b?.currentValue).toBe("b-current")
+ })
+
+ test("parents pass through untouched, by reference", () => {
+ const parents = [collectionVar("A", "resolved-upstream")]
+ const result = resolveInheritedVariables(
+ parents,
+ [collectionVar("B")],
+ "coll-x"
+ )
+
+ expect(result[0]).toBe(parents[0])
+ })
+})
+
+describe("populateValuesInInheritedCollectionVars", () => {
+ test("returns [] without an owning collection ID", () => {
+ expect(
+ populateValuesInInheritedCollectionVars([collectionVar("A")], undefined)
+ ).toEqual([])
+ })
+
+ test("falls back to the variable's own currentValue when nothing is stored", () => {
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [collectionVar("A", "fallback")],
+ "coll-empty"
+ )
+ ).toEqual([expect.objectContaining({ key: "A", currentValue: "fallback" })])
+ })
+
+ // Team collections store client-local values under the server `id`, while
+ // the fetched tree regenerates `_ref_id` on every load.
+ test("resolves via the server-id fallback when the primary ref misses (team key scheme)", () => {
+ currentValues.addEnvironment("server-id-1", [
+ { key: "T", currentValue: "team-CURRENT", varIndex: 0, isSecret: false },
+ ])
+
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [collectionVar("T")],
+ "coll_regenerated_random_ref", // fresh _ref_id: no stored entries
+ "server-id-1"
+ )
+ ).toEqual([
+ expect.objectContaining({ key: "T", currentValue: "team-CURRENT" }),
+ ])
+ })
+
+ test("the primary key wins over the fallback when both have entries", () => {
+ currentValues.addEnvironment("primary-ref", [
+ {
+ key: "P",
+ currentValue: "primary-CURRENT",
+ varIndex: 0,
+ isSecret: false,
+ },
+ ])
+ currentValues.addEnvironment("fallback-id", [
+ {
+ key: "P",
+ currentValue: "fallback-CURRENT",
+ varIndex: 0,
+ isSecret: false,
+ },
+ ])
+
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [collectionVar("P")],
+ "primary-ref",
+ "fallback-id"
+ )
+ ).toEqual([
+ expect.objectContaining({ key: "P", currentValue: "primary-CURRENT" }),
+ ])
+ })
+})
+
+// Secret values are stored in SecretEnvironmentService, NOT
+// CurrentValueService — without `showSecret` the lookup reads the wrong store
+// and secrets silently resolve to "" in the runner.
+describe("populateValuesInInheritedCollectionVars — secret variables", () => {
+ test("resolves a secret's value from SecretEnvironmentService when showSecret is true", () => {
+ secretEnvs.addSecretEnvironment("sec-coll", [
+ storedSecret("TOKEN", "s3cret-CURRENT", 0),
+ ])
+
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [secretCollectionVar("TOKEN")],
+ "sec-coll",
+ undefined,
+ true
+ )
+ ).toEqual([
+ expect.objectContaining({ key: "TOKEN", currentValue: "s3cret-CURRENT" }),
+ ])
+ })
+
+ test("resolves a secret via the server-id fallback when the primary ref misses (team key scheme)", () => {
+ secretEnvs.addSecretEnvironment("sec-srv-1", [
+ storedSecret("TEAM_TOKEN", "team-s3cret", 0),
+ ])
+
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [secretCollectionVar("TEAM_TOKEN")],
+ "sec_regenerated_random_ref", // fresh _ref_id: no stored entries
+ "sec-srv-1",
+ true
+ )
+ ).toEqual([
+ expect.objectContaining({
+ key: "TEAM_TOKEN",
+ currentValue: "team-s3cret",
+ }),
+ ])
+ })
+
+ test("keeps a secret masked (empty) when showSecret is false — the default", () => {
+ secretEnvs.addSecretEnvironment("sec-masked", [
+ storedSecret("TOKEN", "must-not-appear", 0),
+ ])
+
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [secretCollectionVar("TOKEN")],
+ "sec-masked"
+ )
+ ).toEqual([expect.objectContaining({ key: "TOKEN", currentValue: "" })])
+ })
+
+ // Both stores key by the variable's index in the FULL variable list, so a
+ // secret sitting after a non-secret must read its own slot in each store.
+ test("mixed secret and non-secret variables each resolve from their own store", () => {
+ currentValues.addEnvironment("sec-mixed", [
+ stored("plain", "plain-CURRENT", 0),
+ ])
+ secretEnvs.addSecretEnvironment("sec-mixed", [
+ storedSecret("TOKEN", "mixed-s3cret", 1),
+ ])
+
+ expect(
+ populateValuesInInheritedCollectionVars(
+ [collectionVar("plain"), secretCollectionVar("TOKEN")],
+ "sec-mixed",
+ undefined,
+ true
+ )
+ ).toEqual([
+ expect.objectContaining({ key: "plain", currentValue: "plain-CURRENT" }),
+ expect.objectContaining({ key: "TOKEN", currentValue: "mixed-s3cret" }),
+ ])
+ })
+})
+
+describe("resolveInheritedVariables — secret variables", () => {
+ test("threads showSecret through to the own-level resolution", () => {
+ secretEnvs.addSecretEnvironment("sec-own", [
+ storedSecret("OWN_TOKEN", "own-s3cret", 0),
+ ])
+
+ const resolved = resolveInheritedVariables(
+ [collectionVar("A", "resolved-upstream")],
+ [secretCollectionVar("OWN_TOKEN")],
+ "sec-own",
+ undefined,
+ true
+ )
+
+ expect(resolved).toEqual([
+ expect.objectContaining({ key: "A", currentValue: "resolved-upstream" }),
+ expect.objectContaining({
+ key: "OWN_TOKEN",
+ currentValue: "own-s3cret",
+ }),
+ ])
+ })
+
+ test("defaults to masked secrets when showSecret is omitted", () => {
+ secretEnvs.addSecretEnvironment("sec-default", [
+ storedSecret("TOKEN", "must-not-appear", 0),
+ ])
+
+ const resolved = resolveInheritedVariables(
+ [],
+ [secretCollectionVar("TOKEN")],
+ "sec-default"
+ )
+
+ expect(resolved).toEqual([
+ expect.objectContaining({ key: "TOKEN", currentValue: "" }),
+ ])
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/utils/inheritedCollectionVarTransformer.ts b/packages/hoppscotch-common/src/helpers/utils/inheritedCollectionVarTransformer.ts
index 53e47de0e..61284c5c1 100644
--- a/packages/hoppscotch-common/src/helpers/utils/inheritedCollectionVarTransformer.ts
+++ b/packages/hoppscotch-common/src/helpers/utils/inheritedCollectionVarTransformer.ts
@@ -71,13 +71,55 @@ export const transformInheritedCollectionVariablesToAggregateEnv = (
*/
export const populateValuesInInheritedCollectionVars = (
variables: HoppCollectionVariable[],
- parentID?: string
+ parentID?: string,
+ /**
+ * Second storage key to try when `parentID` misses. Client-local values are
+ * stored under `_ref_id ?? id` for personal collections but under the
+ * server `id` for team collections, whose `_ref_id` is regenerated on every
+ * fetch — passing the server id here serves both key schemes.
+ */
+ fallbackID?: string,
+ /**
+ * Secret values live in `SecretEnvironmentService`, not
+ * `CurrentValueService` — pass `true` from execution paths (the collection
+ * runner) so secret variables resolve. Leave `false` anywhere the output
+ * is rendered or persisted.
+ */
+ showSecret: boolean = false
): HoppCollectionVariable[] =>
parentID
? variables.map((variable, index) => ({
...variable,
currentValue:
- getCurrentValue(variable.secret, index, parentID) ??
+ getCurrentValue(variable.secret, index, parentID, showSecret) ??
+ (fallbackID && fallbackID !== parentID
+ ? getCurrentValue(variable.secret, index, fallbackID, showSecret)
+ : undefined) ??
variable.currentValue,
}))
: []
+
+/**
+ * Resolves one level of collection-variable inheritance for the runner walk.
+ *
+ * Parents arrive already resolved and pass through untouched; only the
+ * current collection's own variables are populated here, under its own ID
+ * with indices into its own list — the `(collectionID, varIndex)` key shape
+ * `CurrentValueService` stores. Never re-resolve the merged array under a
+ * single ID: indices collide across owners and read other variables' slots.
+ */
+export const resolveInheritedVariables = (
+ parentVariables: HoppCollectionVariable[],
+ ownVariables: HoppCollectionVariable[],
+ ownCollectionID?: string,
+ ownCollectionFallbackID?: string,
+ showSecret: boolean = false
+): HoppCollectionVariable[] => [
+ ...parentVariables,
+ ...populateValuesInInheritedCollectionVars(
+ ownVariables,
+ ownCollectionID,
+ ownCollectionFallbackID,
+ showSecret
+ ),
+]
diff --git a/packages/hoppscotch-common/src/newstore/__tests__/collections-inherited-props.spec.ts b/packages/hoppscotch-common/src/newstore/__tests__/collections-inherited-props.spec.ts
new file mode 100644
index 000000000..e607e6769
--- /dev/null
+++ b/packages/hoppscotch-common/src/newstore/__tests__/collections-inherited-props.spec.ts
@@ -0,0 +1,173 @@
+import { afterEach, describe, expect, test, vi } from "vitest"
+
+// newstore/collections sits on an import cycle (collections → services/tab/rest
+// → services/persistence → collections); stub the cycle edge so the module
+// loads under vitest.
+vi.mock("~/services/tab/rest", () => ({
+ RESTTabService: class MockRESTTabService {
+ static ID = "REST_TAB_SERVICE"
+ },
+}))
+vi.mock("~/modules/i18n", () => ({ getI18n: () => (k: string) => k }))
+
+import { getService } from "~/modules/dioc"
+import { CurrentValueService } from "~/services/current-environment-value.service"
+import { SecretEnvironmentService } from "~/services/secret-environment.service"
+
+// The value stores are module-scoped singletons — drop everything a test
+// stored so no state leaks into the next one.
+afterEach(() => {
+ getService(CurrentValueService).environments.clear()
+ getService(SecretEnvironmentService).secretEnvironments.clear()
+})
+
+const collectionVar = (key: string, initialValue: string) => ({
+ key,
+ initialValue,
+ // Current values live in CurrentValueService, not on the collection JSON.
+ currentValue: "",
+ secret: false,
+})
+
+const node = (
+ refId: string,
+ name: string,
+ variables: ReturnType<typeof collectionVar>[],
+ folders: unknown[] = []
+) => ({
+ v: 12,
+ _ref_id: refId,
+ name,
+ folders,
+ requests: [],
+ headers: [],
+ variables,
+ auth: { authType: "inherit", authActive: true },
+ description: null,
+ preRequestScript: "",
+ testScript: "",
+})
+
+describe("getRESTCollectionInheritedProps — collection variable values", () => {
+ test("resolves every ancestor level's CURRENT value, not just the top one", async () => {
+ const { getRESTCollectionInheritedProps } = await import("../collections")
+
+ const currentValues = getService(CurrentValueService)
+ currentValues.addEnvironment("ref-root", [
+ {
+ key: "rootVar",
+ currentValue: "root-CURRENT",
+ varIndex: 0,
+ isSecret: false,
+ },
+ ])
+ currentValues.addEnvironment("ref-parent", [
+ {
+ key: "parentVar",
+ currentValue: "parent-CURRENT",
+ varIndex: 0,
+ isSecret: false,
+ },
+ ])
+
+ // root → parent folder → grandchild (the run target)
+ const tree = node(
+ "ref-root",
+ "Root",
+ [collectionVar("rootVar", "root-initial")],
+ [
+ node(
+ "ref-parent",
+ "Parent",
+ [collectionVar("parentVar", "parent-initial")],
+ [node("ref-child", "Child", [])]
+ ),
+ ]
+ )
+
+ const props = getRESTCollectionInheritedProps(
+ "ref-child",
+ [tree] as any,
+ "my-collections"
+ )
+
+ expect(props).not.toBeNull()
+ expect(props!.ancestorVariables).toEqual([
+ expect.objectContaining({ key: "rootVar", currentValue: "root-CURRENT" }),
+ expect.objectContaining({
+ key: "parentVar",
+ currentValue: "parent-CURRENT",
+ }),
+ ])
+ })
+
+ test("running a folder: ancestors resolved, own variables excluded from ancestors", async () => {
+ const { getRESTCollectionInheritedProps } = await import("../collections")
+
+ const currentValues = getService(CurrentValueService)
+ currentValues.addEnvironment("ref-root2", [
+ { key: "a", currentValue: "a-CURRENT", varIndex: 0, isSecret: false },
+ ])
+ currentValues.addEnvironment("ref-f2", [
+ { key: "b", currentValue: "b-CURRENT", varIndex: 0, isSecret: false },
+ ])
+
+ const tree = node(
+ "ref-root2",
+ "Root",
+ [collectionVar("a", "a-initial")],
+ [node("ref-f2", "F", [collectionVar("b", "b-initial")])]
+ )
+
+ const props = getRESTCollectionInheritedProps(
+ "ref-f2",
+ [tree] as any,
+ "my-collections"
+ )
+
+ expect(props!.ancestorVariables).toEqual([
+ expect.objectContaining({ key: "a", currentValue: "a-CURRENT" }),
+ ])
+ // The target's own variables stay out of the ancestor list — the runner
+ // resolves them itself from the raw collection.
+ expect(props!.ancestorVariables).toHaveLength(1)
+ })
+
+ test("running the root: no ancestors", async () => {
+ const { getRESTCollectionInheritedProps } = await import("../collections")
+ const tree = node("ref-solo", "Solo", [collectionVar("x", "x-initial")])
+ const props = getRESTCollectionInheritedProps(
+ "ref-solo",
+ [tree] as any,
+ "my-collections"
+ )
+ expect(props!.ancestorVariables).toEqual([])
+ })
+
+ // Secret values live in SecretEnvironmentService, not CurrentValueService —
+ // this output feeds the runner's execution path, so secrets must resolve.
+ test("resolves an ancestor's SECRET value for the runner", async () => {
+ const { getRESTCollectionInheritedProps } = await import("../collections")
+
+ getService(SecretEnvironmentService).addSecretEnvironment("ref-sec-root", [
+ { key: "TOKEN", value: "root-s3cret", varIndex: 0 },
+ ])
+
+ const tree = node(
+ "ref-sec-root",
+ "Root",
+ [{ key: "TOKEN", initialValue: "", currentValue: "", secret: true }],
+ [node("ref-sec-child", "Child", [])]
+ )
+
+ const props = getRESTCollectionInheritedProps(
+ "ref-sec-child",
+ [tree] as any,
+ "my-collections"
+ )
+
+ expect(props!.ancestorVariables).toEqual([
+ expect.objectContaining({ key: "TOKEN", currentValue: "root-s3cret" }),
+ ])
+ })
+})
diff --git a/packages/hoppscotch-common/src/newstore/collections.ts b/packages/hoppscotch-common/src/newstore/collections.ts
index 38dbdc80b..9e7a073c0 100644
--- a/packages/hoppscotch-common/src/newstore/collections.ts
+++ b/packages/hoppscotch-common/src/newstore/collections.ts
@@ -21,6 +21,7 @@ import { RESTTabService } from "~/services/tab/rest"
import DispatchingStore, { defineDispatchers } from "./DispatchingStore"
import { SecretEnvironmentService } from "~/services/secret-environment.service"
import { CurrentValueService } from "~/services/current-environment-value.service"
+import { populateValuesInInheritedCollectionVars } from "~/helpers/utils/inheritedCollectionVarTransformer"
//collection variables current value and secret value
const secretEnvironmentService = getService(SecretEnvironmentService)
@@ -1713,7 +1714,15 @@ export function getRESTCollection(collectionIndex: number) {
export type RESTCollectionInheritedProps = {
auth: HoppRESTAuth
headers: HoppRESTHeaders
- variables: HoppCollectionVariable[]
+ /**
+ * Ancestor collection variables only (root → target's parent), each level
+ * resolved under its OWNING collection's ID — resolved for EXECUTION
+ * (secret values included; never render or persist them). The target's own
+ * variables are deliberately NOT merged in: the runner resolves those
+ * itself, and re-resolving a merged array under one ID reads other
+ * variables' slots by index collision.
+ */
+ ancestorVariables: HoppCollectionVariable[]
// Ancestor scripts for partial-scope runs (root → target's parent).
// Empty when running from the topmost collection.
ancestorPreRequestScripts: string[]
@@ -1741,9 +1750,19 @@ function computeCollectionInheritedProps(
...collection.headers,
]
+ // Each level's own variables are resolved under the level's OWN ID — the
+ // `(collectionID, varIndex)` key shape current values are stored with.
+ // Consumers must never re-resolve the merged array under a single ID.
+ // Secrets resolve (`showSecret`) because this only feeds the collection
+ // runner's execution path — the output is never rendered or persisted.
const inheritedVariables = [
...(parentVariables ?? []),
- ...collection.variables,
+ ...populateValuesInInheritedCollectionVars(
+ collection.variables,
+ collection._ref_id || collection.id,
+ collection.id,
+ true
+ ),
]
// Check if the current collection matches the target reference ID
@@ -1756,7 +1775,7 @@ function computeCollectionInheritedProps(
return {
auth: inheritedAuth,
headers: inheritedHeaders,
- variables: inheritedVariables,
+ ancestorVariables: parentVariables ?? [],
ancestorPreRequestScripts: parentPreRequestScripts,
ancestorTestScripts: parentTestScripts,
}
diff --git a/packages/hoppscotch-common/src/services/persistence/index.ts b/packages/hoppscotch-common/src/services/persistence/index.ts
index 7561f657f..714b0ca26 100644
--- a/packages/hoppscotch-common/src/services/persistence/index.ts
+++ b/packages/hoppscotch-common/src/services/persistence/index.ts
@@ -1112,7 +1112,20 @@ export class PersistenceService extends Service {
watchDebounced(
this.restTabService.persistableTabState,
async (newData) => {
- await Store.set(STORE_NAMESPACE, STORE_KEYS.REST_TABS, newData)
+ const result = await Store.set(
+ STORE_NAMESPACE,
+ STORE_KEYS.REST_TABS,
+ newData
+ )
+
+ // A failed write (e.g. QuotaExceededError) silently freezes the
+ // persisted state for every REST tab at the last write that fit.
+ if (E.isLeft(result)) {
+ console.error(
+ `Failed persisting ${STORE_KEYS.REST_TABS}:`,
+ result.left
+ )
+ }
},
{ debounce: 500, deep: true }
)
diff --git a/packages/hoppscotch-common/src/services/persistence/validation-schemas/__tests__/testRunnerResultCollection.spec.ts b/packages/hoppscotch-common/src/services/persistence/validation-schemas/__tests__/testRunnerResultCollection.spec.ts
new file mode 100644
index 000000000..a2adde879
--- /dev/null
+++ b/packages/hoppscotch-common/src/services/persistence/validation-schemas/__tests__/testRunnerResultCollection.spec.ts
@@ -0,0 +1,116 @@
+import { getDefaultRESTRequest } from "@hoppscotch/data"
+import { describe, expect, test } from "vitest"
+
+import { TestRunnerResultCollectionSchema } from "../index"
+
+// A HoppRESTRequest augmented with the runner-only result fields, as it lives
+// inside a persisted test-runner result collection.
+const makeRunnerRequest = (name: string) => ({
+ ...getDefaultRESTRequest(),
+ name,
+ type: "test-response" as const,
+ passedTests: 2,
+ failedTests: 1,
+ runnerRequestID: `rid-${name}`,
+ error: undefined,
+ isLoading: false,
+ renderResults: true,
+ testResults: {
+ tests: [],
+ expectResults: [],
+ description: "",
+ scriptError: false,
+ envDiff: {
+ global: { additions: [], updations: [], deletions: [] },
+ selected: { additions: [], updations: [], deletions: [] },
+ },
+ consoleEntries: [],
+ },
+})
+
+const makeResultCollection = () => ({
+ v: 12,
+ name: "Result Collection",
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ variables: [],
+ description: null,
+ preRequestScript: "",
+ testScript: "",
+ requests: [makeRunnerRequest("top")],
+ folders: [
+ {
+ v: 12,
+ name: "Nested",
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ variables: [],
+ description: null,
+ preRequestScript: "",
+ testScript: "",
+ requests: [makeRunnerRequest("nested")],
+ folders: [],
+ },
+ ],
+})
+
+describe("TestRunnerResultCollectionSchema", () => {
+ test("preserves runner result fields on requests through a persist round-trip", () => {
+ const parsed = TestRunnerResultCollectionSchema.safeParse(
+ makeResultCollection()
+ )
+
+ expect(parsed.success).toBe(true)
+ if (!parsed.success) return
+
+ const data = parsed.data as ReturnType<typeof makeResultCollection>
+ const topRequest = data.requests[0]
+
+ // The runner-only fields must survive (the bug was HoppRESTCollectionSchema
+ // stripping them, blanking restored results and JSON export).
+ expect(topRequest.passedTests).toBe(2)
+ expect(topRequest.failedTests).toBe(1)
+ expect(topRequest.runnerRequestID).toBe("rid-top")
+ expect(topRequest.testResults).toBeDefined()
+ expect(topRequest.testResults?.scriptError).toBe(false)
+
+ // ...and recursively for folder-nested requests.
+ const nestedRequest = data.folders[0].requests[0]
+ expect(nestedRequest.passedTests).toBe(2)
+ expect(nestedRequest.runnerRequestID).toBe("rid-nested")
+ expect(nestedRequest.testResults).toBeDefined()
+ })
+
+ test("migrates an older-version collection while keeping runner fields", () => {
+ // A v2 collection (pre-dates variables/preRequestScript/testScript). It must
+ // be migrated to the latest version — not rejected — and still keep the
+ // runner result fields on its requests.
+ const legacyCollection = {
+ v: 2,
+ name: "Legacy Collection",
+ auth: { authType: "inherit", authActive: true },
+ headers: [],
+ requests: [makeRunnerRequest("legacy")],
+ folders: [],
+ }
+
+ const parsed = TestRunnerResultCollectionSchema.safeParse(legacyCollection)
+
+ expect(parsed.success).toBe(true)
+ if (!parsed.success) return
+
+ const data = parsed.data as ReturnType<typeof makeResultCollection> & {
+ v: number
+ }
+
+ // Migrated up: version bumped and the newer collection fields were filled.
+ expect(data.v).toBeGreaterThan(2)
+ expect(data.variables).toBeDefined()
+ expect(data.preRequestScript).toBeDefined()
+
+ // ...and the runner result fields survived the migration.
+ expect(data.requests[0].passedTests).toBe(2)
+ expect(data.requests[0].runnerRequestID).toBe("rid-legacy")
+ expect(data.requests[0].testResults).toBeDefined()
+ })
+})
diff --git a/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts b/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts
index d9e3f694d..e8d9523ed 100644
--- a/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts
+++ b/packages/hoppscotch-common/src/services/persistence/validation-schemas/index.ts
@@ -487,6 +487,25 @@ const HoppTestResultSchema = z
})
.strict()
+const TestRunnerDatasetSchema = z
+ .object({
+ fileName: z.string(),
+ type: z.enum(["csv", "json"]),
+ rows: z.array(z.record(z.string(), z.string())),
+ })
+ .strict()
+
+const TestRunnerMetaSchema = z
+ .object({
+ totalRequests: z.number(),
+ completedRequests: z.number(),
+ totalTests: z.number(),
+ passedTests: z.number(),
+ failedTests: z.number(),
+ totalTime: z.number(),
+ })
+ .strict()
+
const HoppRESTResponseHeaderSchema = z
.object({
key: z.string(),
@@ -584,6 +603,41 @@ const validRestOperations = [
"requestVariables",
] as const
+// The runner-only result fields that live on a request inside a test-runner
+// result collection (`TestRunnerRequest`). All optional and lax — its only job
+// is to re-capture the fields `entityReference` strips during migration.
+const TestRunnerRequestResultFieldsSchema = z.object({
+ type: z.optional(z.literal("test-response")),
+ response: z.optional(z.nullable(HoppRESTResponseSchema)),
+ testResults: z.optional(z.nullable(HoppTestResultSchema)),
+ isLoading: z.optional(z.boolean()),
+ error: z.optional(z.string()),
+ renderResults: z.optional(z.boolean()),
+ passedTests: z.optional(z.number()),
+ failedTests: z.optional(z.number()),
+ runnerRequestID: z.optional(z.string()),
+})
+
+// Mirrors the collection's requests/folders tree, capturing only the runner
+// result fields on each request so it can be merged back onto the migrated
+// collection.
+const TestRunnerResultOverlaySchema: z.ZodType<unknown> = z.lazy(() =>
+ z.object({
+ requests: z.array(TestRunnerRequestResultFieldsSchema),
+ folders: z.array(TestRunnerResultOverlaySchema),
+ })
+)
+
+// A test-runner result collection: the version-migrated HoppCollection (via
+// entityReference, which strips runner fields) intersected with the overlay
+// that re-captures them. z.intersection element-wise-merges the two, so an
+// older-version persisted collection is still migrated AND the runner result
+// fields survive the round-trip.
+export const TestRunnerResultCollectionSchema = z.intersection(
+ HoppRESTCollectionSchema,
+ TestRunnerResultOverlaySchema
+)
+
export const REST_TAB_STATE_SCHEMA = z
.object({
lastActiveTabID: z.string(),
@@ -599,20 +653,34 @@ export const REST_TAB_STATE_SCHEMA = z
keepVariableValues: z.boolean(),
persistResponses: z.boolean(),
stopOnError: z.boolean(),
+ dataset: z.optional(TestRunnerDatasetSchema),
}),
status: z.enum(["idle", "running", "stopped", "error"]),
collection: HoppRESTCollectionSchema,
collectionType: z.enum(["my-collections", "team-collections"]),
collectionID: z.optional(z.string()),
- resultCollection: z.optional(HoppRESTCollectionSchema),
- testRunnerMeta: z.object({
- totalRequests: z.number(),
- completedRequests: z.number(),
- totalTests: z.number(),
- passedTests: z.number(),
- failedTests: z.number(),
- totalTime: z.number(),
- }),
+ resultCollection: z.optional(TestRunnerResultCollectionSchema),
+ iterationResults: z.optional(
+ z.array(
+ z
+ .object({
+ iteration: z.number(),
+ // Current builds persist no iterations at all (see
+ // `persistableTabState`); optional so states written by
+ // earlier builds still validate — and when they carry
+ // result trees, the runner fields survive the parse.
+ resultCollection: z.optional(
+ TestRunnerResultCollectionSchema
+ ),
+ meta: TestRunnerMetaSchema,
+ })
+ .strict()
+ )
+ ),
+ selectedIteration: z.optional(z.number()),
+ selectedRequestRefIds: z.optional(z.array(z.string())),
+ environmentName: z.optional(z.string()),
+ testRunnerMeta: TestRunnerMetaSchema,
request: z.nullable(entityReference(HoppRESTRequest)),
response: z.nullable(HoppRESTResponseSchema),
testResults: z.optional(z.nullable(HoppTestResultSchema)),
diff --git a/packages/hoppscotch-common/src/services/tab/rest.ts b/packages/hoppscotch-common/src/services/tab/rest.ts
index 884491e71..c420e5792 100644
--- a/packages/hoppscotch-common/src/services/tab/rest.ts
+++ b/packages/hoppscotch-common/src/services/tab/rest.ts
@@ -42,12 +42,39 @@ export class RESTTabService extends TabService<HoppTabDocument> {
}
if (tab.document.type === "test-runner") {
+ // Run results are deliberately not persisted: the collection schema
+ // strips `response`/`testResults`/counters so restored rows come back
+ // empty anyway, and per-iteration trees can blow the localStorage
+ // quota. The whole run is dropped; the tab restores ready to run.
return {
tabID: tab.id,
doc: {
...tab.document,
+ // The debounced persist fires during a run, so a tab killed
+ // mid-run would restore as "running". Normalize to "stopped",
+ // never "idle" — an idle runner tab auto-runs on mount.
+ status:
+ tab.document.status === "running"
+ ? ("stopped" as const)
+ : tab.document.status,
request: null,
response: null,
+ // Drop the run outright rather than half of it: an iteration
+ // list without its result trees restores a summary over an
+ // empty table.
+ resultCollection: undefined,
+ iterationResults: undefined,
+ selectedIteration: 0,
+ // Meaningless without the result rows it points into.
+ selectedRequestPath: undefined,
+ testRunnerMeta: {
+ totalRequests: 0,
+ completedRequests: 0,
+ totalTests: 0,
+ passedTests: 0,
+ failedTests: 0,
+ totalTime: 0,
+ },
},
}
}
diff --git a/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.ts b/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.ts
new file mode 100644
index 000000000..1157850de
--- /dev/null
+++ b/packages/hoppscotch-common/src/services/test-runner/__tests__/plan-collection.spec.ts
@@ -0,0 +1,239 @@
+import { afterEach, describe, expect, test, vi } from "vitest"
+
+// RequestRunner drags in the network/kernel stack; the plan walk never
+// touches it.
+vi.mock("~/helpers/RequestRunner", () => ({
+ captureInitialEnvironmentState: vi.fn(),
+ runTestRunnerRequest: vi.fn(),
+}))
+
+import { getService } from "~/modules/dioc"
+import { CurrentValueService } from "~/services/current-environment-value.service"
+import { SecretEnvironmentService } from "~/services/secret-environment.service"
+import { TestRunnerService } from "../test-runner.service"
+
+const currentValues = getService(CurrentValueService)
+const secretEnvs = getService(SecretEnvironmentService)
+const service = getService(TestRunnerService)
+
+// The value stores are module-scoped singletons — drop everything a test
+// stored so no state leaks into the next one.
+afterEach(() => {
+ currentValues.environments.clear()
+ secretEnvs.secretEnvironments.clear()
+})
+
+const planCollection = (collection: unknown, parentVariables: unknown[] = []) =>
+ (service as any).planCollection(
+ collection,
+ new Set<string>(),
+ false,
+ [],
+ [],
+ undefined,
+ undefined,
+ parentVariables
+ )
+
+const collectionVar = (key: string, currentValue = "") => ({
+ key,
+ currentValue,
+ initialValue: "",
+ secret: false,
+})
+
+const request = (name: string) => ({
+ name,
+ _ref_id: `req-${name}`,
+ method: "GET",
+ endpoint: "https://example.com",
+ headers: [],
+ params: [],
+ auth: { authType: "inherit", authActive: true },
+ preRequestScript: "",
+ testScript: "",
+})
+
+const node = (
+ ids: { refId?: string; id?: string },
+ variables: ReturnType<typeof collectionVar>[],
+ requests: ReturnType<typeof request>[] = [],
+ folders: unknown[] = []
+) => ({
+ v: 12,
+ _ref_id: ids.refId,
+ id: ids.id,
+ name: ids.refId ?? ids.id ?? "node",
+ folders,
+ requests,
+ headers: [],
+ variables,
+ auth: { authType: "inherit", authActive: true },
+ preRequestScript: "",
+ testScript: "",
+})
+
+const stored = (key: string, currentValue: string, varIndex: number) => ({
+ key,
+ currentValue,
+ varIndex,
+ isSecret: false,
+})
+
+describe("TestRunnerService.planCollection — inherited variable resolution", () => {
+ test("resolves each level's own variables under that level's ID", () => {
+ currentValues.addEnvironment("plan-c", [stored("A", "a-current", 0)])
+ currentValues.addEnvironment("plan-f", [stored("B", "b-current", 0)])
+
+ const tree = node(
+ { refId: "plan-c" },
+ [collectionVar("A")],
+ [],
+ [node({ refId: "plan-f" }, [collectionVar("B")], [request("leaf")])]
+ )
+
+ const [planned] = planCollection(tree)
+
+ // The index-collision guard: A (owned by the root) must never read B's
+ // storage slot at (plan-f, 0).
+ expect(planned.inheritedVariables).toEqual([
+ expect.objectContaining({ key: "A", currentValue: "a-current" }),
+ expect.objectContaining({ key: "B", currentValue: "b-current" }),
+ ])
+ })
+
+ test("falls back to the server id when _ref_id misses (team key scheme)", () => {
+ currentValues.addEnvironment("srv-1", [stored("T", "team-current", 0)])
+
+ const tree = node(
+ { refId: "regenerated-on-fetch", id: "srv-1" },
+ [collectionVar("T")],
+ [request("team-leaf")]
+ )
+
+ const [planned] = planCollection(tree)
+
+ expect(planned.inheritedVariables).toEqual([
+ expect.objectContaining({ key: "T", currentValue: "team-current" }),
+ ])
+ })
+
+ test("ancestor variables pass through pre-resolved; only the root's own raw list is resolved", () => {
+ currentValues.addEnvironment("plan-root", [stored("own", "own-current", 0)])
+ // A stored value under the root at the ancestor's merged index — the bug
+ // shape: re-resolving a merged array under the root ID would hand this
+ // value to the ancestor variable.
+ const ancestor = {
+ key: "anc",
+ currentValue: "anc-RESOLVED-UPSTREAM",
+ initialValue: "",
+ secret: false,
+ }
+
+ const tree = node(
+ { refId: "plan-root" },
+ [collectionVar("own")],
+ [request("root-leaf")]
+ )
+
+ const [planned] = planCollection(tree, [ancestor])
+
+ expect(planned.inheritedVariables[0]).toBe(ancestor)
+ expect(planned.inheritedVariables).toEqual([
+ expect.objectContaining({
+ key: "anc",
+ currentValue: "anc-RESOLVED-UPSTREAM",
+ }),
+ expect.objectContaining({ key: "own", currentValue: "own-current" }),
+ ])
+ })
+
+ // Secret values live in SecretEnvironmentService, not CurrentValueService;
+ // the plan walk must resolve them (showSecret) or every secret collection
+ // variable executes as "".
+ test("resolves secret variables from SecretEnvironmentService", () => {
+ secretEnvs.addSecretEnvironment("plan-sec", [
+ { key: "TOKEN", value: "plan-s3cret", varIndex: 1 },
+ ])
+ currentValues.addEnvironment("plan-sec", [
+ stored("plain", "plain-current", 0),
+ ])
+
+ const tree = node(
+ { refId: "plan-sec" },
+ [
+ collectionVar("plain"),
+ { key: "TOKEN", currentValue: "", initialValue: "", secret: true },
+ ],
+ [request("secret-leaf")]
+ )
+
+ const [planned] = planCollection(tree)
+
+ expect(planned.inheritedVariables).toEqual([
+ expect.objectContaining({ key: "plain", currentValue: "plain-current" }),
+ expect.objectContaining({ key: "TOKEN", currentValue: "plan-s3cret" }),
+ ])
+ })
+
+ test("resolves secret variables via the server-id fallback (team key scheme)", () => {
+ secretEnvs.addSecretEnvironment("srv-sec-1", [
+ { key: "TEAM_TOKEN", value: "team-s3cret", varIndex: 0 },
+ ])
+
+ const tree = node(
+ { refId: "regenerated-on-fetch-sec", id: "srv-sec-1" },
+ [{ key: "TEAM_TOKEN", currentValue: "", initialValue: "", secret: true }],
+ [request("team-secret-leaf")]
+ )
+
+ const [planned] = planCollection(tree)
+
+ expect(planned.inheritedVariables).toEqual([
+ expect.objectContaining({
+ key: "TEAM_TOKEN",
+ currentValue: "team-s3cret",
+ }),
+ ])
+ })
+})
+
+describe("TestRunnerService.getTestResultInfo — pass/fail counting", () => {
+ const count = (result: unknown) => (service as any).getTestResultInfo(result)
+
+ test("counts error-status expectations as failures", () => {
+ expect(
+ count({
+ expectResults: [
+ { status: "pass", message: "" },
+ { status: "fail", message: "" },
+ { status: "error", message: "" },
+ ],
+ tests: [],
+ })
+ ).toEqual({ passed: 1, failed: 2 })
+ })
+
+ test("counts a script error as one failure", () => {
+ expect(count({ scriptError: true, expectResults: [], tests: [] })).toEqual({
+ passed: 0,
+ failed: 1,
+ })
+ })
+
+ test("accumulates nested test blocks", () => {
+ expect(
+ count({
+ scriptError: false,
+ expectResults: [{ status: "pass", message: "" }],
+ tests: [
+ {
+ description: "",
+ expectResults: [{ status: "error", message: "" }],
+ tests: [],
+ },
+ ],
+ })
+ ).toEqual({ passed: 1, failed: 1 })
+ })
+})
diff --git a/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts b/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts
index d2e8f6052..5a92fac53 100644
--- a/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts
+++ b/packages/hoppscotch-common/src/services/test-runner/test-runner.service.ts
@@ -1,6 +1,7 @@
import {
HoppCollection,
HoppCollectionVariable,
+ Environment,
HoppRESTHeaders,
HoppRESTRequest,
} from "@hoppscotch/data"
@@ -8,24 +9,56 @@ import { Service } from "dioc"
import { hasActualScript } from "@hoppscotch/js-sandbox/scripting"
import * as E from "fp-ts/Either"
import { cloneDeep } from "lodash-es"
-import { nextTick, Ref } from "vue"
+import { Ref } from "vue"
import {
captureInitialEnvironmentState,
runTestRunnerRequest,
+ type InitialEnvironmentState,
} from "~/helpers/RequestRunner"
import {
HoppTestRunnerDocument,
+ TestRunnerMeta,
TestRunnerConfig,
} from "~/helpers/rest/document"
import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse"
import { HoppTestData, HoppTestResult } from "~/helpers/types/HoppTestResult"
import { HoppTab } from "../tab"
-import { populateValuesInInheritedCollectionVars } from "~/helpers/utils/inheritedCollectionVarTransformer"
+import { resolveInheritedVariables } from "~/helpers/utils/inheritedCollectionVarTransformer"
+import { datasetRowToTempVars } from "~/helpers/runner/dataset"
+import {
+ applyRunOrder,
+ getRequestSelectionID,
+} from "~/helpers/runner/selection"
+import { clearTemporaryVariables } from "~/helpers/runner/temp_envs"
+
+// Sentinel errors that unwind the runner: "Test execution stopped" is a user
+// cancel, "…stopped due to error" a stop-on-error halt. Both are normal
+// terminations, so unwinding catches must recognize either form.
+const STOP_SIGNAL_PREFIX = "Test execution stopped"
+const isStopSignal = (error: unknown): error is Error =>
+ error instanceof Error && error.message.startsWith(STOP_SIGNAL_PREFIX)
export type TestRunnerOptions = {
stopRef: Ref<boolean>
} & TestRunnerConfig
+/**
+ * One request resolved against its ancestry and bound to its slot in the
+ * result tree.
+ */
+type PlannedRequest = {
+ /** Selection ID — how the run sequence refers to this request. */
+ id: string
+ request: TestRunnerRequest
+ /** Owning collection/folder, for the test-script context. */
+ collection: HoppCollection
+ /** Folder names from the run root down to this request's parent. */
+ folderPath: string[]
+ inheritedVariables: HoppCollectionVariable[]
+ inheritedPreRequestScripts: string[]
+ inheritedTestScripts: string[]
+}
+
export type TestRunnerRequest = HoppRESTRequest & {
type: "test-response"
response?: HoppRESTResponse | null
@@ -35,6 +68,9 @@ export type TestRunnerRequest = HoppRESTRequest & {
renderResults?: boolean
passedTests: number
failedTests: number
+ runnerRequestID?: string
+ /** Folder names from the run root down to this request's parent. */
+ folderPath?: string[]
}
function delay(timeMS: number) {
@@ -50,16 +86,19 @@ function delay(timeMS: number) {
export class TestRunnerService extends Service {
public static readonly ID = "TEST_RUNNER_SERVICE"
- public runTests(
- tab: Ref<HoppTab<HoppTestRunnerDocument>>,
- collection: HoppCollection,
- options: TestRunnerOptions,
- ancestorPreRequestScripts: string[] = [],
- ancestorTestScripts: string[] = []
- ) {
- // Reset the result collection
- tab.value.document.status = "running"
- tab.value.document.resultCollection = {
+ private createEmptyMeta(): TestRunnerMeta {
+ return {
+ totalRequests: 0,
+ completedRequests: 0,
+ totalTests: 0,
+ passedTests: 0,
+ failedTests: 0,
+ totalTime: 0,
+ }
+ }
+
+ private createResultCollection(collection: HoppCollection): HoppCollection {
+ return {
v: collection.v,
id: collection.id,
name: collection.name,
@@ -72,27 +111,114 @@ export class TestRunnerService extends Service {
preRequestScript: collection.preRequestScript ?? "",
testScript: collection.testScript ?? "",
}
+ }
- this.runTestCollection(
+ private shouldRunRequest(
+ request: HoppRESTRequest,
+ path: number[],
+ selectedIDs: Set<string>,
+ selectionActive: boolean
+ ) {
+ return (
+ !selectionActive || selectedIDs.has(getRequestSelectionID(request, path))
+ )
+ }
+
+ private collectionHasSelectedRequest(
+ collection: HoppCollection,
+ parentPath: number[],
+ selectedIDs: Set<string>,
+ selectionActive: boolean
+ ): boolean {
+ if (!selectionActive) return true
+
+ return (
+ collection.requests.some((request, index) =>
+ this.shouldRunRequest(
+ request as HoppRESTRequest,
+ [...parentPath, index],
+ selectedIDs,
+ selectionActive
+ )
+ ) ||
+ collection.folders.some((folder, index) =>
+ this.collectionHasSelectedRequest(
+ folder,
+ [...parentPath, index],
+ selectedIDs,
+ selectionActive
+ )
+ )
+ )
+ }
+
+ public runTests(
+ tab: Ref<HoppTab<HoppTestRunnerDocument>>,
+ collection: HoppCollection,
+ options: TestRunnerOptions,
+ ancestorPreRequestScripts: string[] = [],
+ ancestorTestScripts: string[] = [],
+ // Pre-resolved under their owning collections; the run root's own
+ // variables stay raw on `collection.variables` for the plan walk.
+ ancestorVariables: HoppCollectionVariable[] = []
+ ) {
+ // `undefined` runs the full collection; an array runs that subset.
+ const selection = tab.value.document.selectedRequestRefIds
+ const selectionActive = Array.isArray(selection)
+ const selectedIDs = new Set(selection ?? [])
+
+ // A selection can resolve to zero requests: an explicitly empty array
+ // (the UI sends `undefined` for "run all"), or IDs that stopped resolving
+ // after a refetch. Fail loudly rather than report a successful empty run.
+ if (
+ selectionActive &&
+ !this.collectionHasSelectedRequest(collection, [], selectedIDs, true)
+ ) {
+ tab.value.document.status = "error"
+ console.error(
+ "[Test Runner] The request selection matches no requests in this " +
+ "collection. Provide at least one request that exists in the tree, " +
+ "or omit the selection to run the full collection."
+ )
+ return
+ }
+
+ // Reset the result collection
+ tab.value.document.status = "running"
+ tab.value.document.resultCollection = undefined
+ tab.value.document.iterationResults = []
+ tab.value.document.selectedIteration = 0
+ tab.value.document.testRunnerMeta = this.createEmptyMeta()
+ clearTemporaryVariables()
+
+ // One run per dataset row when a data file is attached; config.iterations
+ // only drives dataset-less runs (persisted/external state can diverge
+ // from the UI's lock).
+ const resolvedIterations = options.dataset?.rows.length
+ ? options.dataset.rows.length
+ : Math.max(1, Math.floor(Number(options.iterations)) || 1)
+
+ // The selection array doubles as the run order; anything it doesn't
+ // mention keeps collection order, after everything it does.
+ const runOrder = new Map((selection ?? []).map((id, index) => [id, index]))
+
+ this.runTestIterations(
tab,
collection,
options,
- [],
- undefined,
- undefined,
- [],
- undefined,
+ resolvedIterations,
+ selectedIDs,
+ selectionActive,
+ runOrder,
ancestorPreRequestScripts,
- ancestorTestScripts
+ ancestorTestScripts,
+ ancestorVariables
)
.then(() => {
tab.value.document.status = "stopped"
})
.catch((error) => {
- if (
- error instanceof Error &&
- error.message === "Test execution stopped"
- ) {
+ if (isStopSignal(error)) {
tab.value.document.status = "stopped"
} else {
tab.value.document.status = "error"
@@ -100,129 +226,272 @@ export class TestRunnerService extends Service {
}
})
.finally(() => {
- tab.value.document.status = "stopped"
+ if (tab.value.document.status !== "error") {
+ tab.value.document.status = "stopped"
+ }
})
}
- private async runTestCollection(
+ private async runTestIterations(
tab: Ref<HoppTab<HoppTestRunnerDocument>>,
collection: HoppCollection,
options: TestRunnerOptions,
- parentPath: number[] = [],
+ resolvedIterations: number,
+ selectedIDs: Set<string>,
+ selectionActive: boolean,
+ runOrder: Map<string, number>,
+ ancestorPreRequestScripts: string[] = [],
+ ancestorTestScripts: string[] = [],
+ ancestorVariables: HoppCollectionVariable[] = []
+ ) {
+ for (
+ let iterationIndex = 0;
+ iterationIndex < resolvedIterations;
+ iterationIndex++
+ ) {
+ if (options.stopRef?.value) {
+ tab.value.document.status = "stopped"
+ throw new Error("Test execution stopped")
+ }
+
+ if (!options.keepVariableValues) clearTemporaryVariables()
+
+ // Without persisted values the env stores are never written back
+ // mid-iteration, so one snapshot serves the whole iteration. With
+ // keepVariableValues on, each request re-captures (left undefined here).
+ const iterationEnvState = options.keepVariableValues
+ ? undefined
+ : captureInitialEnvironmentState()
+
+ const resultCollection = this.createResultCollection(collection)
+ const meta = this.createEmptyMeta()
+ // The UI locks the iteration count to the dataset length; if the two
+ // ever diverge, reuse the last row rather than read out of bounds.
+ const iterationVars = options.dataset?.rows.length
+ ? datasetRowToTempVars(
+ options.dataset.rows[
+ Math.min(iterationIndex, options.dataset.rows.length - 1)
+ ]
+ )
+ : []
+
+ tab.value.document.iterationResults?.push({
+ iteration: iterationIndex + 1,
+ resultCollection,
+ meta,
+ })
+ // `selectedIteration` is the iteration the user is VIEWING — owned by
+ // the jump control and scroll tracking, not the run. Advancing it here
+ // left a finished run's counter parked on the last iteration while the
+ // viewport still showed the first.
+ tab.value.document.resultCollection = resultCollection
+
+ // Read the collection back off the document: the assignment above stores
+ // the raw object, and mutating a raw object never notifies Vue — rows
+ // must be appended through the reactive view.
+ const liveResultCollection = tab.value.document.resultCollection!
+
+ const orderedPlan = applyRunOrder(
+ this.planCollection(
+ collection,
+ selectedIDs,
+ selectionActive,
+ [],
+ [],
+ undefined,
+ undefined,
+ ancestorVariables,
+ ancestorPreRequestScripts,
+ ancestorTestScripts
+ ),
+ runOrder
+ )
+
+ // Results are a flat list in run order; each row carries its folder
+ // path instead of nesting back under folders.
+ orderedPlan.forEach((entry) =>
+ this.addRequestToPath(liveResultCollection, [], {
+ ...cloneDeep(entry.request),
+ runnerRequestID: entry.id,
+ folderPath: entry.folderPath,
+ passedTests: 0,
+ failedTests: 0,
+ })
+ )
+
+ tab.value.document.testRunnerMeta.totalRequests += orderedPlan.length
+ meta.totalRequests += orderedPlan.length
+
+ await this.runPlan(
+ tab,
+ orderedPlan,
+ options,
+ meta,
+ iterationVars,
+ iterationEnvState
+ )
+ }
+ }
+
+ /**
+ * Walks the collection and returns the requests to run, each with inherited
+ * auth/headers/variables/scripts resolved against its own ancestry.
+ *
+ * Planning is separate from execution so the run sequence can reorder
+ * across folders; result slots are allocated after ordering so results
+ * read in executed order.
+ */
+ private planCollection(
+ collection: HoppCollection,
+ selectedIDs: Set<string>,
+ selectionActive: boolean,
+ sourceParentPath: number[] = [],
+ folderPath: string[] = [],
parentHeaders?: HoppRESTHeaders,
parentAuth?: HoppRESTRequest["auth"],
parentVariables: HoppCollection["variables"] = [],
- parentID?: string,
parentPreRequestScripts: string[] = [],
parentTestScripts: string[] = []
- ) {
- try {
- // Compute inherited auth and headers for this collection
- const inheritedAuth =
- collection.auth?.authType === "inherit" && collection.auth.authActive
- ? parentAuth || { authType: "none", authActive: false }
- : collection.auth || { authType: "none", authActive: false }
-
- const inheritedHeaders: HoppRESTHeaders = [
- ...(parentHeaders || []),
- ...collection.headers,
- ]
-
- const inheritedVariables = [
- ...(populateValuesInInheritedCollectionVars(
- parentVariables,
- parentID || collection._ref_id || collection.id
- ) || []),
- ...(populateValuesInInheritedCollectionVars(
- collection.variables,
- collection._ref_id || collection.id
- ) || []),
- ]
-
- const inheritedPreRequestScripts = [
- ...parentPreRequestScripts,
- ...(hasActualScript(collection.preRequestScript)
- ? [collection.preRequestScript]
- : []),
- ]
- const inheritedTestScripts = [
- ...parentTestScripts,
- ...(hasActualScript(collection.testScript)
- ? [collection.testScript]
- : []),
- ]
-
- // Process folders progressively
- for (let i = 0; i < collection.folders.length; i++) {
- if (options.stopRef?.value) {
- tab.value.document.status = "stopped"
- throw new Error("Test execution stopped")
- }
+ ): PlannedRequest[] {
+ const inheritedAuth =
+ collection.auth?.authType === "inherit" && collection.auth.authActive
+ ? parentAuth || { authType: "none", authActive: false }
+ : collection.auth || { authType: "none", authActive: false }
+
+ const inheritedHeaders: HoppRESTHeaders = [
+ ...(parentHeaders || []),
+ ...collection.headers,
+ ]
+
+ // Parents pass through already resolved; only this collection's own
+ // variables are populated here, under its own ID. The server `id`
+ // fallback mirrors the save-side keying for team collections, whose
+ // `_ref_id` is regenerated on every fetch. `showSecret` is true because
+ // this feeds execution only — planned requests are never persisted.
+ const inheritedVariables = resolveInheritedVariables(
+ parentVariables,
+ collection.variables,
+ collection._ref_id || collection.id,
+ collection.id,
+ true
+ )
- const folder = collection.folders[i]
- const currentPath = [...parentPath, i]
-
- // Add folder to the result collection
- this.addFolderToPath(
- tab.value.document.resultCollection!,
- currentPath,
- {
- ...cloneDeep(folder),
- folders: [],
- requests: [],
- }
+ const inheritedPreRequestScripts = [
+ ...parentPreRequestScripts,
+ ...(hasActualScript(collection.preRequestScript)
+ ? [collection.preRequestScript]
+ : []),
+ ]
+ const inheritedTestScripts = [
+ ...parentTestScripts,
+ ...(hasActualScript(collection.testScript)
+ ? [collection.testScript]
+ : []),
+ ]
+
+ const planned: PlannedRequest[] = []
+
+ // Folders (depth-first) before a node's own requests — must match
+ // `collectRequestIDs` and the run-sequence UI's flatten.
+ for (let i = 0; i < collection.folders.length; i++) {
+ const folder = collection.folders[i]
+ const sourcePath = [...sourceParentPath, i]
+
+ if (
+ !this.collectionHasSelectedRequest(
+ folder,
+ sourcePath,
+ selectedIDs,
+ selectionActive
)
+ ) {
+ continue
+ }
- await this.runTestCollection(
- tab,
+ planned.push(
+ ...this.planCollection(
folder,
- options,
- currentPath,
+ selectedIDs,
+ selectionActive,
+ sourcePath,
+ [...folderPath, folder.name],
inheritedHeaders,
inheritedAuth,
inheritedVariables,
- collection._ref_id || collection.id,
inheritedPreRequestScripts,
inheritedTestScripts
)
- }
-
- // Process requests progressively
- for (let i = 0; i < collection.requests.length; i++) {
- if (options.stopRef?.value) {
- tab.value.document.status = "stopped"
- throw new Error("Test execution stopped")
- }
+ )
+ }
- const request = collection.requests[i] as TestRunnerRequest
- const currentPath = [...parentPath, i]
+ for (let i = 0; i < collection.requests.length; i++) {
+ const request = collection.requests[i] as TestRunnerRequest
+ const sourcePath = [...sourceParentPath, i]
- // Add request to the result collection before execution
- this.addRequestToPath(
- tab.value.document.resultCollection!,
- currentPath,
- cloneDeep(request)
+ if (
+ !this.shouldRunRequest(
+ request,
+ sourcePath,
+ selectedIDs,
+ selectionActive
)
+ ) {
+ continue
+ }
- // Update the request with inherited headers and auth before execution
- const finalRequest = {
+ planned.push({
+ id: getRequestSelectionID(request, sourcePath),
+ request: {
...request,
auth:
request.auth.authType === "inherit" && request.auth.authActive
? inheritedAuth
: request.auth,
headers: [...inheritedHeaders, ...request.headers],
+ },
+ collection,
+ folderPath,
+ inheritedVariables,
+ inheritedPreRequestScripts,
+ inheritedTestScripts,
+ })
+ }
+
+ return planned
+ }
+
+ /**
+ * Runs a plan in the given order, which is the user's run sequence when they
+ * set one and plain collection order otherwise.
+ */
+ private async runPlan(
+ tab: Ref<HoppTab<HoppTestRunnerDocument>>,
+ plan: PlannedRequest[],
+ options: TestRunnerOptions,
+ iterationMeta: TestRunnerMeta,
+ iterationVars: Environment["variables"],
+ iterationEnvState?: InitialEnvironmentState
+ ) {
+ try {
+ for (const [index, entry] of plan.entries()) {
+ if (options.stopRef?.value) {
+ tab.value.document.status = "stopped"
+ throw new Error("Test execution stopped")
}
await this.runTestRequest(
tab,
- finalRequest,
- collection,
+ entry.request,
+ entry.collection,
options,
- currentPath,
- inheritedVariables,
- inheritedPreRequestScripts,
- inheritedTestScripts
+ // Result rows are allocated in this same order: plan index = row.
+ [index],
+ iterationMeta,
+ iterationVars,
+ entry.inheritedVariables,
+ entry.inheritedPreRequestScripts,
+ entry.inheritedTestScripts,
+ iterationEnvState
)
if (options.delay && options.delay > 0) {
@@ -237,10 +506,7 @@ export class TestRunnerService extends Service {
}
}
} catch (error) {
- if (
- error instanceof Error &&
- error.message === "Test execution stopped"
- ) {
+ if (isStopSignal(error)) {
throw error
}
tab.value.document.status = "error"
@@ -249,40 +515,20 @@ export class TestRunnerService extends Service {
}
}
- private addFolderToPath(
- collection: HoppCollection,
- path: number[],
- folder: HoppCollection
- ) {
- let current = collection
-
- // Navigate to the parent folder
- for (let i = 0; i < path.length - 1; i++) {
- current = current.folders[path[i]]
- }
-
- // Add the folder at the specified index
- if (path.length > 0) {
- current.folders[path[path.length - 1]] = folder
- }
- }
-
private addRequestToPath(
collection: HoppCollection,
- path: number[],
+ parentPath: number[],
request: TestRunnerRequest
) {
let current = collection
// Navigate to the parent folder
- for (let i = 0; i < path.length - 1; i++) {
- current = current.folders[path[i]]
+ for (let i = 0; i < parentPath.length; i++) {
+ current = current.folders[parentPath[i]]
}
- // Add the request at the specified index
- if (path.length > 0) {
- current.requests[path[path.length - 1]] = request
- }
+ current.requests.push(request)
+ return current.requests.length - 1
}
private updateRequestAtPath(
@@ -297,13 +543,13 @@ export class TestRunnerService extends Service {
current = current.folders[path[i]]
}
- // Update the request at the specified index
+ // Mutate in place: selecting a request stores a reference to this object
+ // on the tab (`document.request`); replacing it would orphan that
+ // reference and the response would never reach the selected view.
if (path.length > 0) {
const index = path[path.length - 1]
- current.requests[index] = {
- ...current.requests[index],
- ...updates,
- } as TestRunnerRequest
+ const target = current.requests[index]
+ if (target) Object.assign(target, updates)
}
}
@@ -313,9 +559,12 @@ export class TestRunnerService extends Service {
collection: HoppCollection,
options: TestRunnerOptions,
path: number[],
+ iterationMeta: TestRunnerMeta,
+ iterationVars: Environment["variables"],
inheritedVariables: HoppCollectionVariable[] = [],
inheritedPreRequestScripts: string[] = [],
- inheritedTestScripts: string[] = []
+ inheritedTestScripts: string[] = [],
+ iterationEnvState?: InitialEnvironmentState
) {
if (options.stopRef?.value) {
throw new Error("Test execution stopped")
@@ -328,14 +577,11 @@ export class TestRunnerService extends Service {
error: undefined,
})
- // Force Vue to flush DOM updates before starting async work.
- // This ensures components consuming the isLoading state (such as those rendering the Send/Cancel button) update immediately.
- // Performance impact: nextTick() waits for microtask queue drain (actual latency varies based on pending microtasks)
- // but is necessary to prevent UI flicker and ensure loading indicators appear before long-running network requests.
- await nextTick()
-
- // Capture the initial environment state for a test run so that it remains consistent and unchanged when current environment changes
- const initialEnvironmentState = captureInitialEnvironmentState()
+ // Reuse the per-iteration snapshot when variable values aren't
+ // persisted; otherwise re-capture so this request sees env changes
+ // persisted by earlier requests in the run.
+ const initialEnvironmentState =
+ iterationEnvState ?? captureInitialEnvironmentState()
const results = await runTestRunnerRequest(
request,
@@ -343,10 +589,16 @@ export class TestRunnerService extends Service {
inheritedVariables,
initialEnvironmentState,
inheritedPreRequestScripts,
- inheritedTestScripts
+ inheritedTestScripts,
+ iterationVars
)
if (options.stopRef?.value) {
+ // Clear the loading flag so a stop taken mid-flight doesn't leave a
+ // permanent spinner on the row.
+ this.updateRequestAtPath(tab.value.document.resultCollection!, path, {
+ isLoading: false,
+ })
throw new Error("Test execution stopped")
}
@@ -357,11 +609,16 @@ export class TestRunnerService extends Service {
tab.value.document.testRunnerMeta.totalTests += passed + failed
tab.value.document.testRunnerMeta.passedTests += passed
tab.value.document.testRunnerMeta.failedTests += failed
+ iterationMeta.totalTests += passed + failed
+ iterationMeta.passedTests += passed
+ iterationMeta.failedTests += failed
// Update request with results and propagate pre-request script changes in the result collection
this.updateRequestAtPath(tab.value.document.resultCollection!, path, {
...updatedRequest,
testResults: testResult,
+ passedTests: passed,
+ failedTests: failed,
response: options.persistResponses ? response : null,
isLoading: false,
})
@@ -370,6 +627,16 @@ export class TestRunnerService extends Service {
tab.value.document.testRunnerMeta.totalTime +=
response.meta.responseDuration
tab.value.document.testRunnerMeta.completedRequests += 1
+ iterationMeta.totalTime += response.meta.responseDuration
+ iterationMeta.completedRequests += 1
+ }
+
+ // A post-request script failure arrives as a Right with `scriptError`
+ // set, so the Left/stop-on-error branch below never sees it. Halt
+ // here after the row and meta have recorded the request.
+ if (options.stopOnError && testResult.scriptError) {
+ tab.value.document.status = "stopped"
+ throw new Error("Test execution stopped due to error")
}
} else {
const errorMsg = "Request execution failed"
@@ -391,10 +658,7 @@ export class TestRunnerService extends Service {
}
}
} catch (error) {
- if (
- error instanceof Error &&
- error.message === "Test execution stopped"
- ) {
+ if (isStopSignal(error)) {
throw error
}
@@ -414,14 +678,17 @@ export class TestRunnerService extends Service {
}
}
- private getTestResultInfo(testResult: HoppTestData) {
+ private getTestResultInfo(testResult: HoppTestData | HoppTestResult) {
let passed = 0
- let failed = 0
+ // A failed script means the request's assertions never ran — count it as
+ // one failure so the meta counters and the run outcome reflect it.
+ // (`scriptError` exists only on the top-level `HoppTestResult`.)
+ let failed = "scriptError" in testResult && testResult.scriptError ? 1 : 0
for (const result of testResult.expectResults) {
if (result.status === "pass") {
passed++
- } else if (result.status === "fail") {
+ } else if (result.status === "fail" || result.status === "error") {
failed++
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 32760ebc2..a8deae90c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -709,6 +709,9 @@ importers:
paho-mqtt:
specifier: 1.1.0
version: 1.1.0
+ papaparse:
+ specifier: 5.5.4
+ version: 5.5.4
path:
specifier: 0.12.7
version: 0.12.7
@@ -884,6 +887,9 @@ importers:
'@types/paho-mqtt':
specifier: 1.0.10
version: 1.0.10
+ '@types/papaparse':
+ specifier: 5.5.2
+ version: 5.5.2
'@types/postman-collection':
specifier: 3.5.11
version: 3.5.11